prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>GetTag.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
###############################################################################
#
# GetTag
# Retrieves a specified tag object.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo 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.
#
#
###############################################################################
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class GetTag(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the GetTag Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(GetTag, self).__init__(temboo_session, '/Library/GitHub/GitDataAPI/Tags/GetTag')
def new_input_set(self):
return GetTagInputSet()
def _make_result_set(self, result, path):
return GetTagResultSet(result, path)
def _make_execution(self, session, exec_id, path):<|fim▁hole|>class GetTagInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the GetTag
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_AccessToken(self, value):
"""
Set the value of the AccessToken input for this Choreo. ((conditional, string) The Access Token retrieved during the OAuth process. Required when accessing a protected resource.)
"""
super(GetTagInputSet, self)._set_input('AccessToken', value)
def set_Repo(self, value):
"""
Set the value of the Repo input for this Choreo. ((required, string) The name of the repo associated with the tag to retrieve.)
"""
super(GetTagInputSet, self)._set_input('Repo', value)
def set_SHA(self, value):
"""
Set the value of the SHA input for this Choreo. ((required, string) The SHA associated with the tag to retrieve.)
"""
super(GetTagInputSet, self)._set_input('SHA', value)
def set_User(self, value):
"""
Set the value of the User input for this Choreo. ((required, string) The GitHub username.)
"""
super(GetTagInputSet, self)._set_input('User', value)
class GetTagResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the GetTag Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from GitHub.)
"""
return self._output.get('Response', None)
def get_Limit(self):
"""
Retrieve the value for the "Limit" output from this Choreo execution. ((integer) The available rate limit for your account. This is returned in the GitHub response header.)
"""
return self._output.get('Limit', None)
def get_Remaining(self):
"""
Retrieve the value for the "Remaining" output from this Choreo execution. ((integer) The remaining number of API requests available to you. This is returned in the GitHub response header.)
"""
return self._output.get('Remaining', None)
class GetTagChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return GetTagResultSet(response, path)<|fim▁end|> | return GetTagChoreographyExecution(session, exec_id, path)
|
<|file_name|>throttle.go<|end_file_name|><|fim▁begin|>/*
Copyright 2012 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 throttle provides a net.Listener that returns
// artificially-delayed connections for testing real-world
// connectivity.
package throttle
import (
"fmt"
"net"
"sync"
"time"
)
const unitSize = 1400 // read/write chunk size. ~MTU size.
type Rate struct {
KBps int // or 0, to not rate-limit bandwidth
Latency time.Duration
}
// byteTime returns the time required for n bytes.
func (r Rate) byteTime(n int) time.Duration {
if r.KBps == 0 {
return 0
}
return time.Duration(float64(n)/1024/float64(r.KBps)) * time.Second
}
type Listener struct {
net.Listener
Down Rate // server Writes to Client
Up Rate // server Reads from client
}
func (ln *Listener) Accept() (net.Conn, error) {
c, err := ln.Listener.Accept()
time.Sleep(ln.Up.Latency)
if err != nil {
return nil, err
}
tc := &conn{Conn: c, Down: ln.Down, Up: ln.Up}<|fim▁hole|>}
type nErr struct {
n int
err error
}
type writeReq struct {
writeAt time.Time
p []byte
resc chan nErr
}
type conn struct {
net.Conn
Down Rate // for reads
Up Rate // for writes
wchan chan writeReq
closeOnce sync.Once
closeErr error
}
func (c *conn) start() {
c.wchan = make(chan writeReq, 1024)
go c.writeLoop()
}
func (c *conn) writeLoop() {
for req := range c.wchan {
time.Sleep(req.writeAt.Sub(time.Now()))
var res nErr
for len(req.p) > 0 && res.err == nil {
writep := req.p
if len(writep) > unitSize {
writep = writep[:unitSize]
}
n, err := c.Conn.Write(writep)
time.Sleep(c.Up.byteTime(len(writep)))
res.n += n
res.err = err
req.p = req.p[n:]
}
req.resc <- res
}
}
func (c *conn) Close() error {
c.closeOnce.Do(func() {
err := c.Conn.Close()
close(c.wchan)
c.closeErr = err
})
return c.closeErr
}
func (c *conn) Write(p []byte) (n int, err error) {
defer func() {
if e := recover(); e != nil {
n = 0
err = fmt.Errorf("%v", err)
return
}
}()
resc := make(chan nErr, 1)
c.wchan <- writeReq{time.Now().Add(c.Up.Latency), p, resc}
res := <-resc
return res.n, res.err
}
func (c *conn) Read(p []byte) (n int, err error) {
const max = 1024
if len(p) > max {
p = p[:max]
}
n, err = c.Conn.Read(p)
time.Sleep(c.Down.byteTime(n))
return
}<|fim▁end|> | tc.start()
return tc, nil |
<|file_name|>aws-cloudfront.go<|end_file_name|><|fim▁begin|>package mpawscloudfront
import (
"errors"
"flag"
"log"
"os"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatch"
mp "github.com/mackerelio/go-mackerel-plugin"
)
const (
namespace = "AWS/CloudFront"
region = "us-east-1"
metricsTypeAverage = "Average"
metricsTypeSum = "Sum"
)
var graphdef = map[string]mp.Graphs{
"cloudfront.Requests": {
Label: "CloudFront Requests",
Unit: "integer",
Metrics: []mp.Metrics{
{Name: "Requests", Label: "Requests"},
},
},
"cloudfront.Transfer": {
Label: "CloudFront Transfer",
Unit: "bytes",
Metrics: []mp.Metrics{
{Name: "BytesDownloaded", Label: "Download", Stacked: true},
{Name: "BytesUploaded", Label: "Upload", Stacked: true},
},
},
"cloudfront.ErrorRate": {
Label: "CloudFront ErrorRate",
Unit: "percentage",
Metrics: []mp.Metrics{
{Name: "4xxErrorRate", Label: "4xx", Stacked: true},
{Name: "5xxErrorRate", Label: "5xx", Stacked: true},
},
},
}
type metrics struct {
Name string
Type string
}
// CloudFrontPlugin mackerel plugin for cloudfront
type CloudFrontPlugin struct {
AccessKeyID string
SecretAccessKey string
CloudWatch *cloudwatch.CloudWatch
Name string
}
func (p *CloudFrontPlugin) prepare() error {
sess, err := session.NewSession()
if err != nil {
return err
}
config := aws.NewConfig()
if p.AccessKeyID != "" && p.SecretAccessKey != "" {
config = config.WithCredentials(credentials.NewStaticCredentials(p.AccessKeyID, p.SecretAccessKey, ""))
}
config = config.WithRegion(region)
p.CloudWatch = cloudwatch.New(sess, config)
return nil
}
func (p CloudFrontPlugin) getLastPoint(metric metrics) (float64, error) {
now := time.Now()
dimensions := []*cloudwatch.Dimension{
{
Name: aws.String("DistributionId"),
Value: aws.String(p.Name),
},
{
Name: aws.String("Region"),
Value: aws.String("Global"),
},
}
response, err := p.CloudWatch.GetMetricStatistics(&cloudwatch.GetMetricStatisticsInput{
Dimensions: dimensions,
StartTime: aws.Time(now.Add(time.Duration(180) * time.Second * -1)), // 3 min (to fetch at least 1 data-point)
EndTime: aws.Time(now),
MetricName: aws.String(metric.Name),
Period: aws.Int64(60),
Statistics: []*string{aws.String(metric.Type)},
Namespace: aws.String(namespace),
})
if err != nil {
return 0, err
}
datapoints := response.Datapoints
if len(datapoints) == 0 {
return 0, errors.New("fetched no datapoints")
}
// get a least recently datapoint
// because a most recently datapoint is not stable.
least := time.Now()
var latestVal float64
for _, dp := range datapoints {
if dp.Timestamp.Before(least) {
least = *dp.Timestamp
if metric.Type == metricsTypeAverage {
latestVal = *dp.Average
} else if metric.Type == metricsTypeSum {
latestVal = *dp.Sum
}
}
}
return latestVal, nil
}
// FetchMetrics fetch the metrics
func (p CloudFrontPlugin) FetchMetrics() (map[string]float64, error) {
stat := make(map[string]float64)<|fim▁hole|> {Name: "BytesUploaded", Type: metricsTypeSum},
{Name: "4xxErrorRate", Type: metricsTypeAverage},
{Name: "5xxErrorRate", Type: metricsTypeAverage},
} {
v, err := p.getLastPoint(met)
if err == nil {
stat[met.Name] = v
} else {
log.Printf("%s: %s", met, err)
}
}
return stat, nil
}
// GraphDefinition of CloudFrontPlugin
func (p CloudFrontPlugin) GraphDefinition() map[string]mp.Graphs {
return graphdef
}
// Do the plugin
func Do() {
optAccessKeyID := flag.String("access-key-id", "", "AWS Access Key ID")
optSecretAccessKey := flag.String("secret-access-key", "", "AWS Secret Access Key")
optIdentifier := flag.String("identifier", "", "Distribution ID")
optTempfile := flag.String("tempfile", "", "Temp file name")
flag.Parse()
var plugin CloudFrontPlugin
plugin.AccessKeyID = *optAccessKeyID
plugin.SecretAccessKey = *optSecretAccessKey
plugin.Name = *optIdentifier
err := plugin.prepare()
if err != nil {
log.Fatalln(err)
}
helper := mp.NewMackerelPlugin(plugin)
helper.Tempfile = *optTempfile
if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
helper.OutputDefinitions()
} else {
helper.OutputValues()
}
}<|fim▁end|> |
for _, met := range [...]metrics{
{Name: "Requests", Type: metricsTypeSum},
{Name: "BytesDownloaded", Type: metricsTypeSum}, |
<|file_name|>maketopo.py<|end_file_name|><|fim▁begin|>"""
Module to create topo and qinit data files for this example.
"""
from clawpack.geoclaw import topotools
from pylab import *
def maketopo_hilo():
x = loadtxt('x.txt')
y = loadtxt('y.txt')
z = loadtxt('z.txt')
# modify x and y so that cell size is truly uniform:
dx = 1. / (3.*3600.) # 1/3"
xx = linspace(x[0], x[-1], len(x))
yy = linspace(y[-1], y[0], len(y))
zz = flipud(z)
<|fim▁hole|> topo.Z = zz
topo.write('hilo_flattened.tt2',topo_type=2)
def maketopo_flat():
"""
Output topography file for the entire domain
"""
nxpoints = 201
nypoints = 301
xlower = 204.812
xupper = 205.012
ylower = 19.7
yupper = 20.0
outfile= "flat.tt2"
topotools.topo2writer(outfile,topo_flat,xlower,xupper,ylower,yupper,nxpoints,nypoints)
def topo_flat(x,y):
"""
flat
"""
z = where(x < 204.91213, 30., -30.)
return z
def plot_topo_big():
figure(figsize=(8,12))
topo1 = topotools.Topography()
topo1.read('flat.tt2',2)
contourf(topo1.x,topo1.y,topo1.Z,linspace(-30,20,51), extend='both')
topo2 = topotools.Topography()
topo2.read('hilo_flattened.tt2',2)
contourf(topo2.x,topo2.y,topo2.Z,linspace(-30,20,51), extend='both')
x1 = 204.90028
x2 = 204.96509
y1 = 19.71
y2 = 19.95
plot([x1,x2,x2,x1,x1],[y1,y1,y2,y2,y1],'w')
axis('scaled')
colorbar()
def plot_topo():
figure(figsize=(12,8))
topo1 = topotools.Topography()
topo1.read('flat.tt2',2)
contourf(topo1.x,topo1.y,topo1.Z,linspace(-30,20,51), extend='both')
topo2 = topotools.Topography()
topo2.read('hilo_flattened.tt2',2)
contourf(topo2.x,topo2.y,topo2.Z,linspace(-30,20,51), extend='both')
colorbar()
x1 = 204.9
x2 = 204.955
y1 = 19.715
y2 = 19.755
axis([x1,x2,y1,y2])
gca().set_aspect(1./cos(y1*pi/180.))
ticklabel_format(format='plain',useOffset=False)
contour(topo2.x,topo2.y,topo2.Z,[0.],colors='k')
plot([204.9447],[19.7308], 'ko') # from BM description
plot([204.9437],[19.7307], 'ro') # closer to pier
# from <http://tidesandcurrents.noaa.gov/stationhome.html?id=1617760>
# location is listed as: 19 degrees 43.8' N, 155 degrees, 3.3' W
xg = 360 - (155 + 3.3/60.)
yg = 19 + 43.8/60.
plot([xg],[yg], 'bo')
#gauges.append([1125, 204.91802, 19.74517, 0., 1.e9]) #Hilo
#gauges.append([1126, 204.93003, 19.74167, 0., 1.e9]) #Hilo
#gauges.append([3333, 204.93, 19.7576, 0., 1.e9])
if __name__=='__main__':
maketopo_hilo()
maketopo_flat()<|fim▁end|> | topo = topotools.Topography()
topo.x = xx
topo.y = yy |
<|file_name|>uibmodalinstance.ts<|end_file_name|><|fim▁begin|>import type { Mock } from "mocks/types";
import type { UibModalInstanceMock } from "mocks/node-modules/angular/types";
import sinon from "sinon";<|fim▁hole|>
export default class UibModalInstanceMockProvider implements Mock<UibModalInstanceMock> {
// Mock $uibModalInstance object
public constructor(private readonly $uibModalInstance: UibModalInstanceMock = {
close: sinon.stub(),
dismiss: sinon.stub()
}) {}
public $get(): UibModalInstanceMock {
return this.$uibModalInstance;
}
}
UibModalInstanceMockProvider.$inject = [];<|fim▁end|> | |
<|file_name|>test_servlet_newpush.py<|end_file_name|><|fim▁begin|>from contextlib import nested
from contextlib import contextmanager
import mock
import testing as T
import types
from core import db
from core.settings import Settings
from core.mail import MailQueue
from core.util import get_servlet_urlspec
from core.xmppclient import XMPPQueue
import servlets.newpush
from servlets.newpush import NewPushServlet
from servlets.newpush import send_notifications
class NewPushServletTest(T.TestCase, T.ServletTestMixin):
def get_handlers(self):
return [get_servlet_urlspec(NewPushServlet)]
def test_newpush(self):
pushes = []
def on_db_return(success, db_results):
assert success
pushes.extend(db_results.fetchall())
with nested(
mock.patch.dict(db.Settings, T.MockedSettings),
mock.patch.object(NewPushServlet, "get_current_user", return_value = "jblack"),
mock.patch.object(NewPushServlet, "redirect"),
mock.patch.object(MailQueue, "enqueue_user_email"),
):
with mock.patch("%s.servlets.newpush.subprocess.call" % __name__) as mocked_call:
title = "BestPushInTheWorld"
branch = "jblack"
push_type = "regular"
uri = "/newpush?push-title=%s&branch=%s&push-type=%s" % (
title, branch, push_type
)
pushes = []
db.execute_cb(db.push_pushes.select(), on_db_return)
num_pushes_before = len(pushes)
response = self.fetch(uri)
assert response.error == None
pushes = []
db.execute_cb(db.push_pushes.select(), on_db_return)
num_pushes_after = len(pushes)
T.assert_equal(num_pushes_before + 1, num_pushes_after)
# There should be one call to nodebot after a push is created
T.assert_equal(servlets.newpush.subprocess.call.call_count, 1)
# Verify that we have a valid call to
# subprocess.call. Getting the arguments involves ugly
# mock magic
mocked_call.assert_called_once_with([
'/nail/sys/bin/nodebot',
'-i',
mock.ANY, # nickname
mock.ANY, # channel
mock.ANY, # msg
])
def call_on_db_complete(self, urgent=False):
mocked_self = mock.Mock()
mocked_self.check_db_results = mock.Mock(return_value=None)
mocked_self.redirect = mock.Mock(return_value=None)
mocked_self.pushtype = 'normal'
mocked_self.on_db_complete = types.MethodType(NewPushServlet.on_db_complete.im_func, mocked_self)
push = mock.Mock()
push.lastrowid = 0
no_watcher_req = {
'user': 'testuser',
'watchers': None,
}
watched_req = {
'user': 'testuser',
'watchers': 'testuser1,testuser2',
}
if urgent:
no_watcher_req['tags'] = 'urgent'
watched_req['tags'] = 'urgent'
mocked_self.pushtype = 'urgent'
reqs = [no_watcher_req, watched_req]
mocked_self.on_db_complete('success', [push, reqs])
@mock.patch('servlets.newpush.send_notifications')
def test_normal_people_on_db_complete(self, notify):
self.call_on_db_complete()
notify.called_once_with(set(['testuser', 'testuser1', 'testuser2']), mock.ANY, mock.ANY)
@mock.patch('servlets.newpush.send_notifications')
def test_urgent_people_on_db_complete(self, notify):
self.call_on_db_complete(urgent=True)
notify.called_once_with(set(['testuser', 'testuser1', 'testuser2']), mock.ANY, mock.ANY)
class NotificationsTestCase(T.TestCase):
@contextmanager
def mocked_notifications(self):
with mock.patch("%s.servlets.newpush.subprocess.call" % __name__) as mocked_call:
with mock.patch.object(MailQueue, "enqueue_user_email") as mocked_mail:
with mock.patch.object(XMPPQueue, "enqueue_user_xmpp") as mocked_xmpp:
yield mocked_call, mocked_mail, mocked_xmpp
def test_send_notifications(self):
"""New push sends notifications via IRC, XMPP and emails."""
self.people = ["fake_user1", "fake_user2"]
self.pushurl = "/fake_push_url?id=123"
self.pushtype = "fake_puth_type"
with self.mocked_notifications() as (mocked_call, mocked_mail, mocked_xmpp):
send_notifications(self.people, self.pushtype, self.pushurl)
url = "https://%s%s" % (Settings['main_app']['servername'], self.pushurl)
msg = "%s: %s push starting! %s" % (', '.join(self.people), self.pushtype, url)
mocked_call.assert_called_once_with([
'/nail/sys/bin/nodebot',
'-i',
Settings['irc']['nickname'],
Settings['irc']['channel'],
msg
])
mocked_mail.assert_called_once_with(
Settings['mail']['notifyall'],
msg,
mock.ANY, # subject
)
mocked_xmpp.assert_called_once_with(
self.people,
"Push starting! %s" % url<|fim▁hole|> email notifications, but not XMPP messages."""
self.people = []
self.pushurl = "fake_push_url"
self.pushtype = "fake_puth_type"
with self.mocked_notifications() as (mocked_call, mocked_mail, mocked_xmpp):
send_notifications(self.people, self.pushtype, self.pushurl)
mocked_call.assert_called_once_with([
'/nail/sys/bin/nodebot',
'-i',
Settings['irc']['nickname'],
Settings['irc']['channel'],
mock.ANY, # msg
])
mocked_mail.assert_called_once_with(
Settings['mail']['notifyall'],
mock.ANY, # msg
mock.ANY, # subject
)
T.assert_is(mocked_xmpp.called, False)
if __name__ == '__main__':
T.run()<|fim▁end|> | )
def test_send_notifications_empty_user_list(self):
"""If there is no pending push request we'll only send IRC and |
<|file_name|>fixup_oslogin_v1_keywords.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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 argparse
import os
import libcst as cst
import pathlib
import sys
from typing import (Any, Callable, Dict, List, Sequence, Tuple)
def partition(
predicate: Callable[[Any], bool],
iterator: Sequence[Any]
) -> Tuple[List[Any], List[Any]]:
"""A stable, out-of-place partition."""
results = ([], [])
for i in iterator:
results[int(predicate(i))].append(i)
# Returns trueList, falseList
return results[1], results[0]
class osloginCallTransformer(cst.CSTTransformer):
CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata')
METHOD_TO_PARAMS: Dict[str, Tuple[str]] = {
'delete_posix_account': ('name', ),
'delete_ssh_public_key': ('name', ),
'get_login_profile': ('name', 'project_id', 'system_id', ),
'get_ssh_public_key': ('name', ),
'import_ssh_public_key': ('parent', 'ssh_public_key', 'project_id', ),
'update_ssh_public_key': ('name', 'ssh_public_key', 'update_mask', ),
}
def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode:
try:
key = original.func.attr.value
kword_params = self.METHOD_TO_PARAMS[key]
except (AttributeError, KeyError):
# Either not a method from the API or too convoluted to be sure.
return updated
# If the existing code is valid, keyword args come after positional args.
# Therefore, all positional args must map to the first parameters.
args, kwargs = partition(lambda a: not bool(a.keyword), updated.args)
if any(k.keyword.value == "request" for k in kwargs):
# We've already fixed this file, don't fix it again.
return updated
kwargs, ctrl_kwargs = partition(
lambda a: a.keyword.value not in self.CTRL_PARAMS,
kwargs
)
args, ctrl_args = args[:len(kword_params)], args[len(kword_params):]
ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl))
for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS))
request_arg = cst.Arg(
value=cst.Dict([
cst.DictElement(
cst.SimpleString("'{}'".format(name)),
cst.Element(value=arg.value)
)
# Note: the args + kwargs looks silly, but keep in mind that
# the control parameters had to be stripped out, and that
# those could have been passed positionally or by keyword.
for name, arg in zip(kword_params, args + kwargs)]),
keyword=cst.Name("request")
)
return updated.with_changes(
args=[request_arg] + ctrl_kwargs
)
def fix_files(
in_dir: pathlib.Path,
out_dir: pathlib.Path,
*,
transformer=osloginCallTransformer(),
):
"""Duplicate the input dir to the output dir, fixing file method calls.
Preconditions:<|fim▁hole|> * in_dir is a real directory
* out_dir is a real, empty directory
"""
pyfile_gen = (
pathlib.Path(os.path.join(root, f))
for root, _, files in os.walk(in_dir)
for f in files if os.path.splitext(f)[1] == ".py"
)
for fpath in pyfile_gen:
with open(fpath, 'r') as f:
src = f.read()
# Parse the code and insert method call fixes.
tree = cst.parse_module(src)
updated = tree.visit(transformer)
# Create the path and directory structure for the new file.
updated_path = out_dir.joinpath(fpath.relative_to(in_dir))
updated_path.parent.mkdir(parents=True, exist_ok=True)
# Generate the updated source file at the corresponding path.
with open(updated_path, 'w') as f:
f.write(updated.code)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="""Fix up source that uses the oslogin client library.
The existing sources are NOT overwritten but are copied to output_dir with changes made.
Note: This tool operates at a best-effort level at converting positional
parameters in client method calls to keyword based parameters.
Cases where it WILL FAIL include
A) * or ** expansion in a method call.
B) Calls via function or method alias (includes free function calls)
C) Indirect or dispatched calls (e.g. the method is looked up dynamically)
These all constitute false negatives. The tool will also detect false
positives when an API method shares a name with another method.
""")
parser.add_argument(
'-d',
'--input-directory',
required=True,
dest='input_dir',
help='the input directory to walk for python files to fix up',
)
parser.add_argument(
'-o',
'--output-directory',
required=True,
dest='output_dir',
help='the directory to output files fixed via un-flattening',
)
args = parser.parse_args()
input_dir = pathlib.Path(args.input_dir)
output_dir = pathlib.Path(args.output_dir)
if not input_dir.is_dir():
print(
f"input directory '{input_dir}' does not exist or is not a directory",
file=sys.stderr,
)
sys.exit(-1)
if not output_dir.is_dir():
print(
f"output directory '{output_dir}' does not exist or is not a directory",
file=sys.stderr,
)
sys.exit(-1)
if os.listdir(output_dir):
print(
f"output directory '{output_dir}' is not empty",
file=sys.stderr,
)
sys.exit(-1)
fix_files(input_dir, output_dir)<|fim▁end|> | |
<|file_name|>app.js<|end_file_name|><|fim▁begin|>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var Session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// create session middleware
var session = Session({
resave: true, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
secret: 'love' // ???
});
var dashboard_routes = require('./routes/dashboard');
var test_routes = require('./routes/test');
var users_routes = require('./routes/users');
var regions_routes = require('./routes/regions');
var informations_routes = require('./routes/informations');
var commands_routes = require('./routes/commands');
var document_routes = require('./routes/documents');
var images_routes = require('./routes/images');
var authentications_routes = require('./routes/authentications');
var auth = require('./routes/auth');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.png')));
app.use(logger('dev'));
/* Automatically parse json object in request, and store the parsing
* result in `req.body`. If request is not json type (i.e., "Content-Type"
* is not "application/json", it won't be parsed.
*/
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use('/public', express.static(path.join(__dirname, 'public')));
// for logging
// Each time a request reaches, log the verb, url, body of request.
app.use(function(req, res, next) {
console.log('====================================================');
console.log('Request:');
console.log(req.method, req.originalUrl);
console.log(req.body);
console.log('----------------------------------------------------');
next();
});
/*
* Session control:
*
* Session only applies for /login, /login.do, /logout, and url starting with
* /dashboard.
*
* 1. Add `session` middleware for these routes, which can automatically set
* session information in `req.session`
* 2. When a user log in through /login.do, store login information in session,
* specifically, `req.session.user`
* 3. Every time a request ask for /dashboard/*, check whether `req.session.user`
* is set. If `req.session.user` is undefined, redirect to login page.
* 4. When logging out, delete `req.session.user`.
*
*/
app.get('/login', session, function(req, res, next) {
res.render('login');
});
app.post('/login.do', session, function (req, res, next) {
var username = req.body.username;
var password = req.body.password;
console.log('username =', username, 'password =', password);
if (username == "admin" && password == "admin") {
// store login information in session
req.session.user = {
username: 'admin',
password: 'admin'
};
res.redirect('/dashboard');
} else {
res.redirect('/login');
}
});
app.get('/logout', session, function(req, res, next) {
// delete login information in session
req.session.user = null;
res.redirect('/login');
});
// routes, see routes/*.js
app.use('/dashboard', session, function (req, res, next) {
/*
* If `req.session.user` exists, it means that user is already logged in.
* Otherwise, we should redirect to login page.
*/
console.log('req.session = ', req.session);
if (req.session.user || /^\/login/.test(req.url)) {
console.log('next');
next();
} else {
res.redirect('/login');
console.log('redirect');
}
}, dashboard_routes);
// routes for RESTful APIs
app.use('/test', auth.forAllUsers, test_routes);
app.use('/authentications', auth.forAllUsers, authentications_routes);
app.use('/users', auth.forAllUsers, users_routes);
app.use('/regions', auth.forAllUsers, regions_routes);
app.use('/information', auth.forAllUsers, informations_routes);
app.use('/commands', auth.forAllUsers, commands_routes);
app.use('/documents', auth.forAllUsers, document_routes);
app.use('/images', images_routes);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
res.status(404).send({
status: 404,
message: req.url + ' Not Found'
});
});
// error handlers
/* development error handler, will print stacktrace
*
* this error handler can be triggered by `next(error)`,
* where error is an `Error` object created by `new Error(message)`
*
* Example:
*
* function do_get(req, res, next) {
* if (something_wrong) {
* var error = new Error('some message');
* error.status = 503;
* } else {
* do_something();
* }
*
*/
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {<|fim▁hole|> console.log(err.message);
console.log(err.stack);
}
var status = err.status || 500;
res.status(status);
res.send({
status: status,
message: err.message,
stack: err.stack,
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
console.log('caused production error handler');
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;<|fim▁end|> | console.log('caused development error handler');
if (err.status != 404) { |
<|file_name|>AbstractConnectHandlerTest.java<|end_file_name|><|fim▁begin|>package org.eclipse.jetty.server.handler;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.junit.AfterClass;
/**
* @version $Revision$ $Date$
*/
public abstract class AbstractConnectHandlerTest
{
protected static Server server;
protected static Connector serverConnector;
protected static Server proxy;
protected static Connector proxyConnector;
protected static void startServer(Connector connector, Handler handler) throws Exception
{
server = new Server();
serverConnector = connector;
server.addConnector(serverConnector);
server.setHandler(handler);
server.start();
}
protected static void startProxy() throws Exception
{
proxy = new Server();
proxyConnector = new SelectChannelConnector();
proxy.addConnector(proxyConnector);
proxy.setHandler(new ConnectHandler());
proxy.start();
}
@AfterClass
public static void stop() throws Exception
{
stopProxy();
stopServer();
}
protected static void stopServer() throws Exception
{
server.stop();
server.join();
}
protected static void stopProxy() throws Exception
{
proxy.stop();
proxy.join();
}
protected Response readResponse(BufferedReader reader) throws IOException
{
// Simplified parser for HTTP responses
String line = reader.readLine();
if (line == null)
throw new EOFException();
Matcher responseLine = Pattern.compile("HTTP/1\\.1\\s+(\\d+)").matcher(line);
assertTrue(responseLine.lookingAt());
String code = responseLine.group(1);
Map<String, String> headers = new LinkedHashMap<String, String>();
while ((line = reader.readLine()) != null)
{
if (line.trim().length() == 0)
break;
Matcher header = Pattern.compile("([^:]+):\\s*(.*)").matcher(line);
assertTrue(header.lookingAt());
String headerName = header.group(1);
String headerValue = header.group(2);
headers.put(headerName.toLowerCase(), headerValue.toLowerCase());
}
StringBuilder body = new StringBuilder();
if (headers.containsKey("content-length"))
{
int length = Integer.parseInt(headers.get("content-length"));
for (int i = 0; i < length; ++i)
{
char c = (char)reader.read();
body.append(c);
}
}
else if ("chunked".equals(headers.get("transfer-encoding")))
{
while ((line = reader.readLine()) != null)
{
if ("0".equals(line))
{
line = reader.readLine();
assertEquals("", line);
break;
}
int length = Integer.parseInt(line, 16);
for (int i = 0; i < length; ++i)
{
char c = (char)reader.read();
body.append(c);
}
line = reader.readLine();
assertEquals("", line);
}
}
return new Response(code, headers, body.toString().trim());
}
protected Socket newSocket() throws IOException
{
Socket socket = new Socket("localhost", proxyConnector.getLocalPort());
socket.setSoTimeout(5000);
return socket;
}
protected class Response
{
private final String code;
private final Map<String, String> headers;
private final String body;
private Response(String code, Map<String, String> headers, String body)
{
this.code = code;
this.headers = headers;
this.body = body;
}
public String getCode()
{
return code;
}
public Map<String, String> getHeaders()
{
return headers;
}
public String getBody()
{
return body;
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append(code).append("\r\n");
for (Map.Entry<String, String> entry : headers.entrySet())
builder.append(entry.getKey()).append(": ").append(entry.getValue()).append("\r\n");
builder.append("\r\n");<|fim▁hole|> }
}<|fim▁end|> | builder.append(body);
return builder.toString();
} |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | from . import slide_channel_technology_category
from . import slide_channel_technology
from . import slide_channel |
<|file_name|>bpscore_benchmark.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
#
# This script executes different GO BPScore algorithms
# in order to compare their run times.
# for timing
import time
<|fim▁hole|>from pappi.data_config import *
# import the GO association loading function
from pappi.go.utils import load_go_associations_sql
# import similarity scorer to be benchmarked
from pappi.go.fast_similarity import GoFastSimilarity
from pappi.go.fastSemSim_similarity import GoFastSemSimSimilarity
from pappi.go.prebuf_similarity import GoPreBufSimilarity
from pappi.go.gene_prebuf_similarity import GoGenePreBufSimilarity
class BPScore_Benchmarker:
def __init__(self):
# get database connection
self.con = pappi.sql.get_conn(DATABASE)
self.genes = self.get_benchmark_genes(self.con)
self.scorers = []
self.init_time = []
self.run_times = dict() # dict {number of genes -> list of run times}
def init_scorers(self):
# initialize all the scorers (and save the initalization time)
start = time.time()
self.scorers.append(GoFastSimilarity(GO_OBO_FILE, self.con, True))
self.init_time.append(time.time() - start)
start = time.time()
self.scorers.append(GoFastSemSimSimilarity(GO_OBO_FILE, GO_ASSOC_FILE,
self.con))
self.init_time.append(time.time() - start)
start = time.time()
self.scorers.append(GoPreBufSimilarity(GO_OBO_FILE, GO_SCORE_FILE,
GO_SCORE_MAP_FILE, self.con, True))
self.init_time.append(time.time() - start)
start = time.time()
self.scorers.append(GoGenePreBufSimilarity(GO_OBO_FILE, GO_SCORE_FILE,
GO_SCORE_MAP_FILE,
GO_BPSCORE_FILE,
GO_BPSCORE_MAP_FILE, self.con,
True))
self.init_time.append(time.time() - start)
def benchmark_scorers(self, nGenes):
# get a set of genes with the given size
benchmark_genes = set(self.genes[0:nGenes])
# score the gene set with all scorers
score_time = []
for scorer in self.scorers:
start = time.time()
score = scorer.gene_set_score(benchmark_genes)
score_time.append(time.time() - start)
# save run time to class table
self.run_times[nGenes] = score_time
def get_benchmark_genes(self, sql_conn):
# load Gene->GO-Term associations to get a set of genes to be used in
# the benchmark
assoc = load_go_associations_sql(sql_conn)
# use a list for fast/efficient range access
genes = list(assoc.keys())
return genes
def run_benchmark(self):
for n in range(10, 1001, 10):
print("benchmarking for n = " + str(n) + " genes...")
self.benchmark_scorers(n)
def print_timings(self):
print("scored by " + str(len(self.scorers)) + " scorers")
print()
print("n\t" + "\t".join(self.scorers[i].__class__.__name__
for i in range(0, len(self.scorers))))
print("init\t" + "\t".join(str(self.init_time[i])
for i in range(0, len(self.scorers))))
for n in sorted(self.run_times.keys()):
score_time = self.run_times[n]
print(str(n) + "\t" + "\t".join(str(s) for s in score_time))
# the main benchmark:
if __name__ == '__main__':
print("loading benchmarking class...")
benchmarker = BPScore_Benchmarker()
print("benchmark init times...")
benchmarker.init_scorers()
print("benchmark scoring...")
benchmarker.run_benchmark()
# print the actual timing results
benchmarker.print_timings()<|fim▁end|> | # for the data connection
import pappi.sql |
<|file_name|>Gruntfile.js<|end_file_name|><|fim▁begin|>// Generated on 2015-04-11 using
// generator-webapp 0.5.1
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// If you want to recursively match all subfolders, use:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Configurable paths
var config = {
app: 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
config: config,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= config.app %>/scripts/{,*/}*.js'],
tasks: ['jshint'],
options: {
livereload: true
}
},
jstest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['test:watch']
},
gruntfile: {
files: ['Gruntfile.js']
},
styles: {
files: ['<%= config.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'autoprefixer']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= config.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= config.app %>/images/{,*/}*'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
open: true,
livereload: 35729,
// Change this to '0.0.0.0' to access the server from outside
hostname: '0.0.0.0'
},
livereload: {
options: {
middleware: function(connect) {
return [
connect.static('.tmp'),
connect().use('/bower_components', connect.static('./bower_components')),
connect.static(config.app)
];
}
}
},
test: {
options: {
open: false,
port: 9001,
middleware: function(connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use('/bower_components', connect.static('./bower_components')),
connect.static(config.app)
];
}
}
},
dist: {
options: {
base: '<%= config.dist %>',
livereload: false
}
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= config.dist %>/*',
'!<%= config.dist %>/.git*'
]
}]
},
server: '.tmp'
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: [
'Gruntfile.js',
'<%= config.app %>/scripts/{,*/}*.js',
'!<%= config.app %>/scripts/vendor/*',
'test/spec/{,*/}*.js'
]
},
// Jasmine testing framework configuration options
jasmine: {
all: {
options: {
specs: 'test/spec/{,*/}*.js'
}
}
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the HTML file
wiredep: {
app: {
ignorePath: /^\/|\.\.\//,
src: ['<%= config.app %>/index.html'],
exclude: ['bower_components/bootstrap/dist/js/bootstrap.js']
}
},
// Renames files for browser caching purposes
rev: {
dist: {
files: {
src: [
'<%= config.dist %>/scripts/{,*/}*.js',
'<%= config.dist %>/styles/{,*/}*.css',
'<%= config.dist %>/images/{,*/}*.*',
'<%= config.dist %>/styles/fonts/{,*/}*.*',
'<%= config.dist %>/*.{ico,png}'
]
}
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
options: {
dest: '<%= config.dist %>'
},
html: '<%= config.app %>/index.html'
},
// Performs rewrites based on rev and the useminPrepare configuration
usemin: {
options: {
assetsDirs: [
'<%= config.dist %>',
'<%= config.dist %>/images',
'<%= config.dist %>/styles'
]
},
html: ['<%= config.dist %>/{,*/}*.html'],
css: ['<%= config.dist %>/styles/{,*/}*.css']
},
// The following *-min tasks produce minified files in the dist folder
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.{gif,jpeg,jpg,png}',
dest: '<%= config.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.svg',
dest: '<%= config.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
conservativeCollapse: true,
removeAttributeQuotes: true,
removeCommentsFromCDATA: true,
removeEmptyAttributes: true,
removeOptionalTags: true,
removeRedundantAttributes: true,
useShortDoctype: true
},
files: [{
expand: true,
cwd: '<%= config.dist %>',
src: '{,*/}*.html',
dest: '<%= config.dist %>'
}]
}
},
// By default, your `index.html`'s <!-- Usemin block --> will take care
// of minification. These next options are pre-configured if you do not
// wish to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= config.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css',
// '<%= config.app %>/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= config.dist %>/scripts/scripts.js': [
// '<%= config.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= config.app %>',
dest: '<%= config.dist %>',
src: [
'*.{ico,png,txt}',
'images/{,*/}*.webp',
'{,*/}*.html',
'styles/fonts/{,*/}*.*'
]
}, {
src: 'node_modules/apache-server-configs/dist/.htaccess',
dest: '<%= config.dist %>/.htaccess'
}, {
expand: true,
dot: true,
cwd: 'bower_components/bootstrap/dist',
src: 'fonts/*',
dest: '<%= config.dist %>'
}]
},
styles: {
expand: true,
dot: true,
cwd: '<%= config.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up build process
concurrent: {
server: [
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'copy:styles',
'imagemin',
'svgmin'
]
}
});
grunt.registerTask('serve', 'start the server and preview your app, --allow-remote for remote access', function (target) {
if (grunt.option('allow-remote')) {
grunt.config.set('connect.options.hostname', '0.0.0.0');
}
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run([target ? ('serve:' + target) : 'serve']);
});
grunt.registerTask('test', function (target) {
if (target !== 'watch') {
grunt.task.run([
'clean:server',
'concurrent:test',
'autoprefixer'
]);
}
grunt.task.run([
'connect:test',
'jasmine'
]);
});
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'cssmin',
'uglify',<|fim▁hole|> 'copy:dist',
'rev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};<|fim▁end|> | |
<|file_name|>test_data.ts<|end_file_name|><|fim▁begin|>import {
Commit, Digest, SearchResult, TestName,
} from '../rpc_types';
export const fakeNow = Date.parse('2020-03-22T00:00:00.000Z');
const allTheSame: number[] = Array(200).fill(0);
const mod2Data: number[] = Array(200).fill(1).map((_, index) => index % 2);
const mod3Data: number[] = Array(200).fill(1).map((_, index) => index % 3);
export const makeTypicalSearchResult = (testName: TestName, digest: Digest, closestDigest: Digest): SearchResult => ({
test: testName,
digest: digest,
status: 'positive',
triage_history: [
{
user: '[email protected]',
ts: '2020-02-25T16:08:18.776Z',
},
{
user: '[email protected]',
ts: '2020-02-25T16:05:13.000Z',
},
],
paramset: {
ext: [
'png',
],
name: [
testName,
],
source_type: [
'infra',
],
os: [
'Mac', 'Linux',
],
},
traces: {
traces: [
{
data: mod2Data,
label: `,name=${testName},os=Linux,source_type=infra,`,
params: {
ext: 'png',
name: testName,
os: 'Linux',
source_type: 'infra',
},
comment_indices: null, // TODO(kjlubick) skbug.com/6630
},
{
data: mod3Data,
label: `,name=${testName},os=Mac,source_type=infra,`,
params: {
ext: 'png',
name: testName,
os: 'Mac',
source_type: 'infra',
},
comment_indices: null,
},
],
digests: [
{
digest: digest,
status: 'positive',
},
{
digest: closestDigest,
status: 'positive',
},
{
digest: 'ec3b8f27397d99581e06eaa46d6d5837',
status: 'negative',
},
],
total_digests: 3,
},
closestRef: 'pos',
refDiffs: {
neg: {
numDiffPixels: 1689996,
pixelDiffPercent: 99.99976,
maxRGBADiffs: [
255,
255,
255,
0,
],
dimDiffer: true,
combinedMetric: 9.306038,
digest: 'ec3b8f27397d99581e06eaa46d6d5837',
status: 'negative',
paramset: {
ext: [
'png',
],
name: [
testName,
],
source_type: [
'infra',
],
os: [
'Linux',
],
},
},
pos: {
numDiffPixels: 3766,
pixelDiffPercent: 0.22284023,
maxRGBADiffs: [
9,
9,
9,
0,
],
dimDiffer: false,
combinedMetric: 0.082530275,
digest: closestDigest,
status: 'positive',
paramset: {
ext: [
'png',
],
name: [
testName,
],
source_type: [
'infra',
],
os: [
'Mac', 'Linux',
],
},
},
},
});
export const typicalDetails = makeTypicalSearchResult(
'dots-legend-sk_too-many-digests',
'6246b773851984c726cb2e1cb13510c2',
'99c58c7002073346ff55f446d47d6311',
);
export const negativeOnly: SearchResult = {
test: 'dots-legend-sk_too-many-digests',
digest: '6246b773851984c726cb2e1cb13510c2',
status: 'positive',
triage_history: [
{
user: '[email protected]',
ts: '2020-02-25T16:08:18.776Z',
},
{
user: '[email protected]',
ts: '2020-02-25T16:05:13.000Z',
},
],
paramset: {
ext: [
'png',
],
name: [
'dots-legend-sk_too-many-digests',
],
source_type: [
'infra',
],
os: [
'Mac', 'Linux',
],
},
traces: {
traces: [
{
data: mod2Data,
label: ',name=dots-legend-sk_too-many-digests,os=Linux,source_type=infra,',
params: {
ext: 'png',
name: 'dots-legend-sk_too-many-digests',
os: 'Linux',
source_type: 'infra',
},
comment_indices: null,
},
],
digests: [
{
digest: '6246b773851984c726cb2e1cb13510c2',
status: 'positive',
},
{
digest: 'ec3b8f27397d99581e06eaa46d6d5837',
status: 'negative',
},
],
total_digests: 3,
},
closestRef: 'neg',
refDiffs: {
neg: {
numDiffPixels: 1689996,
pixelDiffPercent: 99.99976,
maxRGBADiffs: [
255,
255,
255,
0,
],
dimDiffer: true,
combinedMetric: 9.306038,
digest: 'ec3b8f27397d99581e06eaa46d6d5837',
status: 'negative',
paramset: {
ext: [
'png',
],
name: [
'dots-legend-sk_too-many-digests',
],
source_type: [
'infra',
],
os: [
'Mac',
],
},
},
},
};
export const noRefs: SearchResult = {
test: 'dots-legend-sk_too-many-digests',
digest: '6246b773851984c726cb2e1cb13510c2',
status: 'positive',
triage_history: [
{
user: '[email protected]',
ts: '2020-02-25T16:08:18.776Z',
},
{
user: '[email protected]',
ts: '2020-02-25T16:05:13.000Z',
},
],
paramset: {
ext: [
'png',
],
name: [
'dots-legend-sk_too-many-digests',
],
source_type: [
'infra',
],
os: [
'Linux',
],
},
traces: {
traces: [
{
data: allTheSame,
label: ',name=dots-legend-sk_too-many-digests,os=Linux,source_type=infra,',
params: {
ext: 'png',
name: 'dots-legend-sk_too-many-digests',
os: 'Linux',
source_type: 'infra',
},
comment_indices: null,
},
],
digests: [
{
digest: '6246b773851984c726cb2e1cb13510c2',
status: 'positive',
},
],
total_digests: 3,
},
closestRef: '',
refDiffs: {},
};
export const noRefsYet: SearchResult = {
test: 'dots-legend-sk_too-many-digests',
digest: '6246b773851984c726cb2e1cb13510c2',
status: 'positive',
triage_history: [
{
user: '[email protected]',
ts: '2020-02-25T16:08:18.776Z',
},
{
user: '[email protected]',
ts: '2020-02-25T16:05:13.000Z',
},
],
paramset: {
ext: [
'png',
],<|fim▁hole|> source_type: [
'infra',
],
os: [
'Linux',
],
},
traces: {
traces: [
{
data: mod2Data,
label: ',name=dots-legend-sk_too-many-digests,os=Linux,source_type=infra,',
params: {
ext: 'png',
name: 'dots-legend-sk_too-many-digests',
os: 'Linux',
source_type: 'infra',
},
comment_indices: null,
},
],
digests: [
{
digest: '6246b773851984c726cb2e1cb13510c2',
status: 'positive',
},
{
digest: 'ec3b8f27397d99581e06eaa46d6d5837',
status: 'negative',
},
],
total_digests: 3,
},
closestRef: '',
refDiffs: {},
};
export const noTraces: SearchResult = {
test: 'dots-legend-sk_too-many-digests',
digest: '6246b773851984c726cb2e1cb13510c2',
status: 'positive',
triage_history: [
{
user: '[email protected]',
ts: '2020-02-25T16:08:18.776Z',
},
{
user: '[email protected]',
ts: '2020-02-25T16:05:13.000Z',
},
],
traces: {
traces: [],
digests: [],
total_digests: 0,
},
paramset: {
ext: [
'png',
],
name: [
'dots-legend-sk_too-many-digests',
],
source_type: [
'infra',
],
os: [
'Mac', 'Linux',
],
},
closestRef: 'pos',
refDiffs: {
neg: {
numDiffPixels: 1689996,
pixelDiffPercent: 99.99976,
maxRGBADiffs: [
255,
255,
255,
0,
],
dimDiffer: true,
combinedMetric: 9.306038,
digest: 'ec3b8f27397d99581e06eaa46d6d5837',
status: 'negative',
paramset: {
ext: [
'png',
],
name: [
'dots-legend-sk_too-many-digests',
],
source_type: [
'infra',
],
os: [
'Linux',
],
},
},
pos: {
numDiffPixels: 3766,
pixelDiffPercent: 0.22284023,
maxRGBADiffs: [
9,
9,
9,
0,
],
dimDiffer: false,
combinedMetric: 0.082530275,
digest: '99c58c7002073346ff55f446d47d6311',
status: 'positive',
paramset: {
ext: [
'png',
],
name: [
'dots-legend-sk_too-many-digests',
],
source_type: [
'infra',
],
os: [
'Mac', 'Linux',
],
},
},
},
};
const tsStartTime = 1583130000; // an arbitrary timestamp.
function makeCommits(n: number): Commit[] {
const rv: Commit[] = [];
for (let i = 0; i < n; i++) {
rv.push({
id: 'commit_id',
commit_time: tsStartTime + i * 123, // arbitrary spacing
hash: `${i}`.padEnd(32, '0'), // make a deterministic "md5 hash", which is 32 chars long
author: `user${i % 7}@example.com`,
message: `This is a nice message. I've repeated it ${i + 1} time(s)`,
cl_url: '',
});
}
return rv;
}
export const twoHundredCommits = makeCommits(200);<|fim▁end|> | name: [
'dots-legend-sk_too-many-digests',
], |
<|file_name|>update_tokens.py<|end_file_name|><|fim▁begin|>from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from brambling.utils.payment import dwolla_update_tokens
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
'--days',
action='store',
dest='days',
default=15,
help='Number of days ahead of time to update refresh tokens.'),
)<|fim▁hole|> days = int(options['days'])
except ValueError:
raise CommandError("Days must be an integer value.")
self.stdout.write("Updating dwolla tokens...")
self.stdout.flush()
count, test_count = dwolla_update_tokens(days)
self.stdout.write("Test tokens updated: {}".format(count))
self.stdout.write("Live tokens updated: {}".format(test_count))
self.stdout.flush()<|fim▁end|> |
def handle(self, *args, **options):
try: |
<|file_name|>NickNameCache.cpp<|end_file_name|><|fim▁begin|>#include <core/stdafx.h>
#include <core/smartview/NickNameCache.h>
namespace smartview
{
void SRowStruct::parse()
{
cValues = blockT<DWORD>::parse(parser);
if (*cValues)
{
if (*cValues < _MaxEntriesSmall)
{
lpProps = std::make_shared<PropertiesStruct>(*cValues, true, false);
lpProps->block::parse(parser, false);
}
}
}
void SRowStruct::parseBlocks()
{
addChild(cValues, L"cValues = 0x%1!08X! = %1!d!", cValues->getData());
addChild(lpProps);
}
void NickNameCache::parse()
{
m_Metadata1 = blockBytes::parse(parser, 4);
m_ulMajorVersion = blockT<DWORD>::parse(parser);
m_ulMinorVersion = blockT<DWORD>::parse(parser);
m_cRowCount = blockT<DWORD>::parse(parser);
if (*m_cRowCount)
{
if (*m_cRowCount < _MaxEntriesEnormous)
{
m_lpRows.reserve(*m_cRowCount);
for (DWORD i = 0; i < *m_cRowCount; i++)
{
m_lpRows.emplace_back(block::parse<SRowStruct>(parser, false));
}
}<|fim▁hole|> m_cbEI = blockT<DWORD>::parse(parser);
m_lpbEI = blockBytes::parse(parser, *m_cbEI, _MaxBytes);
m_Metadata2 = blockBytes::parse(parser, 8);
}
void NickNameCache::parseBlocks()
{
setText(L"Nickname Cache");
addLabeledChild(L"Metadata1", m_Metadata1);
addChild(m_ulMajorVersion, L"Major Version = %1!d!", m_ulMajorVersion->getData());
addChild(m_ulMinorVersion, L"Minor Version = %1!d!", m_ulMinorVersion->getData());
addChild(m_cRowCount, L"Row Count = %1!d!", m_cRowCount->getData());
if (!m_lpRows.empty())
{
auto i = DWORD{};
for (const auto& row : m_lpRows)
{
addChild(row, L"Row %1!d!", i);
i++;
}
}
addLabeledChild(L"Extra Info", m_lpbEI);
addLabeledChild(L"Metadata 2", m_Metadata2);
}
} // namespace smartview<|fim▁end|> | }
|
<|file_name|>mastermodel.py<|end_file_name|><|fim▁begin|>import os
import json
from PySide2 import QtCore
from opencmiss.zinc.context import Context
from opencmiss.zinc.material import Material
from mapclientplugins.meshgeneratorstep.model.meshgeneratormodel import MeshGeneratorModel
from mapclientplugins.meshgeneratorstep.model.meshannotationmodel import MeshAnnotationModel
from mapclientplugins.meshgeneratorstep.model.segmentationdatamodel import SegmentationDataModel
from scaffoldmaker.scaffolds import Scaffolds_decodeJSON, Scaffolds_JSONEncoder
class MasterModel(object):
def __init__(self, location, identifier):
self._location = location
self._identifier = identifier
self._filenameStem = os.path.join(self._location, self._identifier)
self._context = Context("MeshGenerator")
self._timekeeper = self._context.getTimekeepermodule().getDefaultTimekeeper()
self._timer = QtCore.QTimer()
self._current_time = 0.0
self._timeValueUpdate = None
self._frameIndexUpdate = None
self._initialise()
self._region = self._context.createRegion()
self._generator_model = MeshGeneratorModel(self._context, self._region, self._materialmodule)
self._segmentation_data_model = SegmentationDataModel(self._region, self._materialmodule)
self._annotation_model = MeshAnnotationModel()
self._settings = {
'segmentation_data_settings' : self._segmentation_data_model.getSettings()
}
self._makeConnections()
# self._loadSettings()
def printLog(self):
logger = self._context.getLogger()
for index in range(logger.getNumberOfMessages()):
print(logger.getMessageTextAtIndex(index))
def _initialise(self):
self._filenameStem = os.path.join(self._location, self._identifier)
tess = self._context.getTessellationmodule().getDefaultTessellation()
tess.setRefinementFactors(12)
# set up standard materials and glyphs so we can use them elsewhere
self._materialmodule = self._context.getMaterialmodule()
self._materialmodule.defineStandardMaterials()
solid_blue = self._materialmodule.createMaterial()
solid_blue.setName('solid_blue')
solid_blue.setManaged(True)
solid_blue.setAttributeReal3(Material.ATTRIBUTE_AMBIENT, [ 0.0, 0.2, 0.6 ])
solid_blue.setAttributeReal3(Material.ATTRIBUTE_DIFFUSE, [ 0.0, 0.7, 1.0 ])
solid_blue.setAttributeReal3(Material.ATTRIBUTE_EMISSION, [ 0.0, 0.0, 0.0 ])
solid_blue.setAttributeReal3(Material.ATTRIBUTE_SPECULAR, [ 0.1, 0.1, 0.1 ])
solid_blue.setAttributeReal(Material.ATTRIBUTE_SHININESS , 0.2)
trans_blue = self._materialmodule.createMaterial()
trans_blue.setName('trans_blue')
trans_blue.setManaged(True)
trans_blue.setAttributeReal3(Material.ATTRIBUTE_AMBIENT, [ 0.0, 0.2, 0.6 ])
trans_blue.setAttributeReal3(Material.ATTRIBUTE_DIFFUSE, [ 0.0, 0.7, 1.0 ])
trans_blue.setAttributeReal3(Material.ATTRIBUTE_EMISSION, [ 0.0, 0.0, 0.0 ])
trans_blue.setAttributeReal3(Material.ATTRIBUTE_SPECULAR, [ 0.1, 0.1, 0.1 ])
trans_blue.setAttributeReal(Material.ATTRIBUTE_ALPHA , 0.3)
trans_blue.setAttributeReal(Material.ATTRIBUTE_SHININESS , 0.2)
glyphmodule = self._context.getGlyphmodule()
glyphmodule.defineStandardGlyphs()
def _makeConnections(self):
pass
def getIdentifier(self):
return self._identifier
def getOutputModelFilename(self):
return self._filenameStem + '.exf'
def getGeneratorModel(self):
return self._generator_model
def getMeshAnnotationModel(self):
return self._annotation_model
<|fim▁hole|> return self._region.getScene()
def getContext(self):
return self._context
def registerSceneChangeCallback(self, sceneChangeCallback):
self._generator_model.registerSceneChangeCallback(sceneChangeCallback)
def done(self):
self._saveSettings()
self._generator_model.done()
self._generator_model.writeModel(self.getOutputModelFilename())
self._generator_model.writeAnnotations(self._filenameStem)
self._generator_model.exportToVtk(self._filenameStem)
def _getSettings(self):
'''
Ensures master model settings includes current settings for sub models.
:return: Master setting dict.
'''
settings = self._settings
settings['generator_settings'] = self._generator_model.getSettings()
settings['segmentation_data_settings'] = self._segmentation_data_model.getSettings()
return settings
def loadSettings(self):
try:
settings = self._settings
with open(self._filenameStem + '-settings.json', 'r') as f:
savedSettings = json.loads(f.read(), object_hook=Scaffolds_decodeJSON)
settings.update(savedSettings)
if not 'generator_settings' in settings:
# migrate from old settings before named generator_settings
settings = {'generator_settings': settings}
except:
# no settings saved yet, following gets defaults
settings = self._getSettings()
self._generator_model.setSettings(settings['generator_settings'])
self._segmentation_data_model.setSettings(settings['segmentation_data_settings'])
self._annotation_model.setScaffoldTypeByName(self._generator_model.getEditScaffoldTypeName())
self._getSettings()
def _saveSettings(self):
self._generator_model.updateSettingsBeforeWrite()
settings = self._getSettings()
with open(self._filenameStem + '-settings.json', 'w') as f:
f.write(json.dumps(settings, cls=Scaffolds_JSONEncoder, sort_keys=True, indent=4))
def setSegmentationDataFile(self, data_filename):
self._segmentation_data_model.setDataFilename(data_filename)<|fim▁end|> | def getSegmentationDataModel(self):
return self._segmentation_data_model
def getScene(self): |
<|file_name|>tool-initdb.js<|end_file_name|><|fim▁begin|>const fs = require('fs')
const path = require('path')
const {generateBabelEnvLoader, getConfig} = require('./common')
const buildCache = {}
module.exports = (params) => {
const baseConfig = getConfig(params)<|fim▁hole|> return {
entry: config.sourcePath + '/tools/initdb.js',
context: config.sourcePath,
target: 'node',
output: {
path: config.outputPath,
filename: 'initdb.js'
},
stats: {
colors: true,
reasons: true,
chunks: false
},
cache: buildCache,
module: {
rules: [generateBabelEnvLoader({node: 'current'}, config)]
},
resolve: {
extensions: ['.js', '.jsx'],
alias: baseConfig.aliases
},
devServer: {
contentBase: config.sourcePath
}
}
}<|fim▁end|> | const config = Object.assign({}, baseConfig)
config.outputPath = path.join(__dirname, '../dist-' + config.app)
|
<|file_name|>all.js<|end_file_name|><|fim▁begin|>module.exports = flatten([
require("./base/dualfilter"),
require("./base/filter"),
require("./base/mirrorBlocks"),
require("./base/overlayMask"),
require("./base/split"),
require("./base/splitMask"),
require("./colourset/lerp"),
require("./colourset/distinct"),
require("./colourset/chunks"),
require("./colourset/alpha"),
require("./extras/swatch"),
require("./extras/text"),
require("./filter/bevel"),<|fim▁hole|> require("./filter/sharpen"),
require("./filter/splash"),
require("./lines/straight"),
require("./lines/curve"),
require("./lines/scribble"),
require("./mask/halfmask"),
require("./overlay/lines"),
require("./overlay/network"),
require("./overlay/shapes"),
require("./overlay/sparkles"),
require("./pallete/monochrome"),
require("./pallete/hightlightAndMidtone"),
require("./pallete/bicolor"),
require("./pointset/static"),
require("./pointset/linear"),
require("./pointset/circular"),
require("./pointset/grid"),
require("./pointset/spiral"),
require("./pointset/tree"),
require("./shapes/polygon"),
require("./shapes/stars"),
require("./shapes/ring"),
require("./shapes/circle"),
require("./simple/blockColor"),
require("./simple/blockOverlay"),
require("./spacial/radial"),
require("./spacial/chaos"),
require("./spacial/linear"),
require("./tiles/squares"),
require("./tiles/triangles"),
])
function flatten( m ){
var retval = [];
for ( var id in m ){
if ( m[id].push ){
retval = retval.concat(m[id]);
}else{
retval.push(m[id]);
}
}
return retval;
}<|fim▁end|> | require("./filter/disolve"),
require("./filter/roughen"), |
<|file_name|>health-report.js<|end_file_name|><|fim▁begin|>/* SPDX-License-Identifier: MIT */
function GHDataReport(apiUrl) {
apiUrl = apiUrl || '/';
var owner = this.getParameterByName('owner');
var repo = this.getParameterByName('repo');
this.api = new GHDataAPIClient(apiUrl, owner, repo);
this.buildReport();
}
GHDataReport.prototype.getParameterByName = function(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
};
GHDataReport.prototype.buildReport = function () {
if (this.api.owner && this.api.repo) {<|fim▁hole|> // Commits
this.api.commitsByWeek().then(function (commits) {
MG.data_graphic({
title: "Commits/Week",
data: MG.convert.date(commits, 'date', '%Y-%m-%dT%H:%M:%S.%LZ'),
chart_type: 'point',
least_squares: true,
full_width: true,
height: 300,
color_range: ['#aaa'],
x_accessor: 'date',
y_accessor: 'commits',
target: '#commits-over-time'
});
});
// Stargazers
this.api.stargazersByWeek().then(function (stargazers) {
MG.data_graphic({
title: "Stars/Week",
data: MG.convert.date(stargazers, 'date', '%Y-%m-%dT%H:%M:%S.%LZ'),
chart_type: 'point',
least_squares: true,
full_width: true,
height: 300,
color_range: ['#aaa'],
x_accessor: 'date',
y_accessor: 'watchers',
target: '#stargazers-over-time'
});
});
// Forks
this.api.forksByWeek().then(function (forks) {
MG.data_graphic({
title: "Forks/Week",
data: MG.convert.date(forks, 'date', '%Y-%m-%dT%H:%M:%S.%LZ'),
chart_type: 'point',
least_squares: true,
full_width: true,
height: 300,
color_range: ['#aaa'],
x_accessor: 'date',
y_accessor: 'projects',
target: '#forks-over-time'
});
});
// Issues
this.api.issuesByWeek().then(function (issues) {
MG.data_graphic({
title: "Issues/Week",
data: MG.convert.date(issues, 'date', '%Y-%m-%dT%H:%M:%S.%LZ'),
chart_type: 'point',
least_squares: true,
full_width: true,
height: 300,
color_range: ['#aaa'],
x_accessor: 'date',
y_accessor: 'issues',
target: '#issues-over-time'
});
});
// Pull Requests
this.api.pullRequestsByWeek().then(function (pulls) {
MG.data_graphic({
title: "Pull Requests/Week",
data: MG.convert.date(pulls, 'date', '%Y-%m-%dT%H:%M:%S.%LZ'),
chart_type: 'point',
least_squares: true,
full_width: true,
height: 300,
color_range: ['#aaa'],
x_accessor: 'date',
y_accessor: 'pull_requests',
target: '#pulls-over-time'
});
});
}
};
var client = new GHDataReport();<|fim▁end|> | document.getElementById('repo-label').innerHTML = this.api.owner + ' / ' + this.api.repo; |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>elementResizeEvent = require('../index.js');
element = document.getElementById("resize");
window.p = p = document.getElementById("width");
console.log(p);
console.log(elementResizeEvent);<|fim▁hole|> console.log("resized!");
console.log(element.offsetWidth);
console.log(p);
console.log(element.offsetWidth + "px wide");
p.innerHTML = element.offsetWidth + "px wide";
}));<|fim▁end|> | console.log(elementResizeEvent(element, function() { |
<|file_name|>handleBlockType-test.js<|end_file_name|><|fim▁begin|>import { expect } from 'chai';
import Draft, { EditorState, SelectionState } from 'draft-js';
import handleBlockType from '../handleBlockType';
describe('handleBlockType', () => {
describe('no markup', () => {
const rawContentState = {
entityMap: {},
blocks: [
{
key: 'item1',
text: '[ ]',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
};
const contentState = Draft.convertFromRaw(rawContentState);
const selection = new SelectionState({
anchorKey: 'item1',
anchorOffset: 3,
focusKey: 'item1',
focusOffset: 3,
isBackward: false,
hasFocus: true,
});
const editorState = EditorState.forceSelection(EditorState.createWithContent(contentState), selection);
it('does not convert block type', () => {
const newEditorState = handleBlockType(editorState, ' ');
expect(newEditorState).to.equal(editorState);
expect(Draft.convertToRaw(newEditorState.getCurrentContent())).to.deep.equal(rawContentState);
});
});
const testCases = {
'converts from unstyled to header-one': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '# Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'header-one',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 6,
focusKey: 'item1',
focusOffset: 6,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to header-two': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '## Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'header-two',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 7,
focusKey: 'item1',
focusOffset: 7,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to header-three': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '### Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'header-three',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 8,
focusKey: 'item1',
focusOffset: 8,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to header-four': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '#### Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'header-four',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 9,
focusKey: 'item1',
focusOffset: 9,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to header-five': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '##### Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'header-five',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 10,
focusKey: 'item1',
focusOffset: 10,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to header-six': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '###### Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},<|fim▁hole|> },
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'header-six',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 11,
focusKey: 'item1',
focusOffset: 11,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to unordered-list-item with hyphen': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '- Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'unordered-list-item',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 6,
focusKey: 'item1',
focusOffset: 6,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to unordered-list-item with astarisk': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '* Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'unordered-list-item',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 6,
focusKey: 'item1',
focusOffset: 6,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to ordered-list-item': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '2. Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'ordered-list-item',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 7,
focusKey: 'item1',
focusOffset: 7,
isBackward: false,
hasFocus: true,
}),
},
'converts from unordered-list-item to unchecked checkable-list-item': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '[] Test',
type: 'unordered-list-item',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test',
type: 'checkable-list-item',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {
checked: false,
},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 1,
focusKey: 'item1',
focusOffset: 1,
isBackward: false,
hasFocus: true,
}),
},
'converts from unordered-list-item to checked checkable-list-item': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '[x]Test',
type: 'unordered-list-item',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test',
type: 'checkable-list-item',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {
checked: true,
},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 3,
focusKey: 'item1',
focusOffset: 3,
isBackward: false,
hasFocus: true,
}),
},
'converts from unstyled to blockquote': {
before: {
entityMap: {},
blocks: [
{
key: 'item1',
text: '> Test',
type: 'unstyled',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
after: {
entityMap: {},
blocks: [
{
key: 'item1',
text: 'Test ',
type: 'blockquote',
depth: 0,
inlineStyleRanges: [],
entityRanges: [],
data: {},
},
],
},
selection: new SelectionState({
anchorKey: 'item1',
anchorOffset: 6,
focusKey: 'item1',
focusOffset: 6,
isBackward: false,
hasFocus: true,
}),
},
};
Object.keys(testCases).forEach(k => {
describe(k, () => {
const testCase = testCases[k];
const { before, after, selection, character = ' ' } = testCase;
const contentState = Draft.convertFromRaw(before);
const editorState = EditorState.forceSelection(EditorState.createWithContent(contentState), selection);
it('converts block type', () => {
const newEditorState = handleBlockType(editorState, character);
expect(newEditorState).not.to.equal(editorState);
expect(Draft.convertToRaw(newEditorState.getCurrentContent())).to.deep.equal(after);
});
});
});
});<|fim▁end|> | ], |
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>/**
* iOS and Android apis should match.
* It doesn't matter if you export `.ios` or `.android`, either one but only one.
*/
// export * from './mip';
// export * from './mip-finder';
// export * from './ble-utils';
// export * from './bluetooth.scanner."
// export * from './codes"
// export * from './mip-controller"
// export * from './mip-device"
// export * from './mip-status-reader"<|fim▁hole|>
// export * from './mip.android';
// export * from './mip-finder.android';
// export * from './ble-utils.android';
// Export any shared classes, constants, etc.
//export * from './mip.common';<|fim▁end|> | // export * from './mip-types" |
<|file_name|>isdict_containingentries.py<|end_file_name|><|fim▁begin|>from hamcrest.core.base_matcher import BaseMatcher
from hamcrest.core.helpers.hasmethod import hasmethod
from hamcrest.core.helpers.wrap_matcher import wrap_matcher
__author__ = "Jon Reid"
__copyright__ = "Copyright 2011 hamcrest.org"
__license__ = "BSD, see License.txt"
class IsDictContainingEntries(BaseMatcher):
def __init__(self, value_matchers):
self.value_matchers = sorted(value_matchers.items())
def _not_a_dictionary(self, dictionary, mismatch_description):
if mismatch_description:
mismatch_description.append_description_of(dictionary) \
.append_text(' is not a mapping object')
return False
def matches(self, dictionary, mismatch_description=None):
for key, value_matcher in self.value_matchers:
try:
if not key in dictionary:
if mismatch_description:
mismatch_description.append_text('no ') \
.append_description_of(key) \
.append_text(' key in ') \
.append_description_of(dictionary)
return False
except TypeError:
return self._not_a_dictionary(dictionary, mismatch_description)
try:
actual_value = dictionary[key]
except TypeError:
return self._not_a_dictionary(dictionary, mismatch_description)
if not value_matcher.matches(actual_value):
if mismatch_description:
mismatch_description.append_text('value for ') \
.append_description_of(key) \
.append_text(' ')
value_matcher.describe_mismatch(actual_value, mismatch_description)
return False
return True
def describe_mismatch(self, item, mismatch_description):
self.matches(item, mismatch_description)
def describe_keyvalue(self, index, value, description):
"""Describes key-value pair at given index."""
description.append_description_of(index) \
.append_text(': ') \
.append_description_of(value)
def describe_to(self, description):
description.append_text('a dictionary containing {')
first = True
for key, value in self.value_matchers:
if not first:
description.append_text(', ')
self.describe_keyvalue(key, value, description)
first = False
description.append_text('}')
def has_entries(*keys_valuematchers, **kv_args):
"""Matches if dictionary contains entries satisfying a dictionary of keys<|fim▁hole|> and corresponding value matchers.
:param matcher_dict: A dictionary mapping keys to associated value matchers,
or to expected values for
:py:func:`~hamcrest.core.core.isequal.equal_to` matching.
Note that the keys must be actual keys, not matchers. Any value argument
that is not a matcher is implicitly wrapped in an
:py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
equality.
Examples::
has_entries({'foo':equal_to(1), 'bar':equal_to(2)})
has_entries({'foo':1, 'bar':2})
``has_entries`` also accepts a list of keyword arguments:
.. function:: has_entries(keyword1=value_matcher1[, keyword2=value_matcher2[, ...]])
:param keyword1: A keyword to look up.
:param valueMatcher1: The matcher to satisfy for the value, or an expected
value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
Examples::
has_entries(foo=equal_to(1), bar=equal_to(2))
has_entries(foo=1, bar=2)
Finally, ``has_entries`` also accepts a list of alternating keys and their
value matchers:
.. function:: has_entries(key1, value_matcher1[, ...])
:param key1: A key (not a matcher) to look up.
:param valueMatcher1: The matcher to satisfy for the value, or an expected
value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
Examples::
has_entries('foo', equal_to(1), 'bar', equal_to(2))
has_entries('foo', 1, 'bar', 2)
"""
if len(keys_valuematchers) == 1:
try:
base_dict = keys_valuematchers[0].copy()
for key in base_dict:
base_dict[key] = wrap_matcher(base_dict[key])
except AttributeError:
raise ValueError('single-argument calls to has_entries must pass a dict as the argument')
else:
if len(keys_valuematchers) % 2:
raise ValueError('has_entries requires key-value pairs')
base_dict = {}
for index in range(int(len(keys_valuematchers) / 2)):
base_dict[keys_valuematchers[2 * index]] = wrap_matcher(keys_valuematchers[2 * index + 1])
for key, value in kv_args.items():
base_dict[key] = wrap_matcher(value)
return IsDictContainingEntries(base_dict)<|fim▁end|> | |
<|file_name|>secure_tempfile.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import base64
import os
import io
import six
from tempfile import _TemporaryFileWrapper
from pretty_bad_protocol._util import _STREAMLIKE_TYPES
from cryptography.exceptions import AlreadyFinalized
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers.algorithms import AES
from cryptography.hazmat.primitives.ciphers.modes import CTR
from cryptography.hazmat.primitives.ciphers import Cipher
class SecureTemporaryFile(_TemporaryFileWrapper, object):
"""Temporary file that provides on-the-fly encryption.
Buffering large submissions in memory as they come in requires too
much memory for too long a period. By writing the file to disk as it
comes in using a stream cipher, we are able to minimize memory usage
as submissions come in, while minimizing the chances of plaintext
recovery through forensic disk analysis. They key used to encrypt
each secure temporary file is also ephemeral, and is only stored in
memory only for as long as needed.
Adapted from Globaleaks' GLSecureTemporaryFile:
https://github.com/globaleaks/GlobaLeaks/blob/master/backend/globaleaks/security.py#L35
WARNING: you can't use this like a normal file object. It supports
being appended to however many times you wish (although content may not be
overwritten), and then it's contents may be read only once (although it may
be done in chunks) and only after it's been written to.
"""
AES_key_size = 256
AES_block_size = 128
def __init__(self, store_dir):
"""Generates an AES key and an initialization vector, and opens
a file in the `store_dir` directory with a
pseudorandomly-generated filename.
Args:
store_dir (str): the directory to create the secure
temporary file under.
Returns: self
"""
self.last_action = 'init'
self.create_key()
data = base64.urlsafe_b64encode(os.urandom(32))
if not six.PY2: # For Python3
self.tmp_file_id = data.decode('utf-8').strip('=')
else:
self.tmp_file_id = data.strip('=')
self.filepath = os.path.join(store_dir,
'{}.aes'.format(self.tmp_file_id))
self.file = io.open(self.filepath, 'w+b')
super(SecureTemporaryFile, self).__init__(self.file, self.filepath)
def create_key(self):
"""Generates a unique, pseudorandom AES key, stored ephemerally in
memory as an instance attribute. Its destruction is ensured by the
automatic nightly reboots of the SecureDrop application server combined
with the freed memory-overwriting PAX_MEMORY_SANITIZE feature of the
grsecurity-patched kernel it uses (for further details consult
https://github.com/freedomofpress/securedrop/pull/477#issuecomment-168445450).
"""
self.key = os.urandom(self.AES_key_size // 8)
self.iv = os.urandom(self.AES_block_size // 8)
self.initialize_cipher()
def initialize_cipher(self):
"""Creates the cipher-related objects needed for AES-CTR
encryption and decryption.
"""
self.cipher = Cipher(AES(self.key), CTR(self.iv), default_backend())
self.encryptor = self.cipher.encryptor()
self.decryptor = self.cipher.decryptor()
def write(self, data):
"""Write `data` to the secure temporary file. This method may be
called any number of times following instance initialization,
but after calling :meth:`read`, you cannot write to the file
again.
"""
if self.last_action == 'read':
raise AssertionError('You cannot write after reading!')
self.last_action = 'write'
# This is the old Python related code
if six.PY2: # noqa
if isinstance(data, unicode):
data = data.encode('utf-8')
elif isinstance(data, str): # noqa
# For Python 3
data = data.encode('utf-8')
self.file.write(self.encryptor.update(data))
def read(self, count=None):
"""Read `data` from the secure temporary file. This method may
be called any number of times following instance initialization
and once :meth:`write has been called at least once, but not
before.
Before the first read operation, `seek(0, 0)` is called. So
while you can call this method any number of times, the full
contents of the file can only be read once. Additional calls to
read will return an empty str, which is desired behavior in that
it matches :class:`file` and because other modules depend on
this behavior to let them know they've reached the end of the
file.
Args:
count (int): the number of bytes to try to read from the
file from the current position.
"""
if self.last_action == 'init':
raise AssertionError('You must write before reading!')
if self.last_action == 'write':
self.seek(0, 0)
self.last_action = 'read'
if count:
return self.decryptor.update(self.file.read(count))
else:
return self.decryptor.update(self.file.read())
def close(self):
"""The __del__ method in tempfile._TemporaryFileWrapper (which
SecureTemporaryFile class inherits from) calls close() when the
temporary file is deleted.
"""<|fim▁hole|> except AlreadyFinalized:
pass
# Since tempfile._TemporaryFileWrapper.close() does other cleanup,
# (i.e. deleting the temp file on disk), we need to call it also.
super(SecureTemporaryFile, self).close()
# python-gnupg will not recognize our SecureTemporaryFile as a stream-like type
# and will attempt to call encode on it, thinking it's a string-like type. To
# avoid this we append it the list of stream-like types.
_STREAMLIKE_TYPES.append(_TemporaryFileWrapper)<|fim▁end|> | try:
self.decryptor.finalize() |
<|file_name|>testimages.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
from time import sleep
import os
import RPi.GPIO as GPIO
import subprocess
import datetime
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN)
count = 0
up = False
down = False
command = ""
filename = ""
index = 0
camera_pause = "500"
def takepic(imageName):
print("picture")
command = "sudo raspistill -o " + imageName + " -q 100 -t " + camera_pause
print(command)
os.system(command)
while(True):
if(up==True):
if(GPIO.input(24)==False):<|fim▁hole|> timeString = now.strftime("%Y-%m-%d_%H%M%S")
filename = "photo-"+timeString+".jpg"
takepic(filename)
subprocess.call(['./processImage.sh', filename, '&'])
up = GPIO.input(24)
count = count+1
sleep(.1)
print "done"<|fim▁end|> | now = datetime.datetime.now() |
<|file_name|>simple.rs<|end_file_name|><|fim▁begin|>use common::{EmailAddress, AddrError};
/// Performs a dead-simple parse of an email address.
pub fn parse(input: &str) -> Result<EmailAddress, AddrError> {
if input.is_empty() {
return Err(AddrError { msg: "empty string is not valid".to_string() });
}
let parts: Vec<&str> = input.rsplitn(1, '@').collect();
if parts[0].is_empty() {
return Err(AddrError { msg: "empty string is not valid for local part".to_string() });
}
if parts[1].is_empty() {<|fim▁hole|> }
Ok(EmailAddress {
local: parts[1].to_string(),
domain: parts[0].to_string()
})
}
#[cfg(test)]
mod test {
use super::*;
use common::{EmailAddress};
#[test]
fn test_simple_parse() {
assert_eq!(
parse("[email protected]").unwrap(),
EmailAddress {
local: "someone".to_string(),
domain: "example.com".to_string()
}
);
}
}<|fim▁end|> | return Err(AddrError { msg: "empty string is not valid for domain part".to_string() }); |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .main import HnsccVisitAdmin, HnsccOffStudyAdmin
from .enrollment_admin import EnrollmentAdmin
from .contemporary_admin import ContemporaryAdmin<|fim▁hole|><|fim▁end|> | # from .historical_admin import HistoricalAdmin
from .hnscc_off_study_model_admin import HnsccOffStudyModelAdmin |
<|file_name|>exportDeclarationInInternalModule.js<|end_file_name|><|fim▁begin|>//// [exportDeclarationInInternalModule.ts]
class Bbb {
}
class Aaa extends Bbb { }
module Aaa {
export class SomeType { }
}
module Bbb {
export class SomeType { }
export * from Aaa; // this line causes the nullref
}
var a: Bbb.SomeType;
//// [exportDeclarationInInternalModule.js]
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Bbb = (function () {
function Bbb() {
}
return Bbb;
}());
var Aaa = (function (_super) {
__extends(Aaa, _super);
function Aaa() {
_super.apply(this, arguments);
}
return Aaa;
}(Bbb));
var Aaa;
<|fim▁hole|> function SomeType() {
}
return SomeType;
}());
Aaa.SomeType = SomeType;
})(Aaa || (Aaa = {}));
var Bbb;
(function (Bbb) {
var SomeType = (function () {
function SomeType() {
}
return SomeType;
}());
Bbb.SomeType = SomeType;
// this line causes the nullref
})(Bbb || (Bbb = {}));
var a;
//// [exportDeclarationInInternalModule.d.ts]
declare class Bbb {
}
declare class Aaa extends Bbb {
}
declare module Aaa {
class SomeType {
}
}
declare module Bbb {
class SomeType {
}
export * from Aaa;
}
declare var a: Bbb.SomeType;<|fim▁end|> | (function (Aaa) {
var SomeType = (function () {
|
<|file_name|>recipe-576734.py<|end_file_name|><|fim▁begin|>import ctypes
class C_struct:
"""Decorator to convert the given class into a C struct."""
# contains a dict of all known translatable types
types = ctypes.__dict__
<|fim▁hole|> @classmethod
def register_type(cls, typename, obj):
"""Adds the new class to the dict of understood types."""
cls.types[typename] = obj
def __call__(self, cls):
"""Converts the given class into a C struct.
Usage:
>>> @C_struct()
... class Account:
... first_name = "c_char_p"
... last_name = "c_char_p"
... balance = "c_float"
...
>>> a = Account()
>>> a
<cstruct.Account object at 0xb7c0ee84>
A very important note: while it *is* possible to
instantiate these classes as follows:
>>> a = Account("Geremy", "Condra", 0.42)
This is strongly discouraged, because there is at
present no way to ensure what order the field names
will be read in.
"""
# build the field mapping (names -> types)
fields = []
for k, v in vars(cls).items():
# don't wrap private variables
if not k.startswith("_"):
# if its a pointer
if v.startswith("*"):
field_type = ctypes.POINTER(self.types[v[1:]])
else:
field_type = self.types[v]
new_field = (k, field_type)
fields.append(new_field)
# make our bases tuple
bases = (ctypes.Structure,) + tuple((base for base in cls.__bases__))
# finish up our wrapping dict
class_attrs = {"_fields_": fields, "__doc__": cls.__doc__}
# now create our class
return type(cls.__name__, bases, class_attrs)<|fim▁end|> | |
<|file_name|>Commands.go<|end_file_name|><|fim▁begin|>package cmd
import (
"fmt"
"os"
"gopkg.in/alecthomas/kingpin.v2"
"github.com/guzzlerio/corcel/config"
"github.com/guzzlerio/corcel/core"
"github.com/guzzlerio/corcel/errormanager"
"github.com/guzzlerio/corcel/logger"
"github.com/guzzlerio/corcel/report"
)
// ServerCommand ...
type ServerCommand struct {
Port int
registry *core.Registry
}
//NewServerCommand ...
func NewServerCommand(app *kingpin.Application, registry *core.Registry) {
c := &ServerCommand{
registry: registry,
}
server := app.Command("server", "Start HTTP server").Action(c.run)
server.Flag("port", "Port").Default("54332").IntVar(&c.Port)
}
func (this *ServerCommand) run(c *kingpin.ParseContext) error {
// have access to c.registry
//Start HTTP Server
// construct HTTP Host
// Start HTTP Host from cmd options
fmt.Printf("Would now be starting the HTTP server on %v\n", this.Port)
return nil
}<|fim▁hole|>// RunCommand ...
type RunCommand struct {
Config *config.Configuration
registry *core.Registry
summaryBuilders *core.SummaryBuilderFactory
}
//NewRunCommand ...
func NewRunCommand(app *kingpin.Application, registry *core.Registry, summaryBuilders *core.SummaryBuilderFactory) {
configuration := &config.Configuration{}
c := &RunCommand{
Config: configuration,
registry: registry,
summaryBuilders: summaryBuilders,
}
run := app.Command("run", "Execute performance test thing").Action(c.run)
run.Arg("file", "Corcel file contains URLs or an ExecutionPlan (see the --plan argument)").Required().StringVar(&configuration.FilePath)
run.Flag("summary", "Output summary to STDOUT").BoolVar(&configuration.Summary)
run.Flag("summary-format", "Format for the summary").Default("console").EnumVar(&configuration.SummaryFormat, "console", "json", "yaml")
run.Flag("iterations", "The number of iterations to run").Short('i').Default("0").IntVar(&configuration.Iterations)
run.Flag("duration", "The duration of the run e.g. 10s 10m 10h etc... valid values are ms, s, m, h").Short('d').Default("0s").DurationVar(&configuration.Duration)
run.Flag("wait-time", "Time to wait between each execution").Default("0s").Short('t').DurationVar(&configuration.WaitTime)
run.Flag("workers", "The number of workers to execute the requests").Short('w').IntVar(&configuration.Workers)
run.Flag("random", "Select the url at random for each execution").Short('r').BoolVar(&configuration.Random)
run.Flag("plan", "Indicate that the corcel file is an ExecutionPlan").BoolVar(&configuration.Plan)
run.Flag("verbose", "verbosity").Short('v').Action(config.Counter).Bool()
run.Flag("progress", "Progress reporter").EnumVar(&configuration.Progress, "bar", "logo", "none")
}
func (this *RunCommand) run(c *kingpin.ParseContext) error {
configuration, err := config.ParseConfiguration(this.Config)
if err != nil {
errormanager.Log(err)
panic("REPLACE ME THIS IS TEMP")
os.Exit(1)
}
logger.ConfigureLogging(configuration)
//This will not be anything other than a Console Host as we are working with Run command and Server command. In essence being in this method means we are inside the Console Host.
app := Application{}
output := app.Execute(configuration)
reporter := report.CreateHTMLReporter()
reporter.Generate(output)
if configuration.Summary {
summary := output.CreateSummary()
summaryBuilder := this.summaryBuilders.Get(configuration.SummaryFormat)
summaryBuilder.Write(summary)
}
return nil
}
func check(err error) {
if err != nil {
errormanager.Log(err)
}
}<|fim▁end|> | |
<|file_name|>fst_module_aux.py<|end_file_name|><|fim▁begin|># FST tests related classes
# Copyright (c) 2015, Qualcomm Atheros, Inc.
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
import logging
import os
import signal
import time
import re
import hostapd
import wpaspy
import utils
from wpasupplicant import WpaSupplicant
import fst_test_common
logger = logging.getLogger()
def parse_fst_iface_event(ev):
"""Parses FST iface event that comes as a string, e.g.
"<3>FST-EVENT-IFACE attached ifname=wlan9 group=fstg0"
Returns a dictionary with parsed "event_type", "ifname", and "group"; or
None if not an FST event or can't be parsed."""
event = {}
if ev.find("FST-EVENT-IFACE") == -1:
return None
if ev.find("attached") != -1:
event['event_type'] = 'attached'
elif ev.find("detached") != -1:
event['event_type'] = 'detached'
else:
return None
f = re.search("ifname=(\S+)", ev)
if f is not None:
event['ifname'] = f.group(1)
f = re.search("group=(\S+)", ev)
if f is not None:
event['group'] = f.group(1)
return event
def parse_fst_session_event(ev):
"""Parses FST session event that comes as a string, e.g.
"<3>FST-EVENT-SESSION event_type=EVENT_FST_SESSION_STATE session_id=0 reason=REASON_STT"
Returns a dictionary with parsed "type", "id", and "reason"; or None if not
a FST event or can't be parsed"""
event = {}
if ev.find("FST-EVENT-SESSION") == -1:
return None
event['new_state'] = '' # The field always exists in the dictionary
f = re.search("event_type=(\S+)", ev)
if f is None:
return None
event['type'] = f.group(1)
f = re.search("session_id=(\d+)", ev)
if f is not None:
event['id'] = f.group(1)
f = re.search("old_state=(\S+)", ev)
if f is not None:
event['old_state'] = f.group(1)
f = re.search("new_state=(\S+)", ev)
if f is not None:
event['new_state'] = f.group(1)
f = re.search("reason=(\S+)", ev)
if f is not None:
event['reason'] = f.group(1)
return event
def start_two_ap_sta_pairs(apdev, rsn=False):
"""auxiliary function that creates two pairs of APs and STAs"""
ap1 = FstAP(apdev[0]['ifname'], 'fst_11a', 'a',
fst_test_common.fst_test_def_chan_a,
fst_test_common.fst_test_def_group,
fst_test_common.fst_test_def_prio_low,
fst_test_common.fst_test_def_llt, rsn=rsn)
ap1.start()
ap2 = FstAP(apdev[1]['ifname'], 'fst_11g', 'g',
fst_test_common.fst_test_def_chan_g,
fst_test_common.fst_test_def_group,
fst_test_common.fst_test_def_prio_high,
fst_test_common.fst_test_def_llt, rsn=rsn)
ap2.start()
sta1 = FstSTA('wlan5',
fst_test_common.fst_test_def_group,
fst_test_common.fst_test_def_prio_low,
fst_test_common.fst_test_def_llt, rsn=rsn)
sta1.start()
sta2 = FstSTA('wlan6',
fst_test_common.fst_test_def_group,
fst_test_common.fst_test_def_prio_high,
fst_test_common.fst_test_def_llt, rsn=rsn)
sta2.start()
return ap1, ap2, sta1, sta2
def stop_two_ap_sta_pairs(ap1, ap2, sta1, sta2):
sta1.stop()
sta2.stop()
ap1.stop()
ap2.stop()
fst_test_common.fst_clear_regdom()
def connect_two_ap_sta_pairs(ap1, ap2, dev1, dev2, rsn=False):
"""Connects a pair of stations, each one to a separate AP"""
dev1.scan(freq=fst_test_common.fst_test_def_freq_a)
dev2.scan(freq=fst_test_common.fst_test_def_freq_g)
if rsn:
dev1.connect(ap1, psk="12345678",
scan_freq=fst_test_common.fst_test_def_freq_a)
dev2.connect(ap2, psk="12345678",
scan_freq=fst_test_common.fst_test_def_freq_g)
else:
dev1.connect(ap1, key_mgmt="NONE",
scan_freq=fst_test_common.fst_test_def_freq_a)
dev2.connect(ap2, key_mgmt="NONE",
scan_freq=fst_test_common.fst_test_def_freq_g)
def disconnect_two_ap_sta_pairs(ap1, ap2, dev1, dev2):
dev1.disconnect()
dev2.disconnect()
def external_sta_connect(sta, ap, **kwargs):
"""Connects the external station to the given AP"""
if not isinstance(sta, WpaSupplicant):
raise Exception("Bad STA object")
if not isinstance(ap, FstAP):
raise Exception("Bad AP object to connect to")
hap = ap.get_instance()
sta.connect(ap.get_ssid(), **kwargs)
def disconnect_external_sta(sta, ap, check_disconnect=True):
"""Disconnects the external station from the AP"""
if not isinstance(sta, WpaSupplicant):
raise Exception("Bad STA object")
if not isinstance(ap, FstAP):
raise Exception("Bad AP object to connect to")
sta.request("DISCONNECT")
if check_disconnect:
hap = ap.get_instance()
ev = hap.wait_event(["AP-STA-DISCONNECTED"], timeout=10)
if ev is None:
raise Exception("No disconnection event received from %s" % ap.get_ssid())
#
# FstDevice class
# This is the parent class for the AP (FstAP) and STA (FstSTA) that implements
# FST functionality.
#
class FstDevice:
def __init__(self, iface, fst_group, fst_pri, fst_llt=None, rsn=False):
self.iface = iface
self.fst_group = fst_group
self.fst_pri = fst_pri
self.fst_llt = fst_llt # None llt means no llt parameter will be set
self.instance = None # Hostapd/WpaSupplicant instance
self.peer_obj = None # Peer object, must be a FstDevice child object
self.new_peer_addr = None # Peer MAC address for new session iface
self.old_peer_addr = None # Peer MAC address for old session iface
self.role = 'initiator' # Role: initiator/responder
s = self.grequest("FST-MANAGER TEST_REQUEST IS_SUPPORTED")
if not s.startswith('OK'):
raise utils.HwsimSkip("FST not supported")
self.rsn = rsn
def ifname(self):
return self.iface
def get_instance(self):
"""Gets the Hostapd/WpaSupplicant instance"""
raise Exception("Virtual get_instance() called!")
def get_own_mac_address(self):
"""Gets the device's own MAC address"""
raise Exception("Virtual get_own_mac_address() called!")
def get_new_peer_addr(self):
return self.new_peer_addr
def get_old_peer_addr(self):
return self.old_peer_addr
def get_actual_peer_addr(self):
"""Gets the peer address. A connected AP/station address is returned."""
raise Exception("Virtual get_actual_peer_addr() called!")
def grequest(self, req):
"""Send request on the global control interface"""
raise Exception("Virtual grequest() called!")
def wait_gevent(self, events, timeout=None):
"""Wait for a list of events on the global interface"""
raise Exception("Virtual wait_gevent() called!")
def request(self, req):
"""Issue a request to the control interface"""
h = self.get_instance()
return h.request(req)
def wait_event(self, events, timeout=None):
"""Wait for an event from the control interface"""
h = self.get_instance()
if timeout is not None:
return h.wait_event(events, timeout=timeout)
else:
return h.wait_event(events)
def set_old_peer_addr(self, peer_addr=None):
"""Sets the peer address"""
if peer_addr is not None:
self.old_peer_addr = peer_addr
else:
self.old_peer_addr = self.get_actual_peer_addr()
def set_new_peer_addr(self, peer_addr=None):
"""Sets the peer address"""
if peer_addr is not None:
self.new_peer_addr = peer_addr
else:
self.new_peer_addr = self.get_actual_peer_addr()
def add_peer(self, obj, old_peer_addr=None, new_peer_addr=None):
"""Add peer for FST session(s). 'obj' is a FstDevice subclass object.
The method must be called before add_session().
If peer_addr is not specified, the address of the currently connected
station is used."""
if not isinstance(obj, FstDevice):
raise Exception("Peer must be a FstDevice object")
self.peer_obj = obj
self.set_old_peer_addr(old_peer_addr)
self.set_new_peer_addr(new_peer_addr)
def get_peer(self):
"""Returns peer object"""
return self.peer_obj
def set_fst_parameters(self, group_id=None, pri=None, llt=None):
"""Change/set new FST parameters. Can be used to start FST sessions with
different FST parameters than defined in the configuration file."""
if group_id is not None:
self.fst_group = group_id
if pri is not None:
self.fst_pri = pri
if llt is not None:
self.fst_llt = llt
def get_local_mbies(self, ifname=None):
if_name = ifname if ifname is not None else self.iface
return self.grequest("FST-MANAGER TEST_REQUEST GET_LOCAL_MBIES " + if_name)
def add_session(self):
"""Adds an FST session. add_peer() must be called calling this
function"""
if self.peer_obj is None:
raise Exception("Peer wasn't added before starting session")
self.dump_monitor()
grp = ' ' + self.fst_group if self.fst_group != '' else ''
sid = self.grequest("FST-MANAGER SESSION_ADD" + grp)
sid = sid.strip()
if sid.startswith("FAIL"):
raise Exception("Cannot add FST session with groupid ==" + grp)
self.dump_monitor()
return sid
def set_session_param(self, params):
request = "FST-MANAGER SESSION_SET"
if params is not None and params != '':
request = request + ' ' + params
return self.grequest(request)
def get_session_params(self, sid):
request = "FST-MANAGER SESSION_GET " + sid
res = self.grequest(request)
if res.startswith("FAIL"):
return None
params = {}
for i in res.splitlines():
p = i.split('=')
params[p[0]] = p[1]
return params
def iface_peers(self, ifname):
grp = self.fst_group if self.fst_group != '' else ''
res = self.grequest("FST-MANAGER IFACE_PEERS " + grp + ' ' + ifname)
if res.startswith("FAIL"):
return None
return res.splitlines()
def get_peer_mbies(self, ifname, peer_addr):
return self.grequest("FST-MANAGER GET_PEER_MBIES %s %s" % (ifname, peer_addr))
def list_ifaces(self):
grp = self.fst_group if self.fst_group != '' else ''
res = self.grequest("FST-MANAGER LIST_IFACES " + grp)
if res.startswith("FAIL"):
return None
ifaces = []
for i in res.splitlines():
p = i.split(':')
iface = {}
iface['name'] = p[0]
iface['priority'] = p[1]
iface['llt'] = p[2]
ifaces.append(iface)
return ifaces
def list_groups(self):
res = self.grequest("FST-MANAGER LIST_GROUPS")
if res.startswith("FAIL"):
return None
return res.splitlines()
def configure_session(self, sid, new_iface, old_iface=None):
"""Calls session_set for a number of parameters some of which are stored
in "self" while others are passed to this function explicitly. If
old_iface is None, current iface is used; if old_iface is an empty
string."""
self.dump_monitor()
oldiface = old_iface if old_iface is not None else self.iface
s = self.set_session_param(sid + ' old_ifname=' + oldiface)
if not s.startswith("OK"):
raise Exception("Cannot set FST session old_ifname: " + s)
if new_iface is not None:
s = self.set_session_param(sid + " new_ifname=" + new_iface)
if not s.startswith("OK"):
raise Exception("Cannot set FST session new_ifname:" + s)
if self.new_peer_addr is not None and self.new_peer_addr != '':
s = self.set_session_param(sid + " new_peer_addr=" + self.new_peer_addr)
if not s.startswith("OK"):
raise Exception("Cannot set FST session peer address:" + s + " (new)")
if self.old_peer_addr is not None and self.old_peer_addr != '':
s = self.set_session_param(sid + " old_peer_addr=" + self.old_peer_addr)
if not s.startswith("OK"):
raise Exception("Cannot set FST session peer address:" + s + " (old)")
if self.fst_llt is not None and self.fst_llt != '':
s = self.set_session_param(sid + " llt=" + self.fst_llt)
if not s.startswith("OK"):
raise Exception("Cannot set FST session llt:" + s)
self.dump_monitor()
def send_iface_attach_request(self, ifname, group, llt, priority):
request = "FST-ATTACH " + ifname + ' ' + group
if llt is not None:
request += " llt=" + llt
if priority is not None:
request += " priority=" + priority
res = self.grequest(request)
if not res.startswith("OK"):
raise Exception("Cannot attach FST iface: " + res)
def send_iface_detach_request(self, ifname):
res = self.grequest("FST-DETACH " + ifname)
if not res.startswith("OK"):
raise Exception("Cannot detach FST iface: " + res)
def send_session_setup_request(self, sid):
s = self.grequest("FST-MANAGER SESSION_INITIATE " + sid)
if not s.startswith('OK'):
raise Exception("Cannot send setup request: %s" % s)
return s
def send_session_setup_response(self, sid, response):
request = "FST-MANAGER SESSION_RESPOND " + sid + " " + response
s = self.grequest(request)
if not s.startswith('OK'):
raise Exception("Cannot send setup response: %s" % s)
return s
def send_test_session_setup_request(self, fsts_id,
additional_parameter=None):
request = "FST-MANAGER TEST_REQUEST SEND_SETUP_REQUEST " + fsts_id
if additional_parameter is not None:
request += " " + additional_parameter
s = self.grequest(request)
if not s.startswith('OK'):
raise Exception("Cannot send FST setup request: %s" % s)
return s
def send_test_session_setup_response(self, fsts_id,
response, additional_parameter=None):
request = "FST-MANAGER TEST_REQUEST SEND_SETUP_RESPONSE " + fsts_id + " " + response
if additional_parameter is not None:
request += " " + additional_parameter
s = self.grequest(request)
if not s.startswith('OK'):
raise Exception("Cannot send FST setup response: %s" % s)
return s
def send_test_ack_request(self, fsts_id):
s = self.grequest("FST-MANAGER TEST_REQUEST SEND_ACK_REQUEST " + fsts_id)
if not s.startswith('OK'):
raise Exception("Cannot send FST ack request: %s" % s)
return s
def send_test_ack_response(self, fsts_id):
s = self.grequest("FST-MANAGER TEST_REQUEST SEND_ACK_RESPONSE " + fsts_id)
if not s.startswith('OK'):
raise Exception("Cannot send FST ack response: %s" % s)
return s
def send_test_tear_down(self, fsts_id):
s = self.grequest("FST-MANAGER TEST_REQUEST SEND_TEAR_DOWN " + fsts_id)
if not s.startswith('OK'):
raise Exception("Cannot send FST tear down: %s" % s)
return s
def get_fsts_id_by_sid(self, sid):
s = self.grequest("FST-MANAGER TEST_REQUEST GET_FSTS_ID " + sid)
if s == ' ' or s.startswith('FAIL'):
raise Exception("Cannot get fsts_id for sid == %s" % sid)
return int(s)
def wait_for_iface_event(self, timeout):
while True:
ev = self.wait_gevent(["FST-EVENT-IFACE"], timeout)
if ev is None:
raise Exception("No FST-EVENT-IFACE received")
event = parse_fst_iface_event(ev)
if event is None:
# We can't parse so it's not our event, wait for next one
continue
return event
def wait_for_session_event(self, timeout, events_to_ignore=[],
events_to_count=[]):
while True:
ev = self.wait_gevent(["FST-EVENT-SESSION"], timeout)
if ev is None:
raise Exception("No FST-EVENT-SESSION received")
event = parse_fst_session_event(ev)
if event is None:
# We can't parse so it's not our event, wait for next one
continue
if len(events_to_ignore) > 0:
if event['type'] in events_to_ignore:
continue
elif len(events_to_count) > 0:
if event['type'] not in events_to_count:
continue
return event
def initiate_session(self, sid, response="accept"):
"""Initiates FST session with given session id 'sid'.
'response' is the session respond answer: "accept", "reject", or a
special "timeout" value to skip the response in order to test session
timeouts.
Returns: "OK" - session has been initiated, otherwise the reason for the
reset: REASON_REJECT, REASON_STT."""
strsid = ' ' + sid if sid != '' else ''
s = self.grequest("FST-MANAGER SESSION_INITIATE"+ strsid)
if not s.startswith('OK'):
raise Exception("Cannot initiate fst session: %s" % s)
ev = self.peer_obj.wait_gevent(["FST-EVENT-SESSION"], timeout=5)
if ev is None:
raise Exception("No FST-EVENT-SESSION received")
# We got FST event
event = parse_fst_session_event(ev)
if event == None:
raise Exception("Unrecognized FST event: " % ev)
if event['type'] != 'EVENT_FST_SETUP':
raise Exception("Expected FST_SETUP event, got: " + event['type'])
ev = self.peer_obj.wait_gevent(["FST-EVENT-SESSION"], timeout=5)
if ev is None:
raise Exception("No FST-EVENT-SESSION received")
event = parse_fst_session_event(ev)
if event == None:
raise Exception("Unrecognized FST event: " % ev)
if event['type'] != 'EVENT_FST_SESSION_STATE':
raise Exception("Expected EVENT_FST_SESSION_STATE event, got: " + event['type'])
if event['new_state'] != "SETUP_COMPLETION":
raise Exception("Expected new state SETUP_COMPLETION, got: " + event['new_state'])
if response == '':
return 'OK'
if response != "timeout":
s = self.peer_obj.grequest("FST-MANAGER SESSION_RESPOND "+ event['id'] + " " + response) # Or reject
if not s.startswith('OK'):
raise Exception("Error session_respond: %s" % s)
# Wait for EVENT_FST_SESSION_STATE events. We should get at least 2
# events. The 1st event will be EVENT_FST_SESSION_STATE
# old_state=INITIAL new_state=SETUP_COMPLETED. The 2nd event will be
# either EVENT_FST_ESTABLISHED with the session id or
# EVENT_FST_SESSION_STATE with new_state=INITIAL if the session was
# reset, the reason field will tell why.
result = ''
while result == '':
ev = self.wait_gevent(["FST-EVENT-SESSION"], timeout=5)
if ev is None:
break # No session event received
event = parse_fst_session_event(ev)
if event == None:
# We can't parse so it's not our event, wait for next one
continue
if event['type'] == 'EVENT_FST_ESTABLISHED':
result = "OK"
break
elif event['type'] == "EVENT_FST_SESSION_STATE":
if event['new_state'] == "INITIAL":
# Session was reset, the only reason to get back to initial
# state.
result = event['reason']
break
if result == '':
raise Exception("No event for session respond")
return result
def transfer_session(self, sid):
"""Transfers the session. 'sid' is the session id. 'hsta' is the
station-responder object.
Returns: REASON_SWITCH - the session has been transferred successfully
or a REASON_... reported by the reset event."""
request = "FST-MANAGER SESSION_TRANSFER"
self.dump_monitor()
if sid != '':
request += ' ' + sid
s = self.grequest(request)
if not s.startswith('OK'):
raise Exception("Cannot transfer fst session: %s" % s)
result = ''
while result == '':
ev = self.peer_obj.wait_gevent(["FST-EVENT-SESSION"], timeout=5)
if ev is None:
raise Exception("Missing session transfer event")
# We got FST event. We expect TRANSITION_CONFIRMED state and then
# INITIAL (reset) with the reason (e.g. "REASON_SWITCH").
# Right now we'll be waiting for the reset event and record the
# reason.
event = parse_fst_session_event(ev)
if event == None:
raise Exception("Unrecognized FST event: " % ev)
if event['new_state'] == 'INITIAL':
result = event['reason']
self.dump_monitor()
return result
def wait_for_tear_down(self):
ev = self.wait_gevent(["FST-EVENT-SESSION"], timeout=5)
if ev is None:
raise Exception("No FST-EVENT-SESSION received")
# We got FST event
event = parse_fst_session_event(ev)
if event == None:
raise Exception("Unrecognized FST event: " % ev)
if event['type'] != 'EVENT_FST_SESSION_STATE':
raise Exception("Expected EVENT_FST_SESSION_STATE event, got: " + event['type'])
if event['new_state'] != "INITIAL":
raise Exception("Expected new state INITIAL, got: " + event['new_state'])
if event['reason'] != 'REASON_TEARDOWN':
raise Exception("Expected reason REASON_TEARDOWN, got: " + event['reason'])
def teardown_session(self, sid):
"""Tears down FST session with a given session id ('sid')"""
strsid = ' ' + sid if sid != '' else ''
s = self.grequest("FST-MANAGER SESSION_TEARDOWN" + strsid)
if not s.startswith('OK'):
raise Exception("Cannot tear down fst session: %s" % s)
self.peer_obj.wait_for_tear_down()
def remove_session(self, sid, wait_for_tear_down=True):
"""Removes FST session with a given session id ('sid')"""
strsid = ' ' + sid if sid != '' else ''
s = self.grequest("FST-MANAGER SESSION_REMOVE" + strsid)
if not s.startswith('OK'):
raise Exception("Cannot remove fst session: %s" % s)
if wait_for_tear_down == True:
self.peer_obj.wait_for_tear_down()
def remove_all_sessions(self):
"""Removes FST session with a given session id ('sid')"""
grp = ' ' + self.fst_group if self.fst_group != '' else ''
s = self.grequest("FST-MANAGER LIST_SESSIONS" + grp)
if not s.startswith('FAIL'):
for sid in s.splitlines():
sid = sid.strip()
if len(sid) != 0:
self.remove_session(sid, wait_for_tear_down=False)
#
# FstAP class
#
class FstAP(FstDevice):
def __init__(self, iface, ssid, mode, chan, fst_group, fst_pri,
fst_llt=None, rsn=False):
"""If fst_group is empty, then FST parameters will not be set
If fst_llt is empty, the parameter will not be set and the default value
is expected to be configured."""
self.ssid = ssid
self.mode = mode
self.chan = chan
self.reg_ctrl = fst_test_common.HapdRegCtrl()
self.reg_ctrl.add_ap(iface, self.chan)
self.global_instance = hostapd.HostapdGlobal()
FstDevice.__init__(self, iface, fst_group, fst_pri, fst_llt, rsn)
def start(self, return_early=False):
"""Starts AP the "standard" way as it was intended by hostapd tests.
This will work only when FST supports fully dynamically loading
parameters in hostapd."""
params = {}
params['ssid'] = self.ssid
params['hw_mode'] = self.mode
params['channel'] = self.chan
params['country_code'] = 'US'
if self.rsn:
params['wpa'] = '2'
params['wpa_key_mgmt'] = 'WPA-PSK'
params['rsn_pairwise'] = 'CCMP'
params['wpa_passphrase'] = '12345678'
self.hapd = hostapd.add_ap(self.iface, params)
if not self.hapd.ping():
raise Exception("Could not ping FST hostapd")
self.reg_ctrl.start()
self.get_global_instance()
if return_early:
return self.hapd
if len(self.fst_group) != 0:
self.send_iface_attach_request(self.iface, self.fst_group,
self.fst_llt, self.fst_pri)
return self.hapd
def stop(self):
"""Removes the AP, To be used when dynamic fst APs are implemented in
hostapd."""
if len(self.fst_group) != 0:
self.remove_all_sessions()
try:
self.send_iface_detach_request(self.iface)
except Exception as e:
logger.info(str(e))
self.reg_ctrl.stop()
del self.global_instance
self.global_instance = None
def get_instance(self):
"""Return the Hostapd/WpaSupplicant instance"""
if self.instance is None:
self.instance = hostapd.Hostapd(self.iface)<|fim▁hole|> return self.global_instance
def get_own_mac_address(self):
"""Gets the device's own MAC address"""
h = self.get_instance()
status = h.get_status()
return status['bssid[0]']
def get_actual_peer_addr(self):
"""Gets the peer address. A connected station address is returned."""
# Use the device instance, the global control interface doesn't have
# station address
h = self.get_instance()
sta = h.get_sta(None)
if sta is None or 'addr' not in sta:
# Maybe station is not connected?
addr = None
else:
addr = sta['addr']
return addr
def grequest(self, req):
"""Send request on the global control interface"""
logger.debug("FstAP::grequest: " + req)
h = self.get_global_instance()
return h.request(req)
def wait_gevent(self, events, timeout=None):
"""Wait for a list of events on the global interface"""
h = self.get_global_instance()
if timeout is not None:
return h.wait_event(events, timeout=timeout)
else:
return h.wait_event(events)
def get_ssid(self):
return self.ssid
def dump_monitor(self):
"""Dump control interface monitor events"""
if self.instance:
self.instance.dump_monitor()
#
# FstSTA class
#
class FstSTA(FstDevice):
def __init__(self, iface, fst_group, fst_pri, fst_llt=None, rsn=False):
"""If fst_group is empty, then FST parameters will not be set
If fst_llt is empty, the parameter will not be set and the default value
is expected to be configured."""
FstDevice.__init__(self, iface, fst_group, fst_pri, fst_llt, rsn)
self.connected = None # FstAP object the station is connected to
def start(self):
"""Current implementation involves running another instance of
wpa_supplicant with fixed FST STAs configurations. When any type of
dynamic STA loading is implemented, rewrite the function similarly to
FstAP."""
h = self.get_instance()
h.interface_add(self.iface, drv_params="force_connect_cmd=1")
if not h.global_ping():
raise Exception("Could not ping FST wpa_supplicant")
if len(self.fst_group) != 0:
self.send_iface_attach_request(self.iface, self.fst_group,
self.fst_llt, self.fst_pri)
return None
def stop(self):
"""Removes the STA. In a static (temporary) implementation does nothing,
the STA will be removed when the fst wpa_supplicant process is killed by
fstap.cleanup()."""
h = self.get_instance()
h.dump_monitor()
if len(self.fst_group) != 0:
self.remove_all_sessions()
self.send_iface_detach_request(self.iface)
h.dump_monitor()
h.interface_remove(self.iface)
h.close_ctrl()
del h
self.instance = None
def get_instance(self):
"""Return the Hostapd/WpaSupplicant instance"""
if self.instance is None:
self.instance = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
return self.instance
def get_own_mac_address(self):
"""Gets the device's own MAC address"""
h = self.get_instance()
status = h.get_status()
return status['address']
def get_actual_peer_addr(self):
"""Gets the peer address. A connected station address is returned"""
h = self.get_instance()
status = h.get_status()
return status['bssid']
def grequest(self, req):
"""Send request on the global control interface"""
logger.debug("FstSTA::grequest: " + req)
h = self.get_instance()
return h.global_request(req)
def wait_gevent(self, events, timeout=None):
"""Wait for a list of events on the global interface"""
h = self.get_instance()
if timeout is not None:
return h.wait_global_event(events, timeout=timeout)
else:
return h.wait_global_event(events)
def scan(self, freq=None, no_wait=False, only_new=False):
"""Issue Scan with given parameters. Returns the BSS dictionary for the
AP found (the 1st BSS found. TODO: What if the AP required is not the
1st in list?) or None if no BSS found. None call be also a result of
no_wait=True. Note, request("SCAN_RESULTS") can be used to get all the
results at once."""
h = self.get_instance()
h.dump_monitor()
h.scan(None, freq, no_wait, only_new)
r = h.get_bss('0')
h.dump_monitor()
return r
def connect(self, ap, **kwargs):
"""Connects to the given AP"""
if not isinstance(ap, FstAP):
raise Exception("Bad AP object to connect to")
h = self.get_instance()
hap = ap.get_instance()
h.dump_monitor()
h.connect(ap.get_ssid(), **kwargs)
h.dump_monitor()
self.connected = ap
def connect_to_external_ap(self, ap, ssid, check_connection=True, **kwargs):
"""Connects to the given external AP"""
if not isinstance(ap, hostapd.Hostapd):
raise Exception("Bad AP object to connect to")
h = self.get_instance()
h.dump_monitor()
h.connect(ssid, **kwargs)
self.connected = ap
if check_connection:
ev = ap.wait_event(["AP-STA-CONNECTED"], timeout=10)
if ev is None:
self.connected = None
raise Exception("No connection event received from %s" % ssid)
h.dump_monitor()
def disconnect(self, check_disconnect=True):
"""Disconnects from the AP the station is currently connected to"""
if self.connected is not None:
h = self.get_instance()
h.dump_monitor()
h.request("DISCONNECT")
if check_disconnect:
hap = self.connected.get_instance()
ev = hap.wait_event(["AP-STA-DISCONNECTED"], timeout=10)
if ev is None:
raise Exception("No disconnection event received from %s" % self.connected.get_ssid())
h.dump_monitor()
self.connected = None
def disconnect_from_external_ap(self, check_disconnect=True):
"""Disconnects from the external AP the station is currently connected
to"""
if self.connected is not None:
h = self.get_instance()
h.dump_monitor()
h.request("DISCONNECT")
if check_disconnect:
hap = self.connected
ev = hap.wait_event(["AP-STA-DISCONNECTED"], timeout=10)
if ev is None:
raise Exception("No disconnection event received from AP")
h.dump_monitor()
self.connected = None
def dump_monitor(self):
"""Dump control interface monitor events"""
if self.instance:
self.instance.dump_monitor()<|fim▁end|> | return self.instance
def get_global_instance(self): |
<|file_name|>pjax-content.js<|end_file_name|><|fim▁begin|>/* YUI 3.9.0pr1 (build 202) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */
YUI.add('pjax-content', function (Y, NAME) {
/**
`Y.Router` extension that provides the content fetching and handling needed to
implement the standard pjax (HTMP5 pushState + Ajax) functionality.
@module pjax
@submodule pjax-content
@since 3.7.0
**/
/**
`Y.Router` extension that provides the content fetching and handling needed to
implement the standard pjax (HTMP5 pushState + Ajax) functionality.
This makes it easy to fetch server rendered content for URLs using Ajax. By
helping the router to fulfill the "request" for the content you can avoid full
page loads.
The `PjaxContent` class isn't useful on its own, but can be mixed into a
`Router`-based class along with the `PjaxBase` class to add Pjax functionality
to that Router. For a pre-made standalone Pjax router, see the `Pjax` class.
var MyRouter = Y.Base.create('myRouter', Y.Router, [
Y.PjaxBase,
Y.PjaxContent
], {
// ...
});
@class PjaxContent
@extensionfor Router
@since 3.7.0
**/
function PjaxContent() {}
PjaxContent.prototype = {
// -- Public Methods -------------------------------------------------------
/**
Extracts and returns the relevant HTML content from an Ajax response. The
content is extracted using the `contentSelector` attribute as a CSS
selector. If `contentSelector` is `null`, the entire response will be
returned.
The return value is an object containing two properties:
* `node`: A `Y.Node` instance for a document fragment containing the
extracted HTML content.
* `title`: The title of the HTML page, if any, extracted using the
`titleSelector` attribute (which defaults to looking for a `<title>`
element). If `titleSelector` is not set or if a title could not be
found, this property will be `undefined`.
@method getContent
@param {String} responseText Raw Ajax response text.
@return {Object} Content object with the properties described above.
@since 3.5.0
**/
getContent: function (responseText) {
var content = {},
contentSelector = this.get('contentSelector'),
frag = Y.Node.create(responseText || ''),
titleSelector = this.get('titleSelector'),
titleNode;
if (contentSelector && frag) {
content.node = frag.all(contentSelector).toFrag();
} else {
content.node = frag;
}
if (titleSelector && frag) {
titleNode = frag.one(titleSelector);
if (titleNode) {
content.title = titleNode.get('text');
}
}
return content;
},
/**
Pjax route middleware to load content from a server. This makes an Ajax
request for the requested URL, parses the returned content and puts it on
the route's response object.
This is route middleware and not intended to be the final callback for a
route. This will add the following information to the route's request and
response objects:
<|fim▁hole|> may contain `"pjax=1"` if the `addPjaxParam` option is set.
- `res.content`: An object containing `node` and `title` properties for
the content extracted from the server's response. See `getContent()` for
more details.
- `res.ioResponse`: The full `Y.io()` response object. This is useful if
you need access to the XHR's response `status` or HTTP headers.
@example
router.route('/foo/', 'loadContent', function (req, res, next) {
Y.one('container').setHTML(res.content.node);
Y.config.doc.title = res.content.title;
});
@method loadContent
@param {Object} req Request object.
@param {Object} res Response Object.
@param {Function} next Function to pass control to the next route callback.
@since 3.7.0
@see Router.route()
**/
loadContent: function (req, res, next) {
var url = req.url;
// If there's an outstanding request, abort it.
if (this._request) {
this._request.abort();
}
// Add a 'pjax=1' query parameter if enabled.
if (this.get('addPjaxParam')) {
// Captures the path with query, and hash parts of the URL. Then
// properly injects the "pjax=1" query param in the right place,
// before any hash fragment, and returns the updated URL.
url = url.replace(/([^#]*)(#.*)?$/, function (match, path, hash) {
path += (path.indexOf('?') > -1 ? '&' : '?') + 'pjax=1';
return path + (hash || '');
});
}
// Send a request.
this._request = Y.io(url, {
'arguments': {
route: {
req : req,
res : res,
next: next
},
url: url
},
context: this,
headers: {'X-PJAX': 'true'},
timeout: this.get('timeout'),
on: {
complete: this._onPjaxIOComplete,
end : this._onPjaxIOEnd
}
});
},
// -- Event Handlers -------------------------------------------------------
/**
Handles IO complete events.
This parses the content from the `Y.io()` response and puts it on the
route's response object.
@method _onPjaxIOComplete
@param {String} id The `Y.io` transaction id.
@param {Object} ioResponse The `Y.io` response object.
@param {Object} details Extra details carried through from `loadContent()`.
@protected
@since 3.7.0
**/
_onPjaxIOComplete: function (id, ioResponse, details) {
var content = this.getContent(ioResponse.responseText),
route = details.route,
req = route.req,
res = route.res;
// Put the URL requested through `Y.io` on the route's `req` object.
req.ioURL = details.url;
// Put the parsed content and `Y.io` response object on the route's
// `res` object.
res.content = content;
res.ioResponse = ioResponse;
route.next();
},
/**
Handles IO end events.
@method _onPjaxIOEnd
@param {String} id The `Y.io` transaction id.
@param {Object} details Extra details carried through from `loadContent()`.
@protected
@since 3.5.0
**/
_onPjaxIOEnd: function () {
this._request = null;
}
};
PjaxContent.ATTRS = {
/**
If `true`, a "pjax=1" query parameter will be appended to all URLs
requested via Pjax.
Browsers ignore HTTP request headers when caching content, so if the
same URL is used to request a partial Pjax page and a full page, the
browser will cache them under the same key and may later load the
cached partial page when the user actually requests a full page (or vice
versa).
To prevent this, we can add a bogus query parameter to the URL so that
Pjax URLs will always be cached separately from non-Pjax URLs.
@attribute addPjaxParam
@type Boolean
@default true
@since 3.5.0
**/
addPjaxParam: {
value: true
},
/**
CSS selector used to extract a specific portion of the content of a page
loaded via Pjax.
For example, if you wanted to load the page `example.html` but only use
the content within an element with the id "pjax-content", you'd set
`contentSelector` to "#pjax-content".
If not set, the entire page will be used.
@attribute contentSelector
@type String
@default null
@since 3.5.0
**/
contentSelector: {
value: null
},
/**
CSS selector used to extract a page title from the content of a page
loaded via Pjax.
By default this is set to extract the title from the `<title>` element,
but you could customize it to extract the title from an `<h1>`, or from
any other element, if that's more appropriate for the content you're
loading.
@attribute titleSelector
@type String
@default "title"
@since 3.5.0
**/
titleSelector: {
value: 'title'
},
/**
Time in milliseconds after which an Ajax request should time out.
@attribute timeout
@type Number
@default 30000
@since 3.5.0
**/
timeout: {
value: 30000
}
};
Y.PjaxContent = PjaxContent;
}, '3.9.0pr1', {"requires": ["io-base", "node-base", "router"]});<|fim▁end|> | - `req.ioURL`: The full URL that was used to make the `Y.io()` XHR. This |
<|file_name|>home.js<|end_file_name|><|fim▁begin|>function Controller() {
function __alloyId24() {
__alloyId24.opts || {};
var models = __alloyId23.models;
var len = models.length;
var rows = [];
for (var i = 0; len > i; i++) {
var __alloyId9 = models[i];
__alloyId9.__transform = {};
var __alloyId10 = Ti.UI.createTableViewRow({
layout: "vertical",
font: {
fontSize: "16dp"
},
height: "auto",
title: "undefined" != typeof __alloyId9.__transform["nome"] ? __alloyId9.__transform["nome"] : __alloyId9.get("nome"),
model: "undefined" != typeof __alloyId9.__transform["alloy_id"] ? __alloyId9.__transform["alloy_id"] : __alloyId9.get("alloy_id"),
editable: "true"
});
rows.push(__alloyId10);
var __alloyId12 = Ti.UI.createView({
layout: "vertical"
});
__alloyId10.add(__alloyId12);<|fim▁hole|> right: "10dp",
color: "blue",
font: {
fontSize: "16dp"
},
text: "undefined" != typeof __alloyId9.__transform["nome"] ? __alloyId9.__transform["nome"] : __alloyId9.get("nome")
});
__alloyId12.add(__alloyId14);
var __alloyId16 = Ti.UI.createView({
height: Ti.UI.SIZE,
width: Ti.UI.FILL
});
__alloyId12.add(__alloyId16);
var __alloyId18 = Ti.UI.createScrollView({
scrollType: "horizontal",
layout: "horizontal",
horizontalWrap: "false"
});
__alloyId16.add(__alloyId18);
var __alloyId20 = Ti.UI.createImageView({
top: "15dp",
image: "undefined" != typeof __alloyId9.__transform["foto1"] ? __alloyId9.__transform["foto1"] : __alloyId9.get("foto1"),
height: "180dp",
width: "320dp"
});
__alloyId18.add(__alloyId20);
var __alloyId22 = Ti.UI.createImageView({
top: "15dp",
image: "undefined" != typeof __alloyId9.__transform["foto2"] ? __alloyId9.__transform["foto2"] : __alloyId9.get("foto2"),
height: "180dp",
width: "320dp"
});
__alloyId18.add(__alloyId22);
}
$.__views.tableviewContatos.setData(rows);
}
function openAdd1() {
var add1 = Alloy.createController("add1");
add1.getView().open({
modal: true
});
}
function maisDetalhes(e) {
var contato = Alloy.Collections.contato.get(e.rowData.model);
var ctrl = Alloy.createController("detalhesContato", contato);
$.homeTab.open(ctrl.getView());
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
this.__controllerPath = "home";
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
arguments[0] ? arguments[0]["__itemTemplate"] : null;
var $ = this;
var exports = {};
var __defers = {};
$.__views.homeWindow = Ti.UI.createWindow({
backgroundColor: "white",
layout: "vertical",
id: "homeWindow",
titleid: "home"
});
$.__views.contatosSearch = Ti.UI.createSearchBar({
hinttextid: "procurarText",
height: "50dp",
id: "contatosSearch",
showCancel: "false"
});
$.__views.homeWindow.add($.__views.contatosSearch);
$.__views.Btadd = Ti.UI.createButton({
top: "10dp",
width: "200dp",
height: "auto",
borderRadius: "10dp",
font: {
fontSize: "17dp"
},
title: L("adicionar"),
id: "Btadd"
});
$.__views.homeWindow.add($.__views.Btadd);
openAdd1 ? $.__views.Btadd.addEventListener("click", openAdd1) : __defers["$.__views.Btadd!click!openAdd1"] = true;
$.__views.tableviewContatos = Ti.UI.createTableView({
id: "tableviewContatos"
});
$.__views.homeWindow.add($.__views.tableviewContatos);
var __alloyId23 = Alloy.Collections["contato"] || contato;
__alloyId23.on("fetch destroy change add remove reset", __alloyId24);
maisDetalhes ? $.__views.tableviewContatos.addEventListener("click", maisDetalhes) : __defers["$.__views.tableviewContatos!click!maisDetalhes"] = true;
$.__views.homeTab = Ti.UI.createTab({
backgroundSelectedColor: "#C8C8C8 ",
backgroundFocusedColor: "#999",
icon: "/images/ic_home.png",
window: $.__views.homeWindow,
id: "homeTab",
titleid: "home"
});
$.__views.homeTab && $.addTopLevelView($.__views.homeTab);
exports.destroy = function() {
__alloyId23.off("fetch destroy change add remove reset", __alloyId24);
};
_.extend($, $.__views);
Alloy.Collections.contato.fetch();
var contatos = Alloy.Collections.contato;
contatos.fetch();
$.tableviewContatos.search = $.contatosSearch;
__defers["$.__views.Btadd!click!openAdd1"] && $.__views.Btadd.addEventListener("click", openAdd1);
__defers["$.__views.tableviewContatos!click!maisDetalhes"] && $.__views.tableviewContatos.addEventListener("click", maisDetalhes);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;<|fim▁end|> | var __alloyId14 = Ti.UI.createLabel({
width: Ti.UI.SIZE,
height: Ti.UI.SIZE, |
<|file_name|>stats.py<|end_file_name|><|fim▁begin|>from itertools import repeat, chain
from operator import itemgetter
from django.db.models import Count, Sum, Case, When, IntegerField, Value, FloatField
from django.db.models.expressions import CombinedExpression
from django.http import JsonResponse
from django.shortcuts import render
from django.utils.translation import ugettext as _
from judge.models import Language, Submission
chart_colors = [0x3366CC, 0xDC3912, 0xFF9900, 0x109618, 0x990099, 0x3B3EAC, 0x0099C6, 0xDD4477, 0x66AA00, 0xB82E2E,<|fim▁hole|>highlight_colors = []
def _highlight_colors():
for color in chart_colors:
r, g, b = color >> 16, (color >> 8) & 0xFF, color & 0xFF
highlight_colors.append('#%02X%02X%02X' % (min(int(r * 1.2), 255),
min(int(g * 1.2), 255),
min(int(b * 1.2), 255)))
_highlight_colors()
del _highlight_colors
chart_colors = map('#%06X'.__mod__, chart_colors)
ac_count = Count(Case(When(submission__result='AC', then=Value(1)), output_field=IntegerField()))
def repeat_chain(iterable):
return chain.from_iterable(repeat(iterable))
def language_data(request, language_count=Language.objects.annotate(count=Count('submission'))):
languages = language_count.filter(count__gte=1000).values('key', 'name', 'short_name', 'count').order_by('-count')
data = []
for language, color, highlight in zip(languages, chart_colors, highlight_colors):
data.append({
'value': language['count'], 'label': language['name'],
'color': color, 'highlight': highlight,
})
data.append({
'value': language_count.filter(count__lt=1000).aggregate(total=Sum('count'))['total'],
'label': 'Other', 'color': '#FDB45C', 'highlight': '#FFC870',
})
return JsonResponse(data, safe=False)
def ac_language_data(request):
return language_data(request, Language.objects.annotate(count=ac_count))
def status_data(request, statuses=None):
if not statuses:
statuses = (Submission.objects.values('result').annotate(count=Count('result'))
.values('result', 'count').order_by('-count'))
data = []
total_count = 0
for status, color, highlight in zip(statuses, chart_colors, highlight_colors):
res = status['result']
if not res:
continue
count = status['count']
total_count += count
data.append({
'value': count, 'label': str(Submission.USER_DISPLAY_CODES[res]),
'color': color, 'highlight': highlight
})
return JsonResponse(data, safe=False)
def ac_rate(request):
rate = CombinedExpression(ac_count / Count('submission'), '*', Value(100.0), output_field=FloatField())
data = Language.objects.annotate(total=Count('submission'), ac_rate=rate).filter(total__gt=0) \
.values('key', 'name', 'short_name', 'ac_rate').order_by('total')
return JsonResponse({
'labels': map(itemgetter('name'), data),
'datasets': [
{
'fillColor': 'rgba(151,187,205,0.5)',
'strokeColor': 'rgba(151,187,205,0.8)',
'highlightFill': 'rgba(151,187,205,0.75)',
'highlightStroke': 'rgba(151,187,205,1)',
'data': map(itemgetter('ac_rate'), data),
}
]
})
def language(request):
return render(request, 'stats/language.html', {
'title': _('Language statistics'), 'tab': 'language'
})<|fim▁end|> | 0x316395, 0x994499, 0x22AA99, 0xAAAA11, 0x6633CC, 0xE67300, 0x8B0707, 0x329262, 0x5574A6, 0x3B3EAC] |
<|file_name|>config.rs<|end_file_name|><|fim▁begin|>#![allow(dead_code)]
extern crate clap;
use helper::Log;
use self::clap::{Arg, App};
use std::process;
use std::error::Error;
pub const APP_VERSION: &'static str = "1.0.34";
pub const MAX_API_VERSION: u32 = 1000;
pub struct NodeConfig {
pub value: u64,
pub token: String,
pub api_version: u32,
pub network: NetworkingConfig,
pub parent_address: String
}
pub struct NetworkingConfig {
pub tcp_server_host: String,
pub concurrency: usize
}
pub fn parse_args() -> NodeConfig {
let matches = App::new("TreeScale Node Service")
.version(APP_VERSION)
.author("TreeScale Inc. <[email protected]>")
.about("TreeScale technology endpoint for event distribution and data transfer")
.arg(Arg::with_name("token")
.short("t")
.long("token")
.value_name("TOKEN")
.help("Token or Name for service identification, if not set, it would be auto-generated using uuid4")
.takes_value(true))
.arg(Arg::with_name("value")
.short("u")
.long("value")
.value_name("VALUE")
.help("Value for current Node, in most cases it would be generated from TreeScale Resolver")
.takes_value(true))
.arg(Arg::with_name("api")
.short("a")
.long("api")
.value_name("API_NUMBER")
.help("Sets API version for specific type of networking communications, default would be the latest version")
.takes_value(true))
.arg(Arg::with_name("parent")
.short("p")
.long("parent")
.value_name("PARENT_ADDRESS")
.takes_value(true))
.arg(Arg::with_name("concurrency")
.short("c")
.long("concurrency")
.value_name("THREADS_COUNT")
.help("Sets concurrency level for handling concurrent tasks, default would be cpu cores count of current machine")
.takes_value(true))
.arg(Arg::with_name("tcp_host")
.short("h")
.long("host")
.value_name("TCP_SERVER_HOST")
.help("Starts TCP server listener on give host: default is 0.0.0.0:8000")
.takes_value(true))
.get_matches();
NodeConfig {
value: match matches.value_of("value") {
Some(v) => match String::from(v).parse::<u64>() {
Ok(vv) => vv,
Err(e) => {
Log::error("Unable to parse given Node Value", e.description());
process::exit(1);
}
},
None => 0
},
token: match matches.value_of("token") {
Some(v) => String::from(v),
None => String::new()
},
api_version: match matches.value_of("api") {
Some(v) => match String::from(v).parse::<u32>() {
Ok(vv) => vv,
Err(e) => {
Log::error("Unable to parse given API Version", e.description());
process::exit(1);
}
},
None => 1
},
network: NetworkingConfig {
tcp_server_host: match matches.value_of("tcp_host") {
Some(v) => String::from(v),
None => String::from("0.0.0.0:8000")
},
concurrency: match matches.value_of("concurrency") {
Some(v) => match String::from(v).parse::<usize>() {
Ok(vv) => vv,
Err(e) => {
Log::error("Unable to parse given Concurrency Level parameter", e.description());
process::exit(1);
}
},
None => 0
},
},
parent_address: match matches.value_of("parent") {
Some(v) => String::from(v),
None => String::new()
},
}<|fim▁hole|><|fim▁end|> | } |
<|file_name|>QuickSort.go<|end_file_name|><|fim▁begin|>/*Copyright 2020 Anil Kumar Teegala
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 for Quick Sort in Go
package main
import (<|fim▁hole|>
func main() {
slice := generateSlice(20)
fmt.Println("\n--- Unsorted --- \n\n", slice)
quicksort(slice)
fmt.Println("\n--- Sorted ---\n\n", slice, "\n")
}
// Generates a slice of size, size filled with random numbers
func generateSlice(size int) []int {
slice := make([]int, size, size)
rand.Seed(time.Now().UnixNano())
for i := 0; i < size; i++ {
slice[i] = rand.Intn(999) - rand.Intn(999)
}
return slice
}
func quicksort(a []int) []int {
if len(a) < 2 {
return a
}
left, right := 0, len(a)-1
pivot := rand.Int() % len(a)
a[pivot], a[right] = a[right], a[pivot]
for i, _ := range a {
if a[i] < a[right] {
a[left], a[i] = a[i], a[left]
left++
}
}
a[left], a[right] = a[right], a[left]
quicksort(a[:left])
quicksort(a[left+1:])
return a
}<|fim▁end|> | "fmt"
"math/rand"
"time"
) |
<|file_name|>topic_count.js<|end_file_name|><|fim▁begin|>/*globals rabbitmq_test_bindings: false,
rabbitmq_bindings_to_remove: false */
/*jslint mocha: true */
"use strict";
var expect = require('chai').expect,
util = require('util'),
Qlobber = require('..').Qlobber;
function QlobberTopicCount (options)
{
Qlobber.call(this, options);
this.topic_count = 0;
}
util.inherits(QlobberTopicCount, Qlobber);
QlobberTopicCount.prototype._initial_value = function (val)
{
this.topic_count += 1;
return Qlobber.prototype._initial_value(val);
};
QlobberTopicCount.prototype._remove_value = function (vals, val)
{
var removed = Qlobber.prototype._remove_value(vals, val);
if (removed)
{
this.topic_count -= 1;
}
return removed;
};
QlobberTopicCount.prototype.clear = function ()
{
this.topic_count = 0;
return Qlobber.prototype.clear.call(this);
};
describe('qlobber-topic-count', function ()<|fim▁hole|> it('should be able to count topics added', function ()
{
var matcher = new QlobberTopicCount();
rabbitmq_test_bindings.forEach(function (topic_val)
{
matcher.add(topic_val[0], topic_val[1]);
});
expect(matcher.topic_count).to.equal(25);
rabbitmq_bindings_to_remove.forEach(function (i)
{
matcher.remove(rabbitmq_test_bindings[i-1][0],
rabbitmq_test_bindings[i-1][1]);
});
expect(matcher.topic_count).to.equal(21);
matcher.clear();
expect(matcher.topic_count).to.equal(0);
expect(matcher.match('a.b.c').length).to.equal(0);
});
it('should not decrement count if entry does not exist', function ()
{
var matcher = new QlobberTopicCount();
expect(matcher.topic_count).to.equal(0);
matcher.add('foo.bar', 23);
expect(matcher.topic_count).to.equal(1);
matcher.remove('foo.bar', 24);
expect(matcher.topic_count).to.equal(1);
matcher.remove('foo.bar2', 23);
expect(matcher.topic_count).to.equal(1);
matcher.remove('foo.bar', 23);
expect(matcher.topic_count).to.equal(0);
matcher.remove('foo.bar', 24);
expect(matcher.topic_count).to.equal(0);
matcher.remove('foo.bar2', 23);
expect(matcher.topic_count).to.equal(0);
});
});<|fim▁end|> | { |
<|file_name|>ConnessioneDB.java<|end_file_name|><|fim▁begin|>import java.sql.*;
public class ConnessioneDB {
static {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();<|fim▁hole|> // TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "calcio";
String userName = "root";
String password = "";
/*
String url = "jdbc:mysql://127.11.139.2:3306/";
String dbName = "sirio";
String userName = "adminlL8hBfI";
String password = "HPZjQCQsnVG4";
*/
public Connection openConnection(){
try {
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connessione al DataBase stabilita!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public void closeConnection(Connection conn){
try {
conn.close();
System.out.println(" Chiusa connessione al DB!");
}
catch (SQLException e) {
e.printStackTrace();
}
}
}<|fim▁end|> | } catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) { |
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import os
import sys
import MySQLdb
if __name__ == "__main__":<|fim▁hole|> execute_from_command_line(sys.argv)<|fim▁end|> | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "academicControl.settings")
from django.core.management import execute_from_command_line
|
<|file_name|>frukkola.ts<|end_file_name|><|fim▁begin|><|fim▁hole|>const FRUKKOLA_MENU_URL = 'http://fruccola.hu/admin/api/daily_menu';
const ARANY_ID = 1;
interface IMenu {
id: number;
place_id: number;
soup_hu: string;
soup_en: string;
dish_hu: string;
dish_en: string;
due_date: string;
push_time: string;
pushed: number;
email_sent: number;
test_mail_sent: number;
soup_allergen_ids: number[];
dish_allergen_ids: number[];
}
interface IFrukkolaResponse {
[key: number]: IMenu;
pricing: {
soup: string,
dish: string,
combo: string,
};
}
export async function getFrukkola() {
try {
const options: request.OptionsWithUrl = {
url: FRUKKOLA_MENU_URL,
json: true,
};
const response: IFrukkolaResponse = await request(options);
const aranyMenu = response[ARANY_ID];
const text_hu = `${aranyMenu.soup_hu} (${response.pricing.soup}), \n` +
`${aranyMenu.dish_hu} (${response.pricing.dish}) \n` +
`${response.pricing.combo}.- Ft`;
return {
title: 'Frukkola :green_apple:',
title_link: FRUKKOLA_URL,
text: text_hu,
};
} catch (error) {
console.log(error);
return {
title: 'Frukkola :ripepperonis:',
title_link: FRUKKOLA_URL,
text: `${error}`,
};
}
}<|fim▁end|> | import * as request from 'request-promise';
const FRUKKOLA_URL = 'http://fruccola.hu/'; |
<|file_name|>Room.java<|end_file_name|><|fim▁begin|>package com.vexus2.jenkins.chatwork.jenkinschatworkplugin.api;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown=true)
public class Room {
@JsonProperty("room_id")
public String roomId;
@JsonProperty("name")
public String name;
@JsonProperty("type")
public String type;
@Override
public int hashCode(){
return new HashCodeBuilder()
.append(name)
.append(roomId)
.append(type)
.toHashCode();
}
@Override
public boolean equals(final Object obj){
if(obj instanceof Room){<|fim▁hole|> final Room other = (Room) obj;
return new EqualsBuilder()
.append(name, other.name)
.append(roomId, other.roomId)
.append(type, other.type)
.isEquals();
} else{
return false;
}
}
}<|fim▁end|> | |
<|file_name|>boundingrecthighlighter.cpp<|end_file_name|><|fim▁begin|>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "boundingrecthighlighter.h"
#include "qdeclarativeviewinspector.h"
#include "qmlinspectorconstants.h"
#include <QtWidgets/QGraphicsPolygonItem>
#include <QtCore/QTimer>
#include <QtCore/QObject>
#include <QtCore/QDebug>
namespace QmlJSDebugger {
namespace QtQuick1 {
BoundingBox::BoundingBox(QGraphicsObject *itemToHighlight, QGraphicsItem *parentItem,
QObject *parent)
: QObject(parent),
highlightedObject(itemToHighlight),
highlightPolygon(0),
highlightPolygonEdge(0)
{
highlightPolygon = new BoundingBoxPolygonItem(parentItem);
highlightPolygonEdge = new BoundingBoxPolygonItem(parentItem);
highlightPolygon->setPen(QPen(QColor(0, 22, 159)));
highlightPolygonEdge->setPen(QPen(QColor(158, 199, 255)));
highlightPolygon->setFlag(QGraphicsItem::ItemIsSelectable, false);
highlightPolygonEdge->setFlag(QGraphicsItem::ItemIsSelectable, false);
}
BoundingBox::~BoundingBox()
{
highlightedObject.clear();
}
BoundingBoxPolygonItem::BoundingBoxPolygonItem(QGraphicsItem *item) : QGraphicsPolygonItem(item)
{
QPen pen;
pen.setColor(QColor(108, 141, 221));
pen.setWidth(1);
setPen(pen);
}
int BoundingBoxPolygonItem::type() const
{
return Constants::EditorItemType;
}
BoundingRectHighlighter::BoundingRectHighlighter(QDeclarativeViewInspector *view) :
LiveLayerItem(view->declarativeView()->scene()),
m_view(view)
{
}
BoundingRectHighlighter::~BoundingRectHighlighter()
{
}
void BoundingRectHighlighter::clear()
{
foreach (BoundingBox *box, m_boxes)
freeBoundingBox(box);
}
BoundingBox *BoundingRectHighlighter::boxFor(QGraphicsObject *item) const
{
foreach (BoundingBox *box, m_boxes) {
if (box->highlightedObject.data() == item)
return box;
}
return 0;
}
void BoundingRectHighlighter::highlight(QList<QGraphicsObject*> items)
{
if (items.isEmpty())
return;
QList<BoundingBox *> newBoxes;
foreach (QGraphicsObject *itemToHighlight, items) {
BoundingBox *box = boxFor(itemToHighlight);
if (!box)
box = createBoundingBox(itemToHighlight);
newBoxes << box;
}
qSort(newBoxes);
if (newBoxes != m_boxes) {
clear();
m_boxes << newBoxes;
}
highlightAll();
}
void BoundingRectHighlighter::highlight(QGraphicsObject* itemToHighlight)
{
if (!itemToHighlight)
return;
BoundingBox *box = boxFor(itemToHighlight);
if (!box) {
box = createBoundingBox(itemToHighlight);
m_boxes << box;
qSort(m_boxes);
}
highlightAll();
}
BoundingBox *BoundingRectHighlighter::createBoundingBox(QGraphicsObject *itemToHighlight)
{
if (!m_freeBoxes.isEmpty()) {
BoundingBox *box = m_freeBoxes.last();
if (box->highlightedObject.isNull()) {
box->highlightedObject = itemToHighlight;
box->highlightPolygon->show();
box->highlightPolygonEdge->show();
m_freeBoxes.removeLast();
return box;
}
}
BoundingBox *box = new BoundingBox(itemToHighlight, this, this);
connect(itemToHighlight, SIGNAL(xChanged()), this, SLOT(refresh()));
connect(itemToHighlight, SIGNAL(yChanged()), this, SLOT(refresh()));
connect(itemToHighlight, SIGNAL(widthChanged()), this, SLOT(refresh()));
connect(itemToHighlight, SIGNAL(heightChanged()), this, SLOT(refresh()));
connect(itemToHighlight, SIGNAL(rotationChanged()), this, SLOT(refresh()));
connect(itemToHighlight, SIGNAL(destroyed(QObject*)), this, SLOT(itemDestroyed(QObject*)));
return box;
}
void BoundingRectHighlighter::removeBoundingBox(BoundingBox *box)
{
delete box;
box = 0;
}
void BoundingRectHighlighter::freeBoundingBox(BoundingBox *box)
{
if (!box->highlightedObject.isNull()) {
disconnect(box->highlightedObject.data(), SIGNAL(xChanged()), this, SLOT(refresh()));
disconnect(box->highlightedObject.data(), SIGNAL(yChanged()), this, SLOT(refresh()));
disconnect(box->highlightedObject.data(), SIGNAL(widthChanged()), this, SLOT(refresh()));
disconnect(box->highlightedObject.data(), SIGNAL(heightChanged()), this, SLOT(refresh()));
disconnect(box->highlightedObject.data(), SIGNAL(rotationChanged()), this, SLOT(refresh()));
}
box->highlightedObject.clear();
box->highlightPolygon->hide();
box->highlightPolygonEdge->hide();<|fim▁hole|>
void BoundingRectHighlighter::itemDestroyed(QObject *obj)
{
foreach (BoundingBox *box, m_boxes) {
if (box->highlightedObject.data() == obj) {
freeBoundingBox(box);
break;
}
}
}
void BoundingRectHighlighter::highlightAll()
{
foreach (BoundingBox *box, m_boxes) {
if (box && box->highlightedObject.isNull()) {
// clear all highlights
clear();
return;
}
QGraphicsObject *item = box->highlightedObject.data();
QRectF boundingRectInSceneSpace(item->mapToScene(item->boundingRect()).boundingRect());
QRectF boundingRectInLayerItemSpace = mapRectFromScene(boundingRectInSceneSpace);
QRectF bboxRect = m_view->adjustToScreenBoundaries(boundingRectInLayerItemSpace);
QRectF edgeRect = bboxRect;
edgeRect.adjust(-1, -1, 1, 1);
box->highlightPolygon->setPolygon(QPolygonF(bboxRect));
box->highlightPolygonEdge->setPolygon(QPolygonF(edgeRect));
}
}
void BoundingRectHighlighter::refresh()
{
if (!m_boxes.isEmpty())
highlightAll();
}
} // namespace QtQuick1
} // namespace QmlJSDebugger<|fim▁end|> | m_boxes.removeOne(box);
m_freeBoxes << box;
} |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import patterns, url
from quenta.storybook import views
urlpatterns = patterns('',
url(r'^(?P<story_id>\d+/)', views.story, name='story'),#+ parametar
url(r'^(?P<story_id>\d+/html/)', views.story_html, name='story_html'),#+ parametar<|fim▁hole|> url(r'^$', views.stories_list, name='stories_list'),
)<|fim▁end|> | |
<|file_name|>test_status_api.py<|end_file_name|><|fim▁begin|># coding: utf-8
"""
Fitmarket
Mali broj ljudi - donori - dijele dnevna mjerenja svoje težine. Iz dnevne težine jednog donora određujemo vrijednosti dviju dionica: - dionica X ima vrijednost koja odgovara težini donora na taj dan. - inverzna dionica ~X ima vrijednost (150 kg - X). Primjetimo da: - kako X raste, ~X pada. - X + ~X = 150 kg Svaki igrač počinje igru sa 10,000 kg raspoloživog novca. Igrač koristi taj novac za trgovanje dionicama. Ukupna vrijednost igrača je zbroj rapoloživog novca i aktualne vrijednosti svih dionica koje posjeduje. Cilj igre je maksimizirati ukupnu vrijednost dobrim predviđanjem kretanja vrijednosti dionica. Na primjer, u prvom danu igrac kupi 125 dionica \"X\" za 80 kg. U drugom danu, dionica naraste na 82 kg. Ako igrac proda sve dionice \"X\", zaradio je 2 kg * 125 = 250 kg! Igra ne dopušta donoru da trguje vlastitim dionicama.
OpenAPI spec version: 1.1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
<|fim▁hole|>import unittest
import fitmarket_api
from fitmarket_api.rest import ApiException
from fitmarket_api.apis.status_api import StatusApi
class TestStatusApi(unittest.TestCase):
""" StatusApi unit test stubs """
def setUp(self):
self.api = fitmarket_api.apis.status_api.StatusApi()
def tearDown(self):
pass
def test_actual_state_get(self):
"""
Test case for actual_state_get
Dohvaca JSON sa trenutnim cijenama svih dionica.
"""
pass
def test_mystate_get(self):
"""
Test case for mystate_get
Dohvaca JSON koji prikazuje korisnikovu ukupnu vrijednost, neinvestiranu vrijednost i vrijednosti investirane u dionice.
"""
pass
def test_plot_txt_get(self):
"""
Test case for plot_txt_get
Dohvaca CSV sa cijenama svih dionica u svim prijasnjim mjerenjima.
"""
pass
if __name__ == '__main__':
unittest.main()<|fim▁end|> | from __future__ import absolute_import
import os
import sys |
<|file_name|>stats.js<|end_file_name|><|fim▁begin|>var fs = require('fs');
fs.stat('/tmp', function(err, stats) {
if (err) {<|fim▁hole|> return;
}
console.log(stats);
});<|fim▁end|> | console.error(err); |
<|file_name|>mem_init.rs<|end_file_name|><|fim▁begin|>// Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// 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.
//! Helper functions for memory initialisation.
use hal::stack::set_stack_limit;
extern {
static _data_load: u32;
static mut _data: u32;
static mut _edata: u32;
static mut _bss: u32;
static mut _ebss: u32;
static _eglobals: u32;
}
/// Helper function to initialise the stack limit.
#[inline(always)]
pub fn init_stack() {
set_stack_limit( unsafe { (&_eglobals as *const u32) } as u32);
}<|fim▁hole|>/// Copies `.data` sections in to RAM and initializes `.bss` sections to zero.
#[inline(always)]
pub fn init_data() {
unsafe {
let mut load_addr: *const u32 = &_data_load;
let mut mem_addr: *mut u32 = &mut _data;
while mem_addr < &mut _edata as *mut u32 {
*mem_addr = *load_addr;
mem_addr = ((mem_addr as u32) + 4) as *mut u32;
load_addr = ((load_addr as u32) + 4) as *const u32;
}
mem_addr = &mut _bss as *mut u32;
while mem_addr < &mut _ebss as *mut u32 {
*mem_addr = 0u32;
mem_addr = ((mem_addr as u32) + 4) as *mut u32;
}
}
}<|fim▁end|> |
/// Helper function to initialize memory. |
<|file_name|>spinner.rs<|end_file_name|><|fim▁begin|>// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use Buildable;
use Widget;
use ffi;
use glib::StaticType;
use glib::Value;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect_raw;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
glib_wrapper! {
pub struct Spinner(Object<ffi::GtkSpinner, ffi::GtkSpinnerClass, SpinnerClass>) @extends Widget, @implements Buildable;
match fn {
get_type => || ffi::gtk_spinner_get_type(),
}
}
impl Spinner {
pub fn new() -> Spinner {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_spinner_new()).unsafe_cast()
}
}
}
impl Default for Spinner {
fn default() -> Self {
Self::new()
}
}
pub const NONE_SPINNER: Option<&Spinner> = None;
pub trait SpinnerExt: 'static {
fn start(&self);
fn stop(&self);
fn get_property_active(&self) -> bool;
fn set_property_active(&self, active: bool);
fn connect_property_active_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<Spinner>> SpinnerExt for O {
fn start(&self) {
unsafe {
ffi::gtk_spinner_start(self.as_ref().to_glib_none().0);
}
}
fn stop(&self) {
unsafe {
ffi::gtk_spinner_stop(self.as_ref().to_glib_none().0);
}
}
fn get_property_active(&self) -> bool {
unsafe {
let mut value = Value::from_type(<bool as StaticType>::static_type());
gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut gobject_ffi::GObject, b"active\0".as_ptr() as *const _, value.to_glib_none_mut().0);
value.get().unwrap()
}
}
fn set_property_active(&self, active: bool) {
unsafe {
gobject_ffi::g_object_set_property(self.to_glib_none().0 as *mut gobject_ffi::GObject, b"active\0".as_ptr() as *const _, Value::from(&active).to_glib_none().0);
}
}
fn connect_property_active_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(self.as_ptr() as *mut _, b"notify::active\0".as_ptr() as *const _,
Some(transmute(notify_active_trampoline::<Self, F> as usize)), Box_::into_raw(f))
}
}
}
unsafe extern "C" fn notify_active_trampoline<P, F: Fn(&P) + 'static>(this: *mut ffi::GtkSpinner, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<Spinner> {
let f: &F = transmute(f);
f(&Spinner::from_glib_borrow(this).unsafe_cast())
}
<|fim▁hole|>}<|fim▁end|> | impl fmt::Display for Spinner {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Spinner")
} |
<|file_name|>clipgrab_tr.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="tr_TR">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>ClipGrab</name>
<message>
<location filename="clipgrab.cpp" line="37"/>
<source>Automatic language recognition</source>
<translation>Otomatik dil tespiti</translation>
</message>
<message>
<location filename="clipgrab.cpp" line="486"/>
<source>Downloading update … %1/%2 MBytes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="clipgrab.cpp" line="495"/>
<source>There was an error while downloading the update.: %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="clipgrab.cpp" line="509"/>
<source>The fingerprint of the downloaded update file could not be verified: %1 should have been %2</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="clipgrab.cpp" line="521"/>
<source>Could not open update file.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>LoginDialog</name>
<message>
<location filename="login_dialog.ui" line="20"/>
<source>Confirmation or Login Required</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="login_dialog.ui" line="54"/>
<source>Confirmation or login required</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="login_dialog.ui" line="67"/>
<source>This video requires you to sign in or confirm your access before downloading it.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="login_dialog.ui" line="100"/>
<source>about:blank</source>
<translation type="unfinished">about:blank</translation>
</message>
<message>
<location filename="login_dialog.ui" line="124"/>
<source>Remember login</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="mainwindow.cpp" line="249"/>
<location filename="mainwindow.cpp" line="261"/>
<source>Select Target</source>
<translation>Hedef Seçiniz</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="331"/>
<source>Please wait while ClipGrab is loading information about the video ...</source>
<translation>Video hakkında bilgi toplanırken lütfen bekleyiniz...</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="348"/>
<source>Please enter the link to the video you want to download in the field below.</source>
<translation>İndirmek istediğiniz videonun link'ini aşağıdaki aşağıdaki bölüme giriniz.</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="353"/>
<source>The link you have entered seems to not be recognised by any of the supported portals.<br/>Now ClipGrab will check if it can download a video from that site anyway.</source>
<translation>Girdiğiniz link desteklenen sitelerden birine ait olarak görünmüyor.<br/>Video yine de indirilmeye çalışılacak.</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="400"/>
<source>No downloadable video could be found.<br />Maybe you have entered the wrong link or there is a problem with your connection.</source>
<translation>İndirilebilecek bir video bulunamadı.<br />Yanlış bir link girmiş olabilirsiniz ya da internet bağlantınızla ilgili bir problem olabilir.</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="413"/>
<source>ClipGrab - Select target path</source>
<translation>ClipGrab - Hedef klasörü giriniz</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="460"/>
<source>ClipGrab: Video discovered in your clipboard</source>
<translation>ClipGrab: Kopyalanan bir video tespit edildi</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="460"/>
<source>ClipGrab has discovered the address of a compatible video in your clipboard. Click on this message to download it now.</source>
<translation>Uyumlu bir video link'ini kopyaladığınız tespit edildi. İndirmek için buraya tıklayınız.</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="566"/>
<source>ClipGrab - Exit confirmation</source>
<translation>ClipGrab - Çıkış onayı</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="566"/>
<source>There is still at least one download in progress.<br />If you exit the program now, all downloads will be canceled and cannot be recovered later.<br />Do you really want to quit ClipGrab now?</source>
<translation>Devam etmekte olan en az bir indirme mevcut.<br />Şimdi çıkarsanız tüm indirmeler iptal edilecek ve daha sonra kurtarılamayacaktır.<br />ClipGrab'den çıkmak istediğinize emin misiniz?</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="603"/>
<source>Download finished</source>
<translation>İndirme tamamlandı</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="603"/>
<source>Downloading and converting “%title” is now finished.</source>
<translation>"%title" isimli dosyanın indirilmesi ve dönüştürülmesi tamamlandı.</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="607"/>
<source>All downloads finished</source>
<translation>Tüm indirmeler tamamlandı</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="607"/>
<source>ClipGrab has finished downloading and converting all selected videos.</source>
<translation>Seçili tüm videoların indirilmesi ve dönüştürülmesi tamamlandı.</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="672"/>
<location filename="mainwindow.cpp" line="674"/>
<location filename="mainwindow.cpp" line="681"/>
<location filename="mainwindow.cpp" line="683"/>
<source>ClipGrab</source>
<translation>ClipGrab</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="672"/>
<location filename="mainwindow.cpp" line="674"/>
<source> MiB</source>
<translation>MiB</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="674"/>
<source> KiB</source>
<translation>KiB</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="681"/>
<location filename="mainwindow.cpp" line="683"/>
<source>Currently no downloads in progress.</source>
<translation>Devam etmekte olan bir indirme yok.</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="684"/>
<source>ClipGrab - Download and Convert Online Videos</source>
<translation>ClipGrab - Online Videoları İndirin ve Dönüştürün</translation>
</message>
<message>
<location filename="mainwindow.cpp" line="880"/>
<source>&Open downloaded file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="mainwindow.cpp" line="881"/>
<source>Open &target folder</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="mainwindow.cpp" line="883"/>
<source>&Pause download</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="mainwindow.cpp" line="884"/>
<source>&Restart download</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="mainwindow.cpp" line="885"/>
<source>&Cancel download</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="mainwindow.cpp" line="887"/>
<source>Copy &video link</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="mainwindow.cpp" line="888"/>
<source>Open video link in &browser</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="mainwindow.cpp" line="893"/>
<source>Resume download</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="mainwindow.cpp" line="902"/>
<source>Show in &Finder</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MainWindowClass</name>
<message>
<location filename="mainwindow.ui" line="14"/>
<source>ClipGrab - Download and Convert Online Videos</source>
<translation>ClipGrab - Online Videoları İndirin ve Dönüştürün</translation>
</message>
<message>
<location filename="mainwindow.ui" line="136"/>
<source>Search</source>
<translation>Ara</translation>
</message>
<message>
<location filename="mainwindow.ui" line="155"/>
<source>Enter keywords in the box below in order to search videos on YouTube</source>
<translation>YouTube'da video aratmak için ilgili kelimeleri aşağıya giriniz</translation>
</message>
<message>
<location filename="mainwindow.ui" line="163"/>
<source>about:blank</source>
<translation>about:blank</translation>
</message>
<message>
<location filename="mainwindow.ui" line="172"/>
<source>Downloads</source>
<translation>İndirmeler</translation>
</message>
<message>
<location filename="mainwindow.ui" line="370"/>
<source>Grab this clip!</source>
<translation>Bu videoyu kap!</translation>
</message>
<message>
<location filename="mainwindow.ui" line="203"/>
<source>Quality:</source>
<translation>Kalite:</translation>
</message>
<message>
<location filename="mainwindow.ui" line="216"/>
<source>Please enter the link to the video you want to download in the field below.</source>
<translation>Lütfen indirmek istediğiniz videonun link'ini aşağıdaki kutuya giriniz.</translation>
</message>
<message>
<location filename="mainwindow.ui" line="251"/>
<source>Format:</source>
<translation>Biçim:</translation>
</message>
<message>
<location filename="mainwindow.ui" line="290"/>
<source>Current Downloads:</source>
<translation>Şu Anki İndirmeler:</translation>
</message>
<message>
<location filename="mainwindow.ui" line="300"/>
<source>Cancel selected download</source>
<translation>Seçili indirmeyi iptal et</translation>
</message>
<message>
<location filename="mainwindow.ui" line="310"/>
<source>Open the target folder of the selected download</source>
<translation>Seçili indirmenin hedef klasörünü aç</translation>
</message>
<message>
<location filename="mainwindow.ui" line="330"/>
<source>Portal</source>
<translation>Portal</translation>
</message>
<message>
<location filename="mainwindow.ui" line="335"/>
<source>Title</source>
<translation>Başlık</translation>
</message>
<message>
<location filename="mainwindow.ui" line="340"/>
<source>Format</source>
<translation>Biçim</translation>
</message>
<message>
<location filename="mainwindow.ui" line="345"/>
<source>Progress</source>
<translation>İlerleme</translation>
</message>
<message>
<location filename="mainwindow.ui" line="356"/>
<source>Pause selected download</source>
<translation>Seçili indirmeyi beklet</translation>
</message>
<message>
<location filename="mainwindow.ui" line="389"/>
<source>…</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="mainwindow.ui" line="397"/>
<source>Settings</source>
<translation>Ayarlar</translation>
</message>
<message>
<location filename="mainwindow.ui" line="410"/>
<source>General</source>
<translation>Genel</translation>
</message>
<message>
<location filename="mainwindow.ui" line="434"/>
<source>Here you can adjust some general settings concerning the behaviour of ClipGrab.</source>
<translation>ClipGrab'le ilgili genel ayarları buradan değiştirebilirsiniz.</translation>
</message>
<message>
<location filename="mainwindow.ui" line="445"/>
<source>Target Path</source>
<translation>Hedef Klasör</translation>
</message>
<message>
<location filename="mainwindow.ui" line="451"/>
<source>Always save at the last used path.</source>
<translation>Her zaman son kullanılan klasöre kaydet.</translation>
</message>
<message>
<location filename="mainwindow.ui" line="465"/>
<source>Here you can configure where the downloaded videos are to be saved.</source>
<translation>İndirilen videoların nereye kaydedileceğini buradan ayarlayabilirsiniz.</translation>
</message>
<message>
<location filename="mainwindow.ui" line="472"/>
<source>Browse ...</source>
<translation>Gözat...</translation>
</message>
<message>
<location filename="mainwindow.ui" line="479"/>
<source>Never ask for file name</source>
<translation>Dosya ismini hiçbir zaman sorma</translation>
</message>
<message>
<location filename="mainwindow.ui" line="500"/>
<source>Metadata</source>
<translation>Metadata</translation>
</message>
<message>
<location filename="mainwindow.ui" line="506"/>
<source>Here you can configure if ClipGrab is supposed to add metadata (ID3 tags) to your mp3 files.</source>
<translation>MP3 dosyalarınıza metadata (ID3 tag'leri) eklenip eklenmeyeceğini buradan ayarlayabilirsiniz.</translation>
</message>
<message>
<location filename="mainwindow.ui" line="513"/>
<source>Use metadata</source>
<translation>Metadata kullan</translation>
</message>
<message>
<location filename="mainwindow.ui" line="534"/>
<source>Clipboard</source>
<translation>Pano</translation>
</message>
<message>
<location filename="mainwindow.ui" line="540"/>
<source>Here you can configure how ClipGrab behaves when a downloadable video is discovered in your clipboard.</source>
<translation>İndirilebilecek bir video link'ini kopyaladığınız tespit edildiğinde ClipGrab'in ne yapacağını burdan ayarlayabilirsiniz.</translation>
</message>
<message>
<location filename="mainwindow.ui" line="547"/>
<source>Always download</source>
<translation>Her zaman indir</translation>
</message>
<message>
<location filename="mainwindow.ui" line="554"/>
<source>Never download</source>
<translation>Hiçbir zaman indirme</translation>
</message>
<message>
<location filename="mainwindow.ui" line="561"/>
<source>Always ask</source>
<translation>Her zaman sor</translation>
</message>
<message>
<location filename="mainwindow.ui" line="582"/>
<source>Notifications</source>
<translation>Bildirimler</translation>
</message>
<message>
<location filename="mainwindow.ui" line="588"/>
<source>After each download</source>
<translation>Her indirmeden sonra</translation>
</message>
<message>
<location filename="mainwindow.ui" line="595"/>
<source>After all downloads have been completed</source>
<translation>Tüm indirmeler tamamlandıktan sonra</translation>
</message>
<message>
<location filename="mainwindow.ui" line="615"/>
<source>Here you can configure when ClipGrab is supposed to display notifications.</source>
<translation>Bildirimlerin ne zaman gösterileceğini buradan ayarlayabilirsiniz.</translation>
</message>
<message>
<location filename="mainwindow.ui" line="622"/>
<source>Never</source>
<translation>Asla</translation>
</message>
<message>
<location filename="mainwindow.ui" line="630"/>
<source>Proxy</source>
<translation>Vekil Sunucu</translation>
</message>
<message>
<location filename="mainwindow.ui" line="636"/>
<source>Use a proxy server</source>
<translation>Vekil sunucu kullan</translation>
</message>
<message>
<location filename="mainwindow.ui" line="646"/>
<source>Proxy settings</source>
<translation>Vekil sunucu ayarları</translation>
</message>
<message>
<location filename="mainwindow.ui" line="655"/>
<source>Hostname/IP:</source>
<translation>Host ismi/IP adresi:</translation>
</message>
<message>
<location filename="mainwindow.ui" line="662"/>
<source>Port:</source>
<translation>Port:</translation>
</message>
<message>
<location filename="mainwindow.ui" line="689"/>
<source>Proxy type:</source>
<translation>Vekil sunucu tipi:</translation>
</message>
<message>
<location filename="mainwindow.ui" line="697"/>
<source>HTTP Proxy</source>
<translation>HTTP Vekil Sunucusu</translation>
</message>
<message>
<location filename="mainwindow.ui" line="702"/>
<source>Socks5 Proxy</source>
<translation>Socks5 Vekil Sunucusu</translation>
</message>
<message>
<location filename="mainwindow.ui" line="729"/>
<source>Proxy authentication</source>
<translation>Vekil sunucu doğrulaması</translation>
</message>
<message>
<location filename="mainwindow.ui" line="735"/>
<source>Username:</source>
<translation>Kullanıcı Adı:</translation>
</message>
<message>
<location filename="mainwindow.ui" line="752"/>
<source>Password:</source>
<translation>Parola:</translation>
</message>
<message>
<location filename="mainwindow.ui" line="765"/>
<source>Proxy requires authentication</source>
<translation>Vekil sunucu doğrulama gerektirir</translation>
</message>
<message>
<location filename="mainwindow.ui" line="773"/>
<source>Other</source>
<translation>Diğer</translation>
</message>
<message>
<location filename="mainwindow.ui" line="800"/>
<source>Remove finished downloads from list</source>
<translation>Tamamlanan indirmeleri listeden kaldır</translation>
</message>
<message>
<location filename="mainwindow.ui" line="779"/>
<source>Minimize ClipGrab to the system tray</source>
<translation>ClipGrab'i küçültünce bildirim alanına yerleştir</translation>
</message>
<message>
<location filename="mainwindow.ui" line="786"/>
<source>Use WebM if possible</source>
<translation>Mümkünse WebM kullan</translation>
</message>
<message>
<location filename="mainwindow.ui" line="793"/>
<source>Ignore SSL errors</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="mainwindow.ui" line="820"/>
<source>Remember logins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="mainwindow.ui" line="827"/>
<source>Remember video quality</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="mainwindow.ui" line="839"/>
<source>Language</source>
<translation>Dil</translation>
</message>
<message>
<location filename="mainwindow.ui" line="863"/>
<source>Here you can change the language of ClipGrab.</source>
<translation>ClipGrab'in kullandığı dili buradan değiştirebilirsiniz.</translation>
</message>
<message>
<location filename="mainwindow.ui" line="870"/>
<source>Please select a language from the list below. You have to restart ClipGrab in order to apply you selection.</source>
<translation>Lütfen aşağıdaki listeden bir dil seçiniz. Değişimin tamamlanması için ClipGrab'i kapatıp tekrar açmalısınız.</translation>
</message>
<message>
<location filename="mainwindow.ui" line="907"/>
<source>Conversion</source>
<translation>Dönüştürme</translation>
</message>
<message>
<location filename="mainwindow.ui" line="930"/>
<source>Experts can create custom presets for the video conversion here.</source>
<translation>Uzman olanlar video dönüştürmeleri için buradan önayar belirleyebilir.</translation>
</message>
<message>
<location filename="mainwindow.ui" line="937"/>
<source>Format preset</source>
<translation>Biçim önayarı</translation>
</message>
<message>
<location filename="mainwindow.ui" line="947"/>
<source>Add new preset</source>
<translation>Yeni önayar ekle</translation>
</message>
<message>
<location filename="mainwindow.ui" line="954"/>
<source>Remove selected preset</source>
<translation>Seçili önayarı kaldır</translation>
</message>
<message>
<location filename="mainwindow.ui" line="977"/>
<source>Audio</source>
<translation>Ses</translation>
</message>
<message>
<location filename="mainwindow.ui" line="989"/>
<location filename="mainwindow.ui" line="1041"/>
<source>Codec</source>
<translation>Codec</translation>
</message>
<message>
<location filename="mainwindow.ui" line="1015"/>
<location filename="mainwindow.ui" line="1103"/>
<source>Bitrate (kb/s)</source>
<translation>Bit hızı (kb/s)</translation>
</message>
<message>
<location filename="mainwindow.ui" line="1022"/>
<source>Disable Audio</source>
<translation>Sesi devre dışı bırak</translation>
</message>
<message>
<location filename="mainwindow.ui" line="1032"/>
<source>Video</source>
<translation>Video</translation>
</message>
<message>
<location filename="mainwindow.ui" line="1054"/>
<source>Frames/second</source>
<translation>Kare/saniye</translation>
</message>
<message>
<location filename="mainwindow.ui" line="1113"/>
<source>Disable video</source>
<translation>Videoyu devre dışı bırak</translation>
</message>
<message>
<location filename="mainwindow.ui" line="1128"/>
<source>About</source>
<translation>Hakkında</translation>
</message>
<message>
<location filename="mainwindow.ui" line="1134"/>
<source><h2>Support ClipGrab!</h2>
<p>Only with your support, ClipGrab can remain free software!<br>So if you like ClipGrab and also want to help ensuring its further development, please consider making a donation.</p></source>
<translation><h2>ClipGrab'i Destekleyin!</h2>
<p>ClipGrab sadece sizin desteğinizle ücretsiz bir yazılım olarak kalabilir!<br>Bu yüzden eğer ClipGrab'i seviyorsanız ve gelişiminin devam etmesini istiyorsanız lütfen bir bağış yapmayı düşünün.</p></translation>
</message>
<message>
<location filename="mainwindow.ui" line="1177"/>
<source><h2>Translation</h2>
ClipGrab is already available in many languages. If ClipGrab has not been translated into your language yet and if you want to contribute a translation, please check <a href="http://clipgrab.de/translate">http://clipgrab.de/translate</a> for further information.</source>
<translatorcomment>Added my name in final sentence for credits in Turkish translation. :-)</translatorcomment>
<translation><h2>Çeviri</h2>
Çoğu dilde ClipGrab zaten mevcut. Eğer ClipGrab henüz sizin dilinize çevrilmediyse ve çevirisine katkıda bulunmak isterseniz daha fazla bilgi için lütfen <a href="http://clipgrab.de/translate">http://clipgrab.de/translate</a> adresini ziyaret ediniz. ClipGrab'in bu sürümü Emre Erokyar tarafından çevrilmiştir.</translation>
</message>
<message>
<location filename="mainwindow.ui" line="1194"/>
<source><h2>Thanks</h2>
ClipGrab relies on the work of the Qt project and the ffmpeg team.<br>
Visit <a href="http://qt-project.org">qt-project.org</a> and <a href="http://ffmpeg.org">ffmpeg.org</a> for further information.</source>
<translation><h2>Teşekkürler</h2>
ClipGrab, Qt project'in ve ffmpeg takımının çalışmasına dayanır.<br>
Ayrıntılı bilgi için <a href="http://qt-project.org">qt-project.org</a> ve <a href="http://ffmpeg.org">ffmpeg.org</a> adreslerini ziyaret ediniz.</translation>
</message>
</context>
<context>
<name>MetadataDialog</name>
<message>
<location filename="metadata-dialog.ui" line="14"/>
<source>ClipGrab - enter metadata</source>
<translation>ClipGrab - metadata giriniz</translation>
</message>
<message>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; font-weight:600;">Please enter the metadata for your download. If you don't want to add</span></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; font-weight:600;">metadata, just leave the fields empty.</span></p></body></html></source>
<translation type="obsolete"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; font-weight:600;">Lütfen indirmeniz için metadata giriniz. Eğer metadata eklemeyecekseniz</span></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'MS Shell Dlg 2'; font-size:8pt; font-weight:600;">ilgili bölümleri boş bırakabilirsiniz.</span></p></body></html></translation>
</message>
<message>
<location filename="metadata-dialog.ui" line="25"/>
<source>Please enter the metadata for your download. If you don't want to add metadata, just leave the fields empty.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="metadata-dialog.ui" line="45"/>
<source>Title:</source>
<translation>Başlık:</translation>
</message>
<message>
<location filename="metadata-dialog.ui" line="52"/>
<source>Artist:</source>
<translation>Artist:</translation>
</message>
</context>
<context>
<name>UpdateMessage</name>
<message>
<location filename="update_message.ui" line="14"/>
<source>Update for ClipGrab</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="update_message.ui" line="69"/>
<source>ClipGrab %1 is now available (you are using %2). Would you like to install the update?</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="update_message.ui" line="83"/>
<source>There is an update for your version of ClipGrab!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="update_message.ui" line="183"/>
<source>Skip this update</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="update_message.ui" line="193"/>
<source>Download update</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="update_message.ui" line="204"/>
<source>about:blank</source>
<translation type="unfinished">about:blank</translation>
</message>
<message>
<location filename="update_message.ui" line="212"/>
<source>Remind me later</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="update_message.ui" line="229"/>
<source>The update will begin in just a moment …</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>YoutubePassword</name>
<message>
<source>Password required</source>
<translation type="obsolete">Parola gerekli</translation>
</message>
<message>
<source>about:blank</source>
<translation type="obsolete">about:blank</translation>
</message>
<message>
<source>This video has an age restriction or is only available for certain users.
Please login with your Google account in order to download this video.</source>
<translation type="obsolete">Bu videonun bir yaş sınırlaması var ya da sadece belirli kullanıcalar için açık.
Videoyu indirebilmek için lütfen Google hesabınızla oturum açınız.</translation>
</message>
<message>
<source>Password:</source>
<translation type="obsolete">Parola:</translation>
</message>
<message>
<source>E-mail:</source>
<translation type="obsolete">E-posta:</translation>
</message>
<message>
<source>Save login data</source>
<translation type="obsolete">Oturum açma bilgilerini kaydet</translation>
</message>
</context>
<context>
<name>converter_copy</name>
<message>
<location filename="converter_copy.cpp" line="28"/>
<source>Original</source>
<translation>Orjinal</translation>
</message>
</context>
<context>
<name>converter_ffmpeg</name>
<message>
<location filename="converter_ffmpeg.cpp" line="212"/>
<source>MPEG4</source>
<translation>MPEG4</translation>
</message>
<message>
<location filename="converter_ffmpeg.cpp" line="213"/>
<source>WMV (Windows)</source>
<translation>WMV (Windows)</translation>
</message>
<message>
<location filename="converter_ffmpeg.cpp" line="214"/>
<source>OGG Theora</source>
<translation>OGG Theora</translation>
</message>
<message>
<location filename="converter_ffmpeg.cpp" line="215"/>
<source>MP3 (audio only)</source>
<translation>MP3 (sadece ses)</translation>
</message>
<message>
<location filename="converter_ffmpeg.cpp" line="216"/>
<source>OGG Vorbis (audio only)</source>
<translation>OGG Vorbis (sadece ses)</translation>
</message>
<message>
<location filename="converter_ffmpeg.cpp" line="217"/>
<source>Original (audio only)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="converter_ffmpeg.cpp" line="345"/>
<source>No installed version of avconv or ffmpeg coud be found. Converting files and downloading 1080p videos from YouTube is not supported.</source>
<translation>avconv ya da ffmpeg'in kurulu sürümü bulunamadı. Dosyaların dönüştürülmesi ve YouTube'dan 1080p videoların indirilmesi desteklenmiyor.</translation>
</message>
<message>
<location filename="converter_ffmpeg.cpp" line="360"/>
<source>The installed version of %1 is outdated.
Downloading 1080p videos from YouTube is not supported.</source>
<translation>%1 için kurulu sürümü güncel değil.
YouTube'dan 1080p videoların indirilmesi desteklenmiyor.</translation>
</message>
</context>
<context>
<name>messageDialog</name>
<message>
<location filename="message_dialog.ui" line="14"/>
<source>Dialog</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="message_dialog.ui" line="35"/>
<source>Close this message</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="message_dialog.ui" line="62"/>
<source>about:blank</source>
<translation type="unfinished">about:blank</translation>
</message>
</context>
<context>
<name>playlistDialog</name>
<message>
<location filename="playlist_dialog.ui" line="14"/>
<source>Dialog</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="playlist_dialog.ui" line="35"/>
<source>Grab those clips!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="playlist_dialog.ui" line="58"/>
<source>Here you can set up the download of multiple videos at once.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="playlist_dialog.ui" line="65"/>
<source>Select all</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="playlist_dialog.ui" line="72"/>
<source>Add link to list</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="playlist_dialog.ui" line="79"/>
<source>Cancel</source><|fim▁hole|> </message>
<message>
<location filename="playlist_dialog.ui" line="89"/>
<source>Deselect all</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>video</name>
<message>
<location filename="video.cpp" line="159"/>
<location filename="video.cpp" line="305"/>
<source>Converting ...</source>
<translation>Dönüştürülüyor...</translation>
</message>
<message>
<location filename="video.cpp" line="200"/>
<source>Downloading ...</source>
<translation>İndiriliyor...</translation>
</message>
<message>
<location filename="video.cpp" line="200"/>
<source> MiB</source>
<translation>MiB</translation>
</message>
<message>
<location filename="video.cpp" line="370"/>
<source>Finished</source>
<translation>Tamamlandı</translation>
</message>
<message>
<location filename="video.cpp" line="376"/>
<source>Finished!</source>
<translation>Tamamlandı!</translation>
</message>
<message>
<location filename="video.cpp" line="515"/>
<source>Cancelled</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>video_clipfish</name>
<message>
<source>normal</source>
<translation type="obsolete">normal</translation>
</message>
</context>
<context>
<name>video_dailymotion</name>
<message>
<location filename="video_dailymotion.cpp" line="83"/>
<source>HD (1080p)</source>
<translation>HD (1080p)</translation>
</message>
<message>
<location filename="video_dailymotion.cpp" line="84"/>
<source>HD (720p)</source>
<translation>HD (720p)</translation>
</message>
<message>
<location filename="video_dailymotion.cpp" line="85"/>
<source>480p</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="video_dailymotion.cpp" line="86"/>
<source>380p</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="video_dailymotion.cpp" line="87"/>
<source>240p</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>high (480p)</source>
<translation type="obsolete">Yüksek (480p)</translation>
</message>
<message>
<source>low (240p)</source>
<translation type="obsolete">Düşük (240p)</translation>
</message>
</context>
<context>
<name>video_facebook</name>
<message>
<location filename="video_facebook.cpp" line="111"/>
<location filename="video_facebook.cpp" line="112"/>
<location filename="video_facebook.cpp" line="141"/>
<source>HD</source>
<translation type="unfinished">HD</translation>
</message>
<message>
<location filename="video_facebook.cpp" line="113"/>
<location filename="video_facebook.cpp" line="114"/>
<source>normal</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>video_heuristic</name>
<message>
<location filename="video_heuristic.cpp" line="75"/>
<location filename="video_heuristic.cpp" line="88"/>
<location filename="video_heuristic.cpp" line="100"/>
<location filename="video_heuristic.cpp" line="113"/>
<location filename="video_heuristic.cpp" line="128"/>
<location filename="video_heuristic.cpp" line="142"/>
<location filename="video_heuristic.cpp" line="155"/>
<location filename="video_heuristic.cpp" line="168"/>
<location filename="video_heuristic.cpp" line="182"/>
<source>normal</source>
<translation></translation>
</message>
</context>
<context>
<name>video_myspass</name>
<message>
<location filename="video_myspass.cpp" line="87"/>
<source>high</source>
<translation>yüksek</translation>
</message>
</context>
<context>
<name>video_myvideo</name>
<message>
<source>normal</source>
<translation type="obsolete">normal</translation>
</message>
</context>
<context>
<name>video_vimeo</name>
<message>
<source>HD</source>
<translation type="obsolete">HD</translation>
</message>
<message>
<source>high</source>
<translation type="obsolete">yüksek</translation>
</message>
</context>
<context>
<name>video_youtube</name>
<message>
<location filename="video_youtube.cpp" line="152"/>
<source>HD (1080p)</source>
<translation type="unfinished">HD (1080p)</translation>
</message>
<message>
<location filename="video_youtube.cpp" line="156"/>
<source>HD (1440p)</source>
<translation type="unfinished">HD (720p) {1440p?}</translation>
</message>
<message>
<location filename="video_youtube.cpp" line="160"/>
<source>4K (2160p)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="video_youtube.cpp" line="164"/>
<source>5K (2880p)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="video_youtube.cpp" line="168"/>
<source>8K (4320p)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="video_youtube.cpp" line="498"/>
<location filename="video_youtube.cpp" line="529"/>
<location filename="video_youtube.cpp" line="625"/>
<location filename="video_youtube.cpp" line="628"/>
<source>Original</source>
<translation type="unfinished">Orjinal</translation>
</message>
<message>
<location filename="video_youtube.cpp" line="681"/>
<source>normal</source>
<translation>düşük</translation>
</message>
</context>
</TS><|fim▁end|> | <translation type="unfinished"></translation> |
<|file_name|>AppUtil.java<|end_file_name|><|fim▁begin|>package com.sms4blood.emergencyhealthservices.util;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;
import com.sms4blood.emergencyhealthservices.Sms;
import com.sms4blood.emergencyhealthservices.app.EhsApplication;
import java.text.DecimalFormat;
/**
* Created by Vishnu on 8/1/2015.
*/
public class AppUtil extends Util {
public static boolean callNumber(String phoneNumber) {
boolean isValidPhoneNumber = checkPhoneNumber(phoneNumber);
if (isValidPhoneNumber) {
String callUri = "tel:" + phoneNumber;
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(callUri));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(callIntent);
} else {
Toast.makeText(EhsApplication.getContext(), "Invalid phone number.", Toast.LENGTH_SHORT).show();
}
return isValidPhoneNumber;
}
public static boolean sendSms(String phoneNumber, String message) {
boolean isValidPhoneNumber = checkPhoneNumber(phoneNumber);
if (isValidPhoneNumber) {
// /*It is better to let the android manage the sms sending task using native messaging app*/
// Intent smsIntent = new Intent(Intent.ACTION_VIEW);
// // Invokes only SMS/MMS clients
// smsIntent.setType("vnd.android-dir/mms-sms");
// // Specify the Phone Number
// smsIntent.putExtra("address", phoneNumber);
// // Specify the Message
// smsIntent.putExtra("sms_body", message);
// smsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// try {
// startActivity(smsIntent);
// } catch (Exception e) {
// e.printStackTrace();
// Toast.makeText(EhsApplication.getContext(), "Unable to send sms to this number.", Toast.LENGTH_SHORT)
// .show();
// }
Intent i=new Intent(EhsApplication.getContext(), Sms.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle bundle = new Bundle();
bundle.putString("mobileno",phoneNumber);
i.putExtras(bundle);
startActivity(i);
} else {
Toast.makeText(EhsApplication.getContext(), "Invalid phone number.", Toast.LENGTH_SHORT).show();
}
return isValidPhoneNumber;
}
public static boolean showMap(String latitude, String longitude) {
try {
if (!TextUtils.isEmpty(latitude) && (!TextUtils.isEmpty(longitude))) {
Uri gmmIntentUri = Uri.parse("google.navigation:q=" + latitude + "," + longitude);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
mapIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mapIntent);
return true;
} else {
Toast.makeText(EhsApplication.getContext(), "Address not available.", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean showMap(String address) {
try {
if (!TextUtils.isEmpty(address)) {
String encodedAddress = address.replaceAll("\n", " ");
Uri gmmIntentUri = Uri.parse("google.navigation:q=" + encodedAddress);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
mapIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mapIntent);
return true;
} else {
Toast.makeText(EhsApplication.getContext(), "Address not available.", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* @param fromLatitude
* @param fromLongitude
* @param toLatitude
* @param toLongitude<|fim▁hole|>
try {
Location.distanceBetween(fromLatitude, fromLongitude, toLatitude, toLongitude, results);
} catch (Exception e) {
if (e != null)
e.printStackTrace();
}
int dist = (int) results[0];
if(dist<=0) {
return 0D;
}
DecimalFormat decimalFormat = new DecimalFormat("#.##");
results[0]/=1000D;
String distance = decimalFormat.format(results[0]);
double d = Double.parseDouble(distance);
return d;
}
}<|fim▁end|> | * @return distance between the two latitudes and longitudes in kms.
*/
public static double calculateDistance(double fromLatitude,double fromLongitude,double toLatitude,double toLongitude) {
float results[] = new float[1]; |
<|file_name|>format_me_please.rs<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | pub fn hello( ) { } |
<|file_name|>basiccircle.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from bokeh.plotting import figure, output_file, show
p = figure(width=400, height=400)
p.circle(2, 3, radius=.5, alpha=0.5)
output_file('out.html')
show(p)<|fim▁end|> | |
<|file_name|>state.js<|end_file_name|><|fim▁begin|>/*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import _ from 'underscore';
import Backbone from 'backbone';
export default Backbone.Model.extend({
defaults: function () {
return {
page: 1,
maxResultsReached: false,
query: {},
facets: []
};
},
nextPage: function () {
var page = this.get('page');
this.set({ page: page + 1 });
},
clearQuery: function (query) {
var q = {};
Object.keys(query).forEach(function (key) {
if (query[key]) {
q[key] = query[key];<|fim▁hole|> }
});
return q;
},
_areQueriesEqual: function (a, b) {
var equal = Object.keys(a).length === Object.keys(b).length;
Object.keys(a).forEach(function (key) {
equal = equal && a[key] === b[key];
});
return equal;
},
updateFilter: function (obj, options) {
var oldQuery = this.get('query'),
query = _.extend({}, oldQuery, obj),
opts = _.defaults(options || {}, { force: false });
query = this.clearQuery(query);
if (opts.force || !this._areQueriesEqual(oldQuery, query)) {
this.setQuery(query);
}
},
setQuery: function (query) {
this.set({ query: query }, { silent: true });
this.set({ changed: true });
this.trigger('change:query');
}
});<|fim▁end|> | |
<|file_name|>DeleteAssociationRequestMarshaller.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 com.amazonaws.services.simplesystemsmanagement.model.transform;
import static com.amazonaws.util.StringUtils.UTF8;
import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;
/**
* DeleteAssociationRequest Marshaller
*/
public class DeleteAssociationRequestMarshaller implements
Marshaller<Request<DeleteAssociationRequest>, DeleteAssociationRequest> {
public Request<DeleteAssociationRequest> marshall(
DeleteAssociationRequest deleteAssociationRequest) {
if (deleteAssociationRequest == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(...)");
}
Request<DeleteAssociationRequest> request = new DefaultRequest<DeleteAssociationRequest>(
deleteAssociationRequest, "AWSSimpleSystemsManagement");
request.addHeader("X-Amz-Target", "AmazonSSM.DeleteAssociation");
request.setHttpMethod(HttpMethodName.POST);
request.setResourcePath("");
<|fim▁hole|> JSONWriter jsonWriter = new JSONWriter(stringWriter);
jsonWriter.object();
if (deleteAssociationRequest.getName() != null) {
jsonWriter.key("Name")
.value(deleteAssociationRequest.getName());
}
if (deleteAssociationRequest.getInstanceId() != null) {
jsonWriter.key("InstanceId").value(
deleteAssociationRequest.getInstanceId());
}
jsonWriter.endObject();
String snippet = stringWriter.toString();
byte[] content = snippet.getBytes(UTF8);
request.setContent(new StringInputStream(snippet));
request.addHeader("Content-Length",
Integer.toString(content.length));
request.addHeader("Content-Type", "application/x-amz-json-1.1");
} catch (Throwable t) {
throw new AmazonClientException(
"Unable to marshall request to JSON: " + t.getMessage(), t);
}
return request;
}
}<|fim▁end|> | try {
StringWriter stringWriter = new StringWriter(); |
<|file_name|>payment.py<|end_file_name|><|fim▁begin|>import json
from collections import OrderedDict
from django import forms
from django.template.loader import get_template
from django.utils.translation import ugettext_lazy as _
from pretix.base.payment import BasePaymentProvider
class BankTransfer(BasePaymentProvider):
identifier = 'banktransfer'
verbose_name = _('Bank transfer')
@property
def settings_form_fields(self):
return OrderedDict(
list(super().settings_form_fields.items()) + [
('bank_details',
forms.CharField(
widget=forms.Textarea,
label=_('Bank account details'),
))
]
)
def payment_form_render(self, request) -> str:
template = get_template('pretixplugins/banktransfer/checkout_payment_form.html')
ctx = {'request': request, 'event': self.event, 'settings': self.settings}
return template.render(ctx)
def checkout_prepare(self, request, total):
return True<|fim▁hole|>
def checkout_confirm_render(self, request):
form = self.payment_form(request)
template = get_template('pretixplugins/banktransfer/checkout_payment_confirm.html')
ctx = {'request': request, 'form': form, 'settings': self.settings}
return template.render(ctx)
def order_pending_mail_render(self, order) -> str:
template = get_template('pretixplugins/banktransfer/email/order_pending.txt')
ctx = {'event': self.event, 'order': order, 'settings': self.settings}
return template.render(ctx)
def order_pending_render(self, request, order) -> str:
template = get_template('pretixplugins/banktransfer/pending.html')
ctx = {'request': request, 'order': order, 'settings': self.settings}
return template.render(ctx)
def order_control_render(self, request, order) -> str:
if order.payment_info:
payment_info = json.loads(order.payment_info)
else:
payment_info = None
template = get_template('pretixplugins/banktransfer/control.html')
ctx = {'request': request, 'event': self.event, 'settings': self.settings,
'payment_info': payment_info, 'order': order}
return template.render(ctx)<|fim▁end|> |
def payment_is_valid_session(self, request):
return True |
<|file_name|>policy_selectors.go<|end_file_name|><|fim▁begin|>// SPDX-License-Identifier: Apache-2.0
// Copyright 2019 Authors of Cilium
package cmd
import (
"fmt"
"os"
"text/tabwriter"
"github.com/spf13/cobra"
"github.com/cilium/cilium/pkg/command"
)
// policyGetCmd represents the policy_get command
var policyCacheGetCmd = &cobra.Command{
Use: "selectors",
Short: "Display cached information about selectors",
Run: func(cmd *cobra.Command, args []string) {
if resp, err := client.PolicyCacheGet(); err != nil {
Fatalf("Cannot get policy: %s\n", err)
} else if command.OutputJSON() {
if err := command.PrintOutput(resp); err != nil {
os.Exit(1)
}
} else if resp != nil {
w := tabwriter.NewWriter(os.Stdout, 5, 0, 3, ' ', 0)
fmt.Fprintf(w, "SELECTOR\tUSERS\tIDENTITIES\n")
for _, mapping := range resp {
first := true
fmt.Fprintf(w, "%s", mapping.Selector)
fmt.Fprintf(w, "\t%d", mapping.Users)
if len(mapping.Identities) == 0 {
fmt.Fprintf(w, "\t\n")
}
for _, idty := range mapping.Identities {
if first {
fmt.Fprintf(w, "\t%d\t\n", idty)
first = false
} else {
fmt.Fprintf(w, "\t\t%d\t\n", idty)
}
}
}
w.Flush()
}
},
}
func init() {
policyCmd.AddCommand(policyCacheGetCmd)
command.AddJSONOutput(policyCacheGetCmd)<|fim▁hole|><|fim▁end|> | } |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>"""Tests for the Volumio integration."""<|fim▁end|> | |
<|file_name|>document.cpp<|end_file_name|><|fim▁begin|>//
// Copyright 2013 Uncodin, 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.<|fim▁hole|>#include "document.h"
namespace Bypass {
Document::Document()
: elements()
{
}
Document::~Document() {
}
void Document::append(const Element& element) {
elements.push_back(Element(element));
}
size_t Document::size() {
return elements.size();
}
Element Document::operator[](size_t i) {
return elements[i];
}
}<|fim▁end|> | // See the License for the specific language governing permissions and
// limitations under the License.
//
|
<|file_name|>message.py<|end_file_name|><|fim▁begin|># Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
# Copyright (c) 2011, 2012 Open Networking Foundation
# Copyright (c) 2012, 2013 Big Switch Networks, Inc.
# See the file LICENSE.pyloxi which should have been included in the source distribution
# Automatically generated by LOXI from template module.py
# Do not modify
import struct
import loxi
import util
import loxi.generic_util
import sys
ofp = sys.modules['loxi.of10']
class message(loxi.OFObject):
subtypes = {}
version = 1
def __init__(self, type=None, xid=None):
if type != None:
self.type = type
else:
self.type = 0
if xid != None:
self.xid = xid
else:
self.xid = None
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
subtype, = reader.peek('B', 1)
subclass = message.subtypes.get(subtype)
if subclass:
return subclass.unpack(reader)
obj = message()
_version = reader.read("!B")[0]
assert(_version == 1)
obj.type = reader.read("!B")[0]
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.type != other.type: return False
if self.xid != other.xid: return False
return True
def pretty_print(self, q):
q.text("message {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.breakable()
q.text('}')
class stats_reply(message):
subtypes = {}
version = 1
type = 17
def __init__(self, xid=None, stats_type=None, flags=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if stats_type != None:
self.stats_type = stats_type
else:
self.stats_type = 0
if flags != None:
self.flags = flags
else:
self.flags = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
subtype, = reader.peek('!H', 8)
subclass = stats_reply.subtypes.get(subtype)
if subclass:
return subclass.unpack(reader)
obj = stats_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 17)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.stats_type = reader.read("!H")[0]
obj.flags = reader.read("!H")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.stats_type != other.stats_type: return False
if self.flags != other.flags: return False
return True
def pretty_print(self, q):
q.text("stats_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.breakable()
q.text('}')
message.subtypes[17] = stats_reply
class aggregate_stats_reply(stats_reply):
version = 1
type = 17
stats_type = 2
def __init__(self, xid=None, flags=None, packet_count=None, byte_count=None, flow_count=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if packet_count != None:
self.packet_count = packet_count
else:
self.packet_count = 0
if byte_count != None:
self.byte_count = byte_count
else:
self.byte_count = 0
if flow_count != None:
self.flow_count = flow_count
else:
self.flow_count = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
packed.append(struct.pack("!Q", self.packet_count))
packed.append(struct.pack("!Q", self.byte_count))
packed.append(struct.pack("!L", self.flow_count))
packed.append('\x00' * 4)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = aggregate_stats_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 17)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 2)
obj.flags = reader.read("!H")[0]
obj.packet_count = reader.read("!Q")[0]
obj.byte_count = reader.read("!Q")[0]
obj.flow_count = reader.read("!L")[0]
reader.skip(4)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.packet_count != other.packet_count: return False
if self.byte_count != other.byte_count: return False
if self.flow_count != other.flow_count: return False
return True
def pretty_print(self, q):
q.text("aggregate_stats_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("packet_count = ");
q.text("%#x" % self.packet_count)
q.text(","); q.breakable()
q.text("byte_count = ");
q.text("%#x" % self.byte_count)
q.text(","); q.breakable()
q.text("flow_count = ");
q.text("%#x" % self.flow_count)
q.breakable()
q.text('}')
stats_reply.subtypes[2] = aggregate_stats_reply
class stats_request(message):
subtypes = {}
version = 1
type = 16
def __init__(self, xid=None, stats_type=None, flags=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if stats_type != None:
self.stats_type = stats_type
else:
self.stats_type = 0
if flags != None:
self.flags = flags
else:
self.flags = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
subtype, = reader.peek('!H', 8)
subclass = stats_request.subtypes.get(subtype)
if subclass:
return subclass.unpack(reader)
obj = stats_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 16)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.stats_type = reader.read("!H")[0]
obj.flags = reader.read("!H")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.stats_type != other.stats_type: return False
if self.flags != other.flags: return False
return True
def pretty_print(self, q):
q.text("stats_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.breakable()
q.text('}')
message.subtypes[16] = stats_request
class aggregate_stats_request(stats_request):
version = 1
type = 16
stats_type = 2
def __init__(self, xid=None, flags=None, match=None, table_id=None, out_port=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if match != None:
self.match = match
else:
self.match = ofp.match()
if table_id != None:
self.table_id = table_id
else:
self.table_id = 0
if out_port != None:
self.out_port = out_port
else:
self.out_port = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
packed.append(self.match.pack())
packed.append(struct.pack("!B", self.table_id))
packed.append('\x00' * 1)
packed.append(util.pack_port_no(self.out_port))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = aggregate_stats_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 16)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 2)
obj.flags = reader.read("!H")[0]
obj.match = ofp.match.unpack(reader)
obj.table_id = reader.read("!B")[0]
reader.skip(1)
obj.out_port = util.unpack_port_no(reader)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.match != other.match: return False
if self.table_id != other.table_id: return False
if self.out_port != other.out_port: return False
return True
def pretty_print(self, q):
q.text("aggregate_stats_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("match = ");
q.pp(self.match)
q.text(","); q.breakable()
q.text("table_id = ");
q.text("%#x" % self.table_id)
q.text(","); q.breakable()
q.text("out_port = ");
q.text(util.pretty_port(self.out_port))
q.breakable()
q.text('}')
stats_request.subtypes[2] = aggregate_stats_request
class error_msg(message):
subtypes = {}
version = 1
type = 1
def __init__(self, xid=None, err_type=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if err_type != None:
self.err_type = err_type
else:
self.err_type = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.err_type))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
subtype, = reader.peek('!H', 8)
subclass = error_msg.subtypes.get(subtype)
if subclass:
return subclass.unpack(reader)
obj = error_msg()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 1)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.err_type = reader.read("!H")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.err_type != other.err_type: return False
return True
def pretty_print(self, q):
q.text("error_msg {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.breakable()
q.text('}')
message.subtypes[1] = error_msg
class bad_action_error_msg(error_msg):
version = 1
type = 1
err_type = 2
def __init__(self, xid=None, code=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if code != None:
self.code = code
else:
self.code = 0
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.err_type))
packed.append(struct.pack("!H", self.code))
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bad_action_error_msg()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 1)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_err_type = reader.read("!H")[0]
assert(_err_type == 2)
obj.code = reader.read("!H")[0]
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.code != other.code: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("bad_action_error_msg {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("code = ");
q.text("%#x" % self.code)
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
error_msg.subtypes[2] = bad_action_error_msg
class bad_request_error_msg(error_msg):
version = 1
type = 1
err_type = 1
def __init__(self, xid=None, code=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if code != None:
self.code = code
else:
self.code = 0
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.err_type))
packed.append(struct.pack("!H", self.code))
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bad_request_error_msg()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 1)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_err_type = reader.read("!H")[0]
assert(_err_type == 1)
obj.code = reader.read("!H")[0]
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.code != other.code: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("bad_request_error_msg {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("code = ");
q.text("%#x" % self.code)
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
error_msg.subtypes[1] = bad_request_error_msg
class barrier_reply(message):
version = 1
type = 19
def __init__(self, xid=None):
if xid != None:
self.xid = xid
else:
self.xid = None
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = barrier_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 19)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
return True
def pretty_print(self, q):
q.text("barrier_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.breakable()
q.text('}')
message.subtypes[19] = barrier_reply
class barrier_request(message):
version = 1
type = 18
def __init__(self, xid=None):
if xid != None:
self.xid = xid
else:
self.xid = None
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = barrier_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 18)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
return True
def pretty_print(self, q):
q.text("barrier_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.breakable()
q.text('}')
message.subtypes[18] = barrier_request
class experimenter(message):
subtypes = {}
version = 1
type = 4
def __init__(self, xid=None, experimenter=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if experimenter != None:
self.experimenter = experimenter
else:
self.experimenter = 0
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
subtype, = reader.peek('!L', 8)
subclass = experimenter.subtypes.get(subtype)
if subclass:
return subclass.unpack(reader)
obj = experimenter()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.experimenter = reader.read("!L")[0]
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.experimenter != other.experimenter: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("experimenter {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
message.subtypes[4] = experimenter
class bsn_header(experimenter):
subtypes = {}
version = 1
type = 4
experimenter = 6035143
def __init__(self, xid=None, subtype=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if subtype != None:
self.subtype = subtype
else:
self.subtype = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
subtype, = reader.peek('!L', 12)
subclass = bsn_header.subtypes.get(subtype)
if subclass:
return subclass.unpack(reader)
obj = bsn_header()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
obj.subtype = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.subtype != other.subtype: return False
return True
def pretty_print(self, q):
q.text("bsn_header {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.breakable()
q.text('}')
experimenter.subtypes[6035143] = bsn_header
class bsn_bw_clear_data_reply(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 22
def __init__(self, xid=None, status=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if status != None:
self.status = status
else:
self.status = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.status))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_bw_clear_data_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 22)
obj.status = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.status != other.status: return False
return True
def pretty_print(self, q):
q.text("bsn_bw_clear_data_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("status = ");
q.text("%#x" % self.status)
q.breakable()
q.text('}')
bsn_header.subtypes[22] = bsn_bw_clear_data_reply
class bsn_bw_clear_data_request(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 21
def __init__(self, xid=None):
if xid != None:
self.xid = xid
else:
self.xid = None
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_bw_clear_data_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 21)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
return True
def pretty_print(self, q):
q.text("bsn_bw_clear_data_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.breakable()
q.text('}')
bsn_header.subtypes[21] = bsn_bw_clear_data_request
class bsn_bw_enable_get_reply(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 20
def __init__(self, xid=None, enabled=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if enabled != None:
self.enabled = enabled
else:
self.enabled = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.enabled))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_bw_enable_get_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 20)
obj.enabled = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.enabled != other.enabled: return False
return True
def pretty_print(self, q):
q.text("bsn_bw_enable_get_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("enabled = ");
q.text("%#x" % self.enabled)
q.breakable()
q.text('}')
bsn_header.subtypes[20] = bsn_bw_enable_get_reply
class bsn_bw_enable_get_request(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 19
def __init__(self, xid=None):
if xid != None:
self.xid = xid
else:
self.xid = None
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_bw_enable_get_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 19)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
return True
def pretty_print(self, q):
q.text("bsn_bw_enable_get_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.breakable()
q.text('}')
bsn_header.subtypes[19] = bsn_bw_enable_get_request
class bsn_bw_enable_set_reply(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 23
def __init__(self, xid=None, enable=None, status=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if enable != None:
self.enable = enable
else:
self.enable = 0
if status != None:
self.status = status
else:
self.status = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.enable))
packed.append(struct.pack("!L", self.status))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_bw_enable_set_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 23)
obj.enable = reader.read("!L")[0]
obj.status = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.enable != other.enable: return False
if self.status != other.status: return False
return True
def pretty_print(self, q):
q.text("bsn_bw_enable_set_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("enable = ");
q.text("%#x" % self.enable)
q.text(","); q.breakable()
q.text("status = ");
q.text("%#x" % self.status)
q.breakable()
q.text('}')
bsn_header.subtypes[23] = bsn_bw_enable_set_reply
class bsn_bw_enable_set_request(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 18
def __init__(self, xid=None, enable=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if enable != None:
self.enable = enable
else:
self.enable = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.enable))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_bw_enable_set_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 18)
obj.enable = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.enable != other.enable: return False
return True
def pretty_print(self, q):
q.text("bsn_bw_enable_set_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("enable = ");
q.text("%#x" % self.enable)
q.breakable()
q.text('}')
bsn_header.subtypes[18] = bsn_bw_enable_set_request
class bsn_get_interfaces_reply(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 10
def __init__(self, xid=None, interfaces=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if interfaces != None:
self.interfaces = interfaces
else:
self.interfaces = []
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(loxi.generic_util.pack_list(self.interfaces))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_get_interfaces_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 10)
obj.interfaces = loxi.generic_util.unpack_list(reader, ofp.common.bsn_interface.unpack)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.interfaces != other.interfaces: return False
return True
def pretty_print(self, q):
q.text("bsn_get_interfaces_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("interfaces = ");
q.pp(self.interfaces)
q.breakable()
q.text('}')
bsn_header.subtypes[10] = bsn_get_interfaces_reply
class bsn_get_interfaces_request(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 9
def __init__(self, xid=None):
if xid != None:
self.xid = xid
else:
self.xid = None
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_get_interfaces_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 9)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
return True
def pretty_print(self, q):
q.text("bsn_get_interfaces_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.breakable()
q.text('}')
bsn_header.subtypes[9] = bsn_get_interfaces_request
class bsn_get_ip_mask_reply(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 2
def __init__(self, xid=None, index=None, mask=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if index != None:
self.index = index
else:
self.index = 0
if mask != None:
self.mask = mask
else:
self.mask = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!B", self.index))
packed.append('\x00' * 3)
packed.append(struct.pack("!L", self.mask))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_get_ip_mask_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 2)
obj.index = reader.read("!B")[0]
reader.skip(3)
obj.mask = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.index != other.index: return False
if self.mask != other.mask: return False
return True
def pretty_print(self, q):
q.text("bsn_get_ip_mask_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("index = ");
q.text("%#x" % self.index)
q.text(","); q.breakable()
q.text("mask = ");
q.text("%#x" % self.mask)
q.breakable()
q.text('}')
bsn_header.subtypes[2] = bsn_get_ip_mask_reply
class bsn_get_ip_mask_request(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 1
def __init__(self, xid=None, index=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if index != None:
self.index = index
else:
self.index = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!B", self.index))
packed.append('\x00' * 7)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_get_ip_mask_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 1)
obj.index = reader.read("!B")[0]
reader.skip(7)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.index != other.index: return False
return True
def pretty_print(self, q):
q.text("bsn_get_ip_mask_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("index = ");
q.text("%#x" % self.index)
q.breakable()
q.text('}')
bsn_header.subtypes[1] = bsn_get_ip_mask_request
class bsn_get_l2_table_reply(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 14
def __init__(self, xid=None, l2_table_enable=None, l2_table_priority=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if l2_table_enable != None:
self.l2_table_enable = l2_table_enable
else:
self.l2_table_enable = 0
if l2_table_priority != None:
self.l2_table_priority = l2_table_priority
else:
self.l2_table_priority = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!B", self.l2_table_enable))
packed.append('\x00' * 1)
packed.append(struct.pack("!H", self.l2_table_priority))
packed.append('\x00' * 4)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_get_l2_table_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 14)
obj.l2_table_enable = reader.read("!B")[0]
reader.skip(1)
obj.l2_table_priority = reader.read("!H")[0]
reader.skip(4)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.l2_table_enable != other.l2_table_enable: return False
if self.l2_table_priority != other.l2_table_priority: return False
return True
def pretty_print(self, q):
q.text("bsn_get_l2_table_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("l2_table_enable = ");
q.text("%#x" % self.l2_table_enable)
q.text(","); q.breakable()
q.text("l2_table_priority = ");
q.text("%#x" % self.l2_table_priority)
q.breakable()
q.text('}')
bsn_header.subtypes[14] = bsn_get_l2_table_reply
class bsn_get_l2_table_request(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 13
def __init__(self, xid=None):
if xid != None:
self.xid = xid
else:
self.xid = None
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_get_l2_table_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 13)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
return True
def pretty_print(self, q):
q.text("bsn_get_l2_table_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.breakable()
q.text('}')
bsn_header.subtypes[13] = bsn_get_l2_table_request
class bsn_get_mirroring_reply(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 5
def __init__(self, xid=None, report_mirror_ports=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if report_mirror_ports != None:
self.report_mirror_ports = report_mirror_ports
else:
self.report_mirror_ports = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!B", self.report_mirror_ports))
packed.append('\x00' * 3)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_get_mirroring_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 5)
obj.report_mirror_ports = reader.read("!B")[0]
reader.skip(3)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.report_mirror_ports != other.report_mirror_ports: return False
return True
def pretty_print(self, q):
q.text("bsn_get_mirroring_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("report_mirror_ports = ");
q.text("%#x" % self.report_mirror_ports)
q.breakable()
q.text('}')
bsn_header.subtypes[5] = bsn_get_mirroring_reply
class bsn_get_mirroring_request(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 4
def __init__(self, xid=None, report_mirror_ports=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if report_mirror_ports != None:
self.report_mirror_ports = report_mirror_ports
else:
self.report_mirror_ports = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!B", self.report_mirror_ports))
packed.append('\x00' * 3)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_get_mirroring_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 4)
obj.report_mirror_ports = reader.read("!B")[0]
reader.skip(3)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.report_mirror_ports != other.report_mirror_ports: return False
return True
def pretty_print(self, q):
q.text("bsn_get_mirroring_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("report_mirror_ports = ");
q.text("%#x" % self.report_mirror_ports)
q.breakable()
q.text('}')
bsn_header.subtypes[4] = bsn_get_mirroring_request
class bsn_hybrid_get_reply(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 28
def __init__(self, xid=None, hybrid_enable=None, hybrid_version=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if hybrid_enable != None:
self.hybrid_enable = hybrid_enable
else:
self.hybrid_enable = 0
if hybrid_version != None:
self.hybrid_version = hybrid_version
else:
self.hybrid_version = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!B", self.hybrid_enable))
packed.append('\x00' * 1)
packed.append(struct.pack("!H", self.hybrid_version))
packed.append('\x00' * 4)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_hybrid_get_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 28)
obj.hybrid_enable = reader.read("!B")[0]
reader.skip(1)
obj.hybrid_version = reader.read("!H")[0]
reader.skip(4)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.hybrid_enable != other.hybrid_enable: return False
if self.hybrid_version != other.hybrid_version: return False
return True
def pretty_print(self, q):
q.text("bsn_hybrid_get_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("hybrid_enable = ");
q.text("%#x" % self.hybrid_enable)
q.text(","); q.breakable()
q.text("hybrid_version = ");
q.text("%#x" % self.hybrid_version)
q.breakable()
q.text('}')
bsn_header.subtypes[28] = bsn_hybrid_get_reply
class bsn_hybrid_get_request(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 27
def __init__(self, xid=None):
if xid != None:
self.xid = xid
else:
self.xid = None
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_hybrid_get_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 27)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
return True
def pretty_print(self, q):
q.text("bsn_hybrid_get_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.breakable()
q.text('}')
bsn_header.subtypes[27] = bsn_hybrid_get_request
class bsn_pdu_rx_reply(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 34
def __init__(self, xid=None, status=None, port_no=None, slot_num=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if status != None:
self.status = status
else:
self.status = 0
if port_no != None:
self.port_no = port_no
else:
self.port_no = 0
if slot_num != None:
self.slot_num = slot_num
else:
self.slot_num = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.status))
packed.append(util.pack_port_no(self.port_no))
packed.append(struct.pack("!B", self.slot_num))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_pdu_rx_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 34)
obj.status = reader.read("!L")[0]
obj.port_no = util.unpack_port_no(reader)
obj.slot_num = reader.read("!B")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.status != other.status: return False
if self.port_no != other.port_no: return False
if self.slot_num != other.slot_num: return False
return True
def pretty_print(self, q):
q.text("bsn_pdu_rx_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("status = ");
q.text("%#x" % self.status)
q.text(","); q.breakable()
q.text("port_no = ");
q.text(util.pretty_port(self.port_no))
q.text(","); q.breakable()
q.text("slot_num = ");
q.text("%#x" % self.slot_num)
q.breakable()
q.text('}')
bsn_header.subtypes[34] = bsn_pdu_rx_reply
class bsn_pdu_rx_request(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 33
def __init__(self, xid=None, timeout_ms=None, port_no=None, slot_num=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if timeout_ms != None:
self.timeout_ms = timeout_ms
else:
self.timeout_ms = 0
if port_no != None:
self.port_no = port_no
else:
self.port_no = 0
if slot_num != None:
self.slot_num = slot_num
else:
self.slot_num = 0
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.timeout_ms))
packed.append(util.pack_port_no(self.port_no))
packed.append(struct.pack("!B", self.slot_num))
packed.append('\x00' * 3)
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_pdu_rx_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 33)
obj.timeout_ms = reader.read("!L")[0]
obj.port_no = util.unpack_port_no(reader)
obj.slot_num = reader.read("!B")[0]
reader.skip(3)
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.timeout_ms != other.timeout_ms: return False
if self.port_no != other.port_no: return False
if self.slot_num != other.slot_num: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("bsn_pdu_rx_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("timeout_ms = ");
q.text("%#x" % self.timeout_ms)
q.text(","); q.breakable()
q.text("port_no = ");
q.text(util.pretty_port(self.port_no))
q.text(","); q.breakable()
q.text("slot_num = ");
q.text("%#x" % self.slot_num)
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
bsn_header.subtypes[33] = bsn_pdu_rx_request
class bsn_pdu_rx_timeout(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 35
def __init__(self, xid=None, port_no=None, slot_num=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if port_no != None:
self.port_no = port_no
else:
self.port_no = 0
if slot_num != None:
self.slot_num = slot_num
else:
self.slot_num = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(util.pack_port_no(self.port_no))
packed.append(struct.pack("!B", self.slot_num))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_pdu_rx_timeout()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 35)
obj.port_no = util.unpack_port_no(reader)
obj.slot_num = reader.read("!B")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.port_no != other.port_no: return False
if self.slot_num != other.slot_num: return False
return True
def pretty_print(self, q):
q.text("bsn_pdu_rx_timeout {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("port_no = ");
q.text(util.pretty_port(self.port_no))
q.text(","); q.breakable()
q.text("slot_num = ");
q.text("%#x" % self.slot_num)
q.breakable()
q.text('}')
bsn_header.subtypes[35] = bsn_pdu_rx_timeout
class bsn_pdu_tx_reply(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 32
def __init__(self, xid=None, status=None, port_no=None, slot_num=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if status != None:
self.status = status
else:
self.status = 0
if port_no != None:
self.port_no = port_no
else:
self.port_no = 0
if slot_num != None:
self.slot_num = slot_num
else:
self.slot_num = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.status))
packed.append(util.pack_port_no(self.port_no))
packed.append(struct.pack("!B", self.slot_num))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_pdu_tx_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 32)
obj.status = reader.read("!L")[0]
obj.port_no = util.unpack_port_no(reader)
obj.slot_num = reader.read("!B")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.status != other.status: return False
if self.port_no != other.port_no: return False
if self.slot_num != other.slot_num: return False
return True
def pretty_print(self, q):
q.text("bsn_pdu_tx_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("status = ");
q.text("%#x" % self.status)
q.text(","); q.breakable()
q.text("port_no = ");
q.text(util.pretty_port(self.port_no))
q.text(","); q.breakable()
q.text("slot_num = ");
q.text("%#x" % self.slot_num)
q.breakable()
q.text('}')
bsn_header.subtypes[32] = bsn_pdu_tx_reply
class bsn_pdu_tx_request(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 31
def __init__(self, xid=None, tx_interval_ms=None, port_no=None, slot_num=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if tx_interval_ms != None:
self.tx_interval_ms = tx_interval_ms
else:
self.tx_interval_ms = 0
if port_no != None:
self.port_no = port_no
else:
self.port_no = 0
if slot_num != None:
self.slot_num = slot_num
else:
self.slot_num = 0
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.tx_interval_ms))
packed.append(util.pack_port_no(self.port_no))
packed.append(struct.pack("!B", self.slot_num))
packed.append('\x00' * 3)
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_pdu_tx_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 31)
obj.tx_interval_ms = reader.read("!L")[0]
obj.port_no = util.unpack_port_no(reader)
obj.slot_num = reader.read("!B")[0]
reader.skip(3)
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.tx_interval_ms != other.tx_interval_ms: return False
if self.port_no != other.port_no: return False
if self.slot_num != other.slot_num: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("bsn_pdu_tx_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("tx_interval_ms = ");
q.text("%#x" % self.tx_interval_ms)
q.text(","); q.breakable()
q.text("port_no = ");
q.text(util.pretty_port(self.port_no))
q.text(","); q.breakable()
q.text("slot_num = ");
q.text("%#x" % self.slot_num)
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
bsn_header.subtypes[31] = bsn_pdu_tx_request
class bsn_set_ip_mask(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 0
def __init__(self, xid=None, index=None, mask=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if index != None:
self.index = index
else:
self.index = 0
if mask != None:
self.mask = mask
else:
self.mask = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!B", self.index))
packed.append('\x00' * 3)
packed.append(struct.pack("!L", self.mask))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_set_ip_mask()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 0)
obj.index = reader.read("!B")[0]
reader.skip(3)
obj.mask = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.index != other.index: return False
if self.mask != other.mask: return False
return True
def pretty_print(self, q):
q.text("bsn_set_ip_mask {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("index = ");
q.text("%#x" % self.index)
q.text(","); q.breakable()
q.text("mask = ");
q.text("%#x" % self.mask)
q.breakable()
q.text('}')
bsn_header.subtypes[0] = bsn_set_ip_mask
class bsn_set_l2_table_reply(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 24
def __init__(self, xid=None, l2_table_enable=None, l2_table_priority=None, status=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if l2_table_enable != None:
self.l2_table_enable = l2_table_enable
else:
self.l2_table_enable = 0
if l2_table_priority != None:
self.l2_table_priority = l2_table_priority
else:
self.l2_table_priority = 0
if status != None:
self.status = status
else:
self.status = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!B", self.l2_table_enable))
packed.append('\x00' * 1)
packed.append(struct.pack("!H", self.l2_table_priority))
packed.append(struct.pack("!L", self.status))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_set_l2_table_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 24)
obj.l2_table_enable = reader.read("!B")[0]
reader.skip(1)
obj.l2_table_priority = reader.read("!H")[0]
obj.status = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.l2_table_enable != other.l2_table_enable: return False
if self.l2_table_priority != other.l2_table_priority: return False
if self.status != other.status: return False
return True
def pretty_print(self, q):
q.text("bsn_set_l2_table_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("l2_table_enable = ");
q.text("%#x" % self.l2_table_enable)
q.text(","); q.breakable()
q.text("l2_table_priority = ");
q.text("%#x" % self.l2_table_priority)
q.text(","); q.breakable()
q.text("status = ");
q.text("%#x" % self.status)
q.breakable()
q.text('}')
bsn_header.subtypes[24] = bsn_set_l2_table_reply
class bsn_set_l2_table_request(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 12
def __init__(self, xid=None, l2_table_enable=None, l2_table_priority=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if l2_table_enable != None:
self.l2_table_enable = l2_table_enable
else:
self.l2_table_enable = 0
if l2_table_priority != None:
self.l2_table_priority = l2_table_priority
else:
self.l2_table_priority = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!B", self.l2_table_enable))
packed.append('\x00' * 1)
packed.append(struct.pack("!H", self.l2_table_priority))
packed.append('\x00' * 4)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_set_l2_table_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 12)
obj.l2_table_enable = reader.read("!B")[0]
reader.skip(1)
obj.l2_table_priority = reader.read("!H")[0]
reader.skip(4)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.l2_table_enable != other.l2_table_enable: return False
if self.l2_table_priority != other.l2_table_priority: return False
return True
def pretty_print(self, q):
q.text("bsn_set_l2_table_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("l2_table_enable = ");
q.text("%#x" % self.l2_table_enable)
q.text(","); q.breakable()
q.text("l2_table_priority = ");
q.text("%#x" % self.l2_table_priority)
q.breakable()
q.text('}')
bsn_header.subtypes[12] = bsn_set_l2_table_request
class bsn_set_mirroring(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 3
def __init__(self, xid=None, report_mirror_ports=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if report_mirror_ports != None:
self.report_mirror_ports = report_mirror_ports
else:
self.report_mirror_ports = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!B", self.report_mirror_ports))
packed.append('\x00' * 3)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_set_mirroring()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 3)
obj.report_mirror_ports = reader.read("!B")[0]
reader.skip(3)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.report_mirror_ports != other.report_mirror_ports: return False
return True
def pretty_print(self, q):
q.text("bsn_set_mirroring {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("report_mirror_ports = ");
q.text("%#x" % self.report_mirror_ports)
q.breakable()
q.text('}')
bsn_header.subtypes[3] = bsn_set_mirroring
class bsn_set_pktin_suppression_reply(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 25
def __init__(self, xid=None, status=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if status != None:
self.status = status
else:
self.status = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.status))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_set_pktin_suppression_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 25)
obj.status = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.status != other.status: return False
return True
def pretty_print(self, q):
q.text("bsn_set_pktin_suppression_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("status = ");
q.text("%#x" % self.status)
q.breakable()
q.text('}')
bsn_header.subtypes[25] = bsn_set_pktin_suppression_reply
class bsn_set_pktin_suppression_request(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 11
def __init__(self, xid=None, enabled=None, idle_timeout=None, hard_timeout=None, priority=None, cookie=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if enabled != None:
self.enabled = enabled
else:
self.enabled = 0
if idle_timeout != None:
self.idle_timeout = idle_timeout
else:
self.idle_timeout = 0
if hard_timeout != None:
self.hard_timeout = hard_timeout
else:
self.hard_timeout = 0
if priority != None:
self.priority = priority
else:
self.priority = 0
if cookie != None:
self.cookie = cookie
else:
self.cookie = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!B", self.enabled))
packed.append('\x00' * 1)
packed.append(struct.pack("!H", self.idle_timeout))
packed.append(struct.pack("!H", self.hard_timeout))
packed.append(struct.pack("!H", self.priority))
packed.append(struct.pack("!Q", self.cookie))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_set_pktin_suppression_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 11)
obj.enabled = reader.read("!B")[0]
reader.skip(1)
obj.idle_timeout = reader.read("!H")[0]
obj.hard_timeout = reader.read("!H")[0]
obj.priority = reader.read("!H")[0]
obj.cookie = reader.read("!Q")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.enabled != other.enabled: return False
if self.idle_timeout != other.idle_timeout: return False
if self.hard_timeout != other.hard_timeout: return False
if self.priority != other.priority: return False
if self.cookie != other.cookie: return False
return True
def pretty_print(self, q):
q.text("bsn_set_pktin_suppression_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("enabled = ");
q.text("%#x" % self.enabled)
q.text(","); q.breakable()
q.text("idle_timeout = ");
q.text("%#x" % self.idle_timeout)
q.text(","); q.breakable()
q.text("hard_timeout = ");
q.text("%#x" % self.hard_timeout)
q.text(","); q.breakable()
q.text("priority = ");
q.text("%#x" % self.priority)
q.text(","); q.breakable()
q.text("cookie = ");
q.text("%#x" % self.cookie)
q.breakable()
q.text('}')
bsn_header.subtypes[11] = bsn_set_pktin_suppression_request
class bsn_shell_command(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 6
def __init__(self, xid=None, service=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if service != None:
self.service = service
else:
self.service = 0
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.service))
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_shell_command()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 6)
obj.service = reader.read("!L")[0]
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.service != other.service: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("bsn_shell_command {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("service = ");
q.text("%#x" % self.service)
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
bsn_header.subtypes[6] = bsn_shell_command
class bsn_shell_output(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 7
def __init__(self, xid=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_shell_output()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 7)
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("bsn_shell_output {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
bsn_header.subtypes[7] = bsn_shell_output
class bsn_shell_status(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 8
def __init__(self, xid=None, status=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if status != None:
self.status = status
else:
self.status = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.status))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_shell_status()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 8)
obj.status = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.status != other.status: return False
return True
def pretty_print(self, q):
q.text("bsn_shell_status {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("status = ");
q.text("%#x" % self.status)
q.breakable()
q.text('}')
bsn_header.subtypes[8] = bsn_shell_status
class experimenter_stats_reply(stats_reply):
subtypes = {}
version = 1
type = 17
stats_type = 65535
def __init__(self, xid=None, flags=None, experimenter=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if experimenter != None:
self.experimenter = experimenter
else:
self.experimenter = 0
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
packed.append(struct.pack("!L", self.experimenter))
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
subtype, = reader.peek('!L', 12)
subclass = experimenter_stats_reply.subtypes.get(subtype)
if subclass:
return subclass.unpack(reader)
obj = experimenter_stats_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 17)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 65535)
obj.flags = reader.read("!H")[0]
obj.experimenter = reader.read("!L")[0]
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.experimenter != other.experimenter: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("experimenter_stats_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
stats_reply.subtypes[65535] = experimenter_stats_reply
class bsn_stats_reply(experimenter_stats_reply):
subtypes = {}
version = 1
type = 19
stats_type = 65535
experimenter = 6035143
def __init__(self, xid=None, flags=None, subtype=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if subtype != None:
self.subtype = subtype
else:
self.subtype = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
packed.append('\x00' * 4)
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
subtype, = reader.peek('!L', 20)
subclass = bsn_stats_reply.subtypes.get(subtype)
if subclass:
return subclass.unpack(reader)
obj = bsn_stats_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 19)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 65535)
obj.flags = reader.read("!H")[0]
reader.skip(4)
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
obj.subtype = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.subtype != other.subtype: return False
return True
def pretty_print(self, q):
q.text("bsn_stats_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.breakable()
q.text('}')
experimenter_stats_reply.subtypes[6035143] = bsn_stats_reply
class experimenter_stats_request(stats_request):
subtypes = {}
version = 1
type = 16
stats_type = 65535
def __init__(self, xid=None, flags=None, experimenter=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if experimenter != None:
self.experimenter = experimenter
else:
self.experimenter = 0
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
packed.append(struct.pack("!L", self.experimenter))
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
subtype, = reader.peek('!L', 12)
subclass = experimenter_stats_request.subtypes.get(subtype)
if subclass:
return subclass.unpack(reader)
obj = experimenter_stats_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 16)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 65535)
obj.flags = reader.read("!H")[0]
obj.experimenter = reader.read("!L")[0]
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.experimenter != other.experimenter: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("experimenter_stats_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
stats_request.subtypes[65535] = experimenter_stats_request
class bsn_stats_request(experimenter_stats_request):
subtypes = {}
version = 1
type = 18
stats_type = 65535
experimenter = 6035143
def __init__(self, xid=None, flags=None, subtype=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if subtype != None:
self.subtype = subtype
else:
self.subtype = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
packed.append('\x00' * 4)
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
subtype, = reader.peek('!L', 20)
subclass = bsn_stats_request.subtypes.get(subtype)
if subclass:
return subclass.unpack(reader)
obj = bsn_stats_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 18)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 65535)
obj.flags = reader.read("!H")[0]
reader.skip(4)
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
obj.subtype = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.subtype != other.subtype: return False
return True
def pretty_print(self, q):
q.text("bsn_stats_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.breakable()
q.text('}')
experimenter_stats_request.subtypes[6035143] = bsn_stats_request
class bsn_virtual_port_create_reply(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 16
def __init__(self, xid=None, status=None, vport_no=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if status != None:
self.status = status
else:
self.status = 0
if vport_no != None:
self.vport_no = vport_no
else:
self.vport_no = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.status))
packed.append(struct.pack("!L", self.vport_no))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_virtual_port_create_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 16)
obj.status = reader.read("!L")[0]
obj.vport_no = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.status != other.status: return False
if self.vport_no != other.vport_no: return False
return True
def pretty_print(self, q):
q.text("bsn_virtual_port_create_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("status = ");
q.text("%#x" % self.status)
q.text(","); q.breakable()
q.text("vport_no = ");
q.text("%#x" % self.vport_no)
q.breakable()
q.text('}')
bsn_header.subtypes[16] = bsn_virtual_port_create_reply
class bsn_virtual_port_create_request(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 15
def __init__(self, xid=None, vport=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if vport != None:
self.vport = vport
else:
self.vport = ofp.bsn_vport()
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(self.vport.pack())
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_virtual_port_create_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 15)
obj.vport = ofp.bsn_vport.unpack(reader)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.vport != other.vport: return False
return True
def pretty_print(self, q):
q.text("bsn_virtual_port_create_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("vport = ");
q.pp(self.vport)
q.breakable()
q.text('}')
bsn_header.subtypes[15] = bsn_virtual_port_create_request
class bsn_virtual_port_remove_reply(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 26
def __init__(self, xid=None, status=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if status != None:
self.status = status
else:
self.status = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.status))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_virtual_port_remove_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 26)
obj.status = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.status != other.status: return False
return True
def pretty_print(self, q):
q.text("bsn_virtual_port_remove_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("status = ");
q.text("%#x" % self.status)
q.breakable()
q.text('}')
bsn_header.subtypes[26] = bsn_virtual_port_remove_reply
class bsn_virtual_port_remove_request(bsn_header):
version = 1
type = 4
experimenter = 6035143
subtype = 17
def __init__(self, xid=None, vport_no=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if vport_no != None:
self.vport_no = vport_no
else:
self.vport_no = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.vport_no))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = bsn_virtual_port_remove_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 6035143)
_subtype = reader.read("!L")[0]
assert(_subtype == 17)
obj.vport_no = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.vport_no != other.vport_no: return False
return True
def pretty_print(self, q):
q.text("bsn_virtual_port_remove_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("vport_no = ");
q.text("%#x" % self.vport_no)
q.breakable()
q.text('}')
bsn_header.subtypes[17] = bsn_virtual_port_remove_request
class desc_stats_reply(stats_reply):
version = 1
type = 17
stats_type = 0
def __init__(self, xid=None, flags=None, mfr_desc=None, hw_desc=None, sw_desc=None, serial_num=None, dp_desc=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if mfr_desc != None:
self.mfr_desc = mfr_desc
else:
self.mfr_desc = ""
if hw_desc != None:
self.hw_desc = hw_desc
else:
self.hw_desc = ""
if sw_desc != None:
self.sw_desc = sw_desc
else:
self.sw_desc = ""
if serial_num != None:
self.serial_num = serial_num
else:
self.serial_num = ""
if dp_desc != None:
self.dp_desc = dp_desc
else:
self.dp_desc = ""
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
packed.append(struct.pack("!256s", self.mfr_desc))
packed.append(struct.pack("!256s", self.hw_desc))
packed.append(struct.pack("!256s", self.sw_desc))
packed.append(struct.pack("!32s", self.serial_num))
packed.append(struct.pack("!256s", self.dp_desc))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = desc_stats_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 17)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 0)
obj.flags = reader.read("!H")[0]
obj.mfr_desc = reader.read("!256s")[0].rstrip("\x00")
obj.hw_desc = reader.read("!256s")[0].rstrip("\x00")
obj.sw_desc = reader.read("!256s")[0].rstrip("\x00")
obj.serial_num = reader.read("!32s")[0].rstrip("\x00")
obj.dp_desc = reader.read("!256s")[0].rstrip("\x00")
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.mfr_desc != other.mfr_desc: return False
if self.hw_desc != other.hw_desc: return False
if self.sw_desc != other.sw_desc: return False
if self.serial_num != other.serial_num: return False
if self.dp_desc != other.dp_desc: return False
return True
def pretty_print(self, q):
q.text("desc_stats_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("mfr_desc = ");
q.pp(self.mfr_desc)
q.text(","); q.breakable()
q.text("hw_desc = ");
q.pp(self.hw_desc)
q.text(","); q.breakable()
q.text("sw_desc = ");
q.pp(self.sw_desc)
q.text(","); q.breakable()
q.text("serial_num = ");
q.pp(self.serial_num)
q.text(","); q.breakable()
q.text("dp_desc = ");
q.pp(self.dp_desc)
q.breakable()
q.text('}')
stats_reply.subtypes[0] = desc_stats_reply
class desc_stats_request(stats_request):
version = 1
type = 16
stats_type = 0
def __init__(self, xid=None, flags=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = desc_stats_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 16)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 0)
obj.flags = reader.read("!H")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
return True
def pretty_print(self, q):
q.text("desc_stats_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.breakable()
q.text('}')
stats_request.subtypes[0] = desc_stats_request
class echo_reply(message):
version = 1
type = 3
def __init__(self, xid=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = echo_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 3)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("echo_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
message.subtypes[3] = echo_reply
class echo_request(message):
version = 1
type = 2
def __init__(self, xid=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = echo_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 2)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("echo_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
message.subtypes[2] = echo_request
class features_reply(message):
version = 1
type = 6
def __init__(self, xid=None, datapath_id=None, n_buffers=None, n_tables=None, capabilities=None, actions=None, ports=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if datapath_id != None:
self.datapath_id = datapath_id
else:
self.datapath_id = 0
if n_buffers != None:
self.n_buffers = n_buffers
else:
self.n_buffers = 0
if n_tables != None:
self.n_tables = n_tables
else:
self.n_tables = 0
if capabilities != None:
self.capabilities = capabilities
else:
self.capabilities = 0
if actions != None:
self.actions = actions
else:
self.actions = 0
if ports != None:
self.ports = ports
else:
self.ports = []
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!Q", self.datapath_id))
packed.append(struct.pack("!L", self.n_buffers))
packed.append(struct.pack("!B", self.n_tables))
packed.append('\x00' * 3)
packed.append(struct.pack("!L", self.capabilities))
packed.append(struct.pack("!L", self.actions))
packed.append(loxi.generic_util.pack_list(self.ports))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = features_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 6)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.datapath_id = reader.read("!Q")[0]
obj.n_buffers = reader.read("!L")[0]
obj.n_tables = reader.read("!B")[0]
reader.skip(3)
obj.capabilities = reader.read("!L")[0]
obj.actions = reader.read("!L")[0]
obj.ports = loxi.generic_util.unpack_list(reader, ofp.common.port_desc.unpack)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.datapath_id != other.datapath_id: return False
if self.n_buffers != other.n_buffers: return False
if self.n_tables != other.n_tables: return False
if self.capabilities != other.capabilities: return False
if self.actions != other.actions: return False
if self.ports != other.ports: return False
return True
def pretty_print(self, q):
q.text("features_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("datapath_id = ");
q.text("%#x" % self.datapath_id)
q.text(","); q.breakable()
q.text("n_buffers = ");
q.text("%#x" % self.n_buffers)
q.text(","); q.breakable()
q.text("n_tables = ");
q.text("%#x" % self.n_tables)
q.text(","); q.breakable()
q.text("capabilities = ");
q.text("%#x" % self.capabilities)
q.text(","); q.breakable()
q.text("actions = ");
q.text("%#x" % self.actions)
q.text(","); q.breakable()
q.text("ports = ");
q.pp(self.ports)
q.breakable()
q.text('}')
message.subtypes[6] = features_reply
class features_request(message):
version = 1
type = 5
def __init__(self, xid=None):
if xid != None:
self.xid = xid
else:
self.xid = None
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = features_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 5)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
return True
def pretty_print(self, q):
q.text("features_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.breakable()
q.text('}')
message.subtypes[5] = features_request
class flow_mod(message):
subtypes = {}
version = 1
type = 14
def __init__(self, xid=None, match=None, cookie=None, _command=None, idle_timeout=None, hard_timeout=None, priority=None, buffer_id=None, out_port=None, flags=None, actions=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if match != None:
self.match = match
else:
self.match = ofp.match()
if cookie != None:
self.cookie = cookie
else:
self.cookie = 0
if _command != None:
self._command = _command
else:
self._command = 0
if idle_timeout != None:
self.idle_timeout = idle_timeout
else:
self.idle_timeout = 0
if hard_timeout != None:
self.hard_timeout = hard_timeout
else:
self.hard_timeout = 0
if priority != None:
self.priority = priority
else:
self.priority = 0
if buffer_id != None:
self.buffer_id = buffer_id
else:
self.buffer_id = 0
if out_port != None:
self.out_port = out_port
else:
self.out_port = 0
if flags != None:
self.flags = flags
else:
self.flags = 0
if actions != None:
self.actions = actions
else:
self.actions = []
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(self.match.pack())
packed.append(struct.pack("!Q", self.cookie))
packed.append(util.pack_fm_cmd(self._command))
packed.append(struct.pack("!H", self.idle_timeout))
packed.append(struct.pack("!H", self.hard_timeout))
packed.append(struct.pack("!H", self.priority))
packed.append(struct.pack("!L", self.buffer_id))
packed.append(util.pack_port_no(self.out_port))
packed.append(struct.pack("!H", self.flags))
packed.append(loxi.generic_util.pack_list(self.actions))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
subtype, = reader.peek('!H', 56)
subclass = flow_mod.subtypes.get(subtype)
if subclass:
return subclass.unpack(reader)
obj = flow_mod()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 14)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.match = ofp.match.unpack(reader)
obj.cookie = reader.read("!Q")[0]
obj._command = util.unpack_fm_cmd(reader)
obj.idle_timeout = reader.read("!H")[0]
obj.hard_timeout = reader.read("!H")[0]
obj.priority = reader.read("!H")[0]
obj.buffer_id = reader.read("!L")[0]
obj.out_port = util.unpack_port_no(reader)
obj.flags = reader.read("!H")[0]
obj.actions = loxi.generic_util.unpack_list(reader, ofp.action.action.unpack)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.match != other.match: return False
if self.cookie != other.cookie: return False
if self._command != other._command: return False
if self.idle_timeout != other.idle_timeout: return False
if self.hard_timeout != other.hard_timeout: return False
if self.priority != other.priority: return False
if self.buffer_id != other.buffer_id: return False
if self.out_port != other.out_port: return False
if self.flags != other.flags: return False
if self.actions != other.actions: return False
return True
def pretty_print(self, q):
q.text("flow_mod {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("match = ");
q.pp(self.match)
q.text(","); q.breakable()
q.text("cookie = ");
q.text("%#x" % self.cookie)
q.text(","); q.breakable()
q.text("idle_timeout = ");
q.text("%#x" % self.idle_timeout)
q.text(","); q.breakable()
q.text("hard_timeout = ");
q.text("%#x" % self.hard_timeout)
q.text(","); q.breakable()
q.text("priority = ");
q.text("%#x" % self.priority)
q.text(","); q.breakable()
q.text("buffer_id = ");
q.text("%#x" % self.buffer_id)
q.text(","); q.breakable()
q.text("out_port = ");
q.text(util.pretty_port(self.out_port))
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("actions = ");
q.pp(self.actions)
q.breakable()
q.text('}')
message.subtypes[14] = flow_mod
class flow_add(flow_mod):
version = 1
type = 14
_command = 0
def __init__(self, xid=None, match=None, cookie=None, idle_timeout=None, hard_timeout=None, priority=None, buffer_id=None, out_port=None, flags=None, actions=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if match != None:
self.match = match
else:
self.match = ofp.match()
if cookie != None:
self.cookie = cookie
else:
self.cookie = 0
if idle_timeout != None:
self.idle_timeout = idle_timeout
else:
self.idle_timeout = 0
if hard_timeout != None:
self.hard_timeout = hard_timeout
else:
self.hard_timeout = 0
if priority != None:
self.priority = priority
else:
self.priority = 0
if buffer_id != None:
self.buffer_id = buffer_id
else:
self.buffer_id = 0
if out_port != None:
self.out_port = out_port
else:
self.out_port = 0
if flags != None:
self.flags = flags
else:
self.flags = 0
if actions != None:
self.actions = actions
else:
self.actions = []
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(self.match.pack())
packed.append(struct.pack("!Q", self.cookie))
packed.append(util.pack_fm_cmd(self._command))
packed.append(struct.pack("!H", self.idle_timeout))
packed.append(struct.pack("!H", self.hard_timeout))
packed.append(struct.pack("!H", self.priority))
packed.append(struct.pack("!L", self.buffer_id))
packed.append(util.pack_port_no(self.out_port))
packed.append(struct.pack("!H", self.flags))
packed.append(loxi.generic_util.pack_list(self.actions))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = flow_add()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 14)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.match = ofp.match.unpack(reader)
obj.cookie = reader.read("!Q")[0]
__command = util.unpack_fm_cmd(reader)
assert(__command == 0)
obj.idle_timeout = reader.read("!H")[0]
obj.hard_timeout = reader.read("!H")[0]
obj.priority = reader.read("!H")[0]
obj.buffer_id = reader.read("!L")[0]
obj.out_port = util.unpack_port_no(reader)
obj.flags = reader.read("!H")[0]
obj.actions = loxi.generic_util.unpack_list(reader, ofp.action.action.unpack)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.match != other.match: return False
if self.cookie != other.cookie: return False
if self.idle_timeout != other.idle_timeout: return False
if self.hard_timeout != other.hard_timeout: return False
if self.priority != other.priority: return False
if self.buffer_id != other.buffer_id: return False
if self.out_port != other.out_port: return False
if self.flags != other.flags: return False
if self.actions != other.actions: return False
return True
def pretty_print(self, q):
q.text("flow_add {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("match = ");
q.pp(self.match)
q.text(","); q.breakable()
q.text("cookie = ");
q.text("%#x" % self.cookie)
q.text(","); q.breakable()
q.text("idle_timeout = ");
q.text("%#x" % self.idle_timeout)
q.text(","); q.breakable()
q.text("hard_timeout = ");
q.text("%#x" % self.hard_timeout)
q.text(","); q.breakable()
q.text("priority = ");
q.text("%#x" % self.priority)
q.text(","); q.breakable()
q.text("buffer_id = ");
q.text("%#x" % self.buffer_id)
q.text(","); q.breakable()
q.text("out_port = ");
q.text(util.pretty_port(self.out_port))
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("actions = ");
q.pp(self.actions)
q.breakable()
q.text('}')
flow_mod.subtypes[0] = flow_add
class flow_delete(flow_mod):
version = 1
type = 14
_command = 3
def __init__(self, xid=None, match=None, cookie=None, idle_timeout=None, hard_timeout=None, priority=None, buffer_id=None, out_port=None, flags=None, actions=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if match != None:
self.match = match
else:
self.match = ofp.match()
if cookie != None:
self.cookie = cookie
else:
self.cookie = 0
if idle_timeout != None:
self.idle_timeout = idle_timeout
else:
self.idle_timeout = 0
if hard_timeout != None:
self.hard_timeout = hard_timeout
else:
self.hard_timeout = 0
if priority != None:
self.priority = priority
else:
self.priority = 0
if buffer_id != None:
self.buffer_id = buffer_id
else:
self.buffer_id = 0
if out_port != None:
self.out_port = out_port
else:
self.out_port = 0
if flags != None:
self.flags = flags
else:
self.flags = 0
if actions != None:
self.actions = actions
else:
self.actions = []
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(self.match.pack())
packed.append(struct.pack("!Q", self.cookie))
packed.append(util.pack_fm_cmd(self._command))
packed.append(struct.pack("!H", self.idle_timeout))
packed.append(struct.pack("!H", self.hard_timeout))
packed.append(struct.pack("!H", self.priority))
packed.append(struct.pack("!L", self.buffer_id))
packed.append(util.pack_port_no(self.out_port))
packed.append(struct.pack("!H", self.flags))
packed.append(loxi.generic_util.pack_list(self.actions))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = flow_delete()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 14)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.match = ofp.match.unpack(reader)
obj.cookie = reader.read("!Q")[0]
__command = util.unpack_fm_cmd(reader)
assert(__command == 3)
obj.idle_timeout = reader.read("!H")[0]
obj.hard_timeout = reader.read("!H")[0]
obj.priority = reader.read("!H")[0]
obj.buffer_id = reader.read("!L")[0]
obj.out_port = util.unpack_port_no(reader)
obj.flags = reader.read("!H")[0]
obj.actions = loxi.generic_util.unpack_list(reader, ofp.action.action.unpack)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.match != other.match: return False
if self.cookie != other.cookie: return False
if self.idle_timeout != other.idle_timeout: return False
if self.hard_timeout != other.hard_timeout: return False
if self.priority != other.priority: return False
if self.buffer_id != other.buffer_id: return False
if self.out_port != other.out_port: return False
if self.flags != other.flags: return False
if self.actions != other.actions: return False
return True
def pretty_print(self, q):
q.text("flow_delete {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("match = ");
q.pp(self.match)
q.text(","); q.breakable()
q.text("cookie = ");
q.text("%#x" % self.cookie)
q.text(","); q.breakable()
q.text("idle_timeout = ");
q.text("%#x" % self.idle_timeout)
q.text(","); q.breakable()
q.text("hard_timeout = ");
q.text("%#x" % self.hard_timeout)
q.text(","); q.breakable()
q.text("priority = ");
q.text("%#x" % self.priority)
q.text(","); q.breakable()
q.text("buffer_id = ");
q.text("%#x" % self.buffer_id)
q.text(","); q.breakable()
q.text("out_port = ");
q.text(util.pretty_port(self.out_port))
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("actions = ");
q.pp(self.actions)
q.breakable()
q.text('}')
flow_mod.subtypes[3] = flow_delete
class flow_delete_strict(flow_mod):
version = 1
type = 14
_command = 4
def __init__(self, xid=None, match=None, cookie=None, idle_timeout=None, hard_timeout=None, priority=None, buffer_id=None, out_port=None, flags=None, actions=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if match != None:
self.match = match
else:
self.match = ofp.match()
if cookie != None:
self.cookie = cookie
else:
self.cookie = 0
if idle_timeout != None:
self.idle_timeout = idle_timeout
else:
self.idle_timeout = 0
if hard_timeout != None:
self.hard_timeout = hard_timeout
else:
self.hard_timeout = 0
if priority != None:
self.priority = priority
else:
self.priority = 0
if buffer_id != None:
self.buffer_id = buffer_id
else:
self.buffer_id = 0
if out_port != None:
self.out_port = out_port
else:
self.out_port = 0
if flags != None:
self.flags = flags
else:
self.flags = 0
if actions != None:
self.actions = actions
else:
self.actions = []
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(self.match.pack())
packed.append(struct.pack("!Q", self.cookie))
packed.append(util.pack_fm_cmd(self._command))
packed.append(struct.pack("!H", self.idle_timeout))
packed.append(struct.pack("!H", self.hard_timeout))
packed.append(struct.pack("!H", self.priority))
packed.append(struct.pack("!L", self.buffer_id))
packed.append(util.pack_port_no(self.out_port))
packed.append(struct.pack("!H", self.flags))
packed.append(loxi.generic_util.pack_list(self.actions))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = flow_delete_strict()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 14)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.match = ofp.match.unpack(reader)
obj.cookie = reader.read("!Q")[0]
__command = util.unpack_fm_cmd(reader)
assert(__command == 4)
obj.idle_timeout = reader.read("!H")[0]
obj.hard_timeout = reader.read("!H")[0]
obj.priority = reader.read("!H")[0]
obj.buffer_id = reader.read("!L")[0]
obj.out_port = util.unpack_port_no(reader)
obj.flags = reader.read("!H")[0]
obj.actions = loxi.generic_util.unpack_list(reader, ofp.action.action.unpack)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.match != other.match: return False
if self.cookie != other.cookie: return False
if self.idle_timeout != other.idle_timeout: return False
if self.hard_timeout != other.hard_timeout: return False
if self.priority != other.priority: return False
if self.buffer_id != other.buffer_id: return False
if self.out_port != other.out_port: return False
if self.flags != other.flags: return False
if self.actions != other.actions: return False
return True
def pretty_print(self, q):
q.text("flow_delete_strict {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("match = ");
q.pp(self.match)
q.text(","); q.breakable()
q.text("cookie = ");
q.text("%#x" % self.cookie)
q.text(","); q.breakable()
q.text("idle_timeout = ");
q.text("%#x" % self.idle_timeout)
q.text(","); q.breakable()
q.text("hard_timeout = ");
q.text("%#x" % self.hard_timeout)
q.text(","); q.breakable()
q.text("priority = ");
q.text("%#x" % self.priority)
q.text(","); q.breakable()
q.text("buffer_id = ");
q.text("%#x" % self.buffer_id)
q.text(","); q.breakable()
q.text("out_port = ");
q.text(util.pretty_port(self.out_port))
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("actions = ");
q.pp(self.actions)
q.breakable()
q.text('}')
flow_mod.subtypes[4] = flow_delete_strict
class flow_mod_failed_error_msg(error_msg):
version = 1
type = 1
err_type = 3
def __init__(self, xid=None, code=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if code != None:
self.code = code
else:
self.code = 0
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.err_type))
packed.append(struct.pack("!H", self.code))
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = flow_mod_failed_error_msg()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 1)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_err_type = reader.read("!H")[0]
assert(_err_type == 3)
obj.code = reader.read("!H")[0]
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.code != other.code: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("flow_mod_failed_error_msg {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("code = ");
q.text("%#x" % self.code)
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
error_msg.subtypes[3] = flow_mod_failed_error_msg
class flow_modify(flow_mod):
version = 1
type = 14
_command = 1
def __init__(self, xid=None, match=None, cookie=None, idle_timeout=None, hard_timeout=None, priority=None, buffer_id=None, out_port=None, flags=None, actions=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if match != None:
self.match = match
else:
self.match = ofp.match()
if cookie != None:
self.cookie = cookie
else:
self.cookie = 0
if idle_timeout != None:
self.idle_timeout = idle_timeout
else:
self.idle_timeout = 0
if hard_timeout != None:
self.hard_timeout = hard_timeout
else:
self.hard_timeout = 0
if priority != None:
self.priority = priority
else:
self.priority = 0
if buffer_id != None:
self.buffer_id = buffer_id
else:
self.buffer_id = 0
if out_port != None:
self.out_port = out_port
else:
self.out_port = 0
if flags != None:
self.flags = flags
else:
self.flags = 0
if actions != None:
self.actions = actions
else:
self.actions = []
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(self.match.pack())
packed.append(struct.pack("!Q", self.cookie))
packed.append(util.pack_fm_cmd(self._command))
packed.append(struct.pack("!H", self.idle_timeout))
packed.append(struct.pack("!H", self.hard_timeout))
packed.append(struct.pack("!H", self.priority))
packed.append(struct.pack("!L", self.buffer_id))
packed.append(util.pack_port_no(self.out_port))
packed.append(struct.pack("!H", self.flags))
packed.append(loxi.generic_util.pack_list(self.actions))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = flow_modify()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 14)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.match = ofp.match.unpack(reader)
obj.cookie = reader.read("!Q")[0]
__command = util.unpack_fm_cmd(reader)
assert(__command == 1)
obj.idle_timeout = reader.read("!H")[0]
obj.hard_timeout = reader.read("!H")[0]
obj.priority = reader.read("!H")[0]
obj.buffer_id = reader.read("!L")[0]
obj.out_port = util.unpack_port_no(reader)
obj.flags = reader.read("!H")[0]
obj.actions = loxi.generic_util.unpack_list(reader, ofp.action.action.unpack)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.match != other.match: return False
if self.cookie != other.cookie: return False
if self.idle_timeout != other.idle_timeout: return False
if self.hard_timeout != other.hard_timeout: return False
if self.priority != other.priority: return False
if self.buffer_id != other.buffer_id: return False
if self.out_port != other.out_port: return False
if self.flags != other.flags: return False
if self.actions != other.actions: return False
return True
def pretty_print(self, q):
q.text("flow_modify {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("match = ");
q.pp(self.match)
q.text(","); q.breakable()
q.text("cookie = ");
q.text("%#x" % self.cookie)
q.text(","); q.breakable()
q.text("idle_timeout = ");
q.text("%#x" % self.idle_timeout)
q.text(","); q.breakable()
q.text("hard_timeout = ");
q.text("%#x" % self.hard_timeout)
q.text(","); q.breakable()
q.text("priority = ");
q.text("%#x" % self.priority)
q.text(","); q.breakable()
q.text("buffer_id = ");
q.text("%#x" % self.buffer_id)
q.text(","); q.breakable()
q.text("out_port = ");
q.text(util.pretty_port(self.out_port))
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("actions = ");
q.pp(self.actions)
q.breakable()
q.text('}')
flow_mod.subtypes[1] = flow_modify
class flow_modify_strict(flow_mod):
version = 1
type = 14
_command = 2
def __init__(self, xid=None, match=None, cookie=None, idle_timeout=None, hard_timeout=None, priority=None, buffer_id=None, out_port=None, flags=None, actions=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if match != None:
self.match = match
else:
self.match = ofp.match()
if cookie != None:
self.cookie = cookie
else:
self.cookie = 0
if idle_timeout != None:
self.idle_timeout = idle_timeout
else:
self.idle_timeout = 0
if hard_timeout != None:
self.hard_timeout = hard_timeout
else:
self.hard_timeout = 0
if priority != None:
self.priority = priority
else:
self.priority = 0
if buffer_id != None:
self.buffer_id = buffer_id
else:
self.buffer_id = 0
if out_port != None:
self.out_port = out_port
else:
self.out_port = 0
if flags != None:
self.flags = flags
else:
self.flags = 0
if actions != None:
self.actions = actions
else:
self.actions = []
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(self.match.pack())
packed.append(struct.pack("!Q", self.cookie))
packed.append(util.pack_fm_cmd(self._command))
packed.append(struct.pack("!H", self.idle_timeout))
packed.append(struct.pack("!H", self.hard_timeout))
packed.append(struct.pack("!H", self.priority))
packed.append(struct.pack("!L", self.buffer_id))
packed.append(util.pack_port_no(self.out_port))
packed.append(struct.pack("!H", self.flags))
packed.append(loxi.generic_util.pack_list(self.actions))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = flow_modify_strict()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 14)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.match = ofp.match.unpack(reader)
obj.cookie = reader.read("!Q")[0]
__command = util.unpack_fm_cmd(reader)
assert(__command == 2)
obj.idle_timeout = reader.read("!H")[0]
obj.hard_timeout = reader.read("!H")[0]
obj.priority = reader.read("!H")[0]
obj.buffer_id = reader.read("!L")[0]
obj.out_port = util.unpack_port_no(reader)
obj.flags = reader.read("!H")[0]
obj.actions = loxi.generic_util.unpack_list(reader, ofp.action.action.unpack)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.match != other.match: return False
if self.cookie != other.cookie: return False
if self.idle_timeout != other.idle_timeout: return False
if self.hard_timeout != other.hard_timeout: return False
if self.priority != other.priority: return False
if self.buffer_id != other.buffer_id: return False
if self.out_port != other.out_port: return False
if self.flags != other.flags: return False
if self.actions != other.actions: return False
return True
def pretty_print(self, q):
q.text("flow_modify_strict {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("match = ");
q.pp(self.match)
q.text(","); q.breakable()
q.text("cookie = ");
q.text("%#x" % self.cookie)
q.text(","); q.breakable()
q.text("idle_timeout = ");
q.text("%#x" % self.idle_timeout)
q.text(","); q.breakable()
q.text("hard_timeout = ");
q.text("%#x" % self.hard_timeout)
q.text(","); q.breakable()
q.text("priority = ");
q.text("%#x" % self.priority)
q.text(","); q.breakable()
q.text("buffer_id = ");
q.text("%#x" % self.buffer_id)
q.text(","); q.breakable()
q.text("out_port = ");
q.text(util.pretty_port(self.out_port))
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("actions = ");
q.pp(self.actions)
q.breakable()
q.text('}')
flow_mod.subtypes[2] = flow_modify_strict
class flow_removed(message):
version = 1
type = 11
def __init__(self, xid=None, match=None, cookie=None, priority=None, reason=None, duration_sec=None, duration_nsec=None, idle_timeout=None, packet_count=None, byte_count=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if match != None:
self.match = match
else:
self.match = ofp.match()
if cookie != None:
self.cookie = cookie
else:
self.cookie = 0
if priority != None:
self.priority = priority
else:
self.priority = 0
if reason != None:
self.reason = reason
else:
self.reason = 0
if duration_sec != None:
self.duration_sec = duration_sec
else:
self.duration_sec = 0
if duration_nsec != None:
self.duration_nsec = duration_nsec
else:
self.duration_nsec = 0
if idle_timeout != None:
self.idle_timeout = idle_timeout
else:
self.idle_timeout = 0
if packet_count != None:
self.packet_count = packet_count
else:
self.packet_count = 0
if byte_count != None:
self.byte_count = byte_count
else:
self.byte_count = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(self.match.pack())
packed.append(struct.pack("!Q", self.cookie))
packed.append(struct.pack("!H", self.priority))
packed.append(struct.pack("!B", self.reason))
packed.append('\x00' * 1)
packed.append(struct.pack("!L", self.duration_sec))
packed.append(struct.pack("!L", self.duration_nsec))
packed.append(struct.pack("!H", self.idle_timeout))
packed.append('\x00' * 2)
packed.append(struct.pack("!Q", self.packet_count))
packed.append(struct.pack("!Q", self.byte_count))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = flow_removed()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 11)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.match = ofp.match.unpack(reader)
obj.cookie = reader.read("!Q")[0]
obj.priority = reader.read("!H")[0]
obj.reason = reader.read("!B")[0]
reader.skip(1)
obj.duration_sec = reader.read("!L")[0]
obj.duration_nsec = reader.read("!L")[0]
obj.idle_timeout = reader.read("!H")[0]
reader.skip(2)
obj.packet_count = reader.read("!Q")[0]
obj.byte_count = reader.read("!Q")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.match != other.match: return False
if self.cookie != other.cookie: return False
if self.priority != other.priority: return False
if self.reason != other.reason: return False
if self.duration_sec != other.duration_sec: return False
if self.duration_nsec != other.duration_nsec: return False
if self.idle_timeout != other.idle_timeout: return False
if self.packet_count != other.packet_count: return False
if self.byte_count != other.byte_count: return False
return True
def pretty_print(self, q):
q.text("flow_removed {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("match = ");
q.pp(self.match)
q.text(","); q.breakable()
q.text("cookie = ");
q.text("%#x" % self.cookie)
q.text(","); q.breakable()
q.text("priority = ");
q.text("%#x" % self.priority)
q.text(","); q.breakable()
q.text("reason = ");
q.text("%#x" % self.reason)
q.text(","); q.breakable()
q.text("duration_sec = ");
q.text("%#x" % self.duration_sec)
q.text(","); q.breakable()
q.text("duration_nsec = ");
q.text("%#x" % self.duration_nsec)
q.text(","); q.breakable()
q.text("idle_timeout = ");
q.text("%#x" % self.idle_timeout)
q.text(","); q.breakable()
q.text("packet_count = ");
q.text("%#x" % self.packet_count)
q.text(","); q.breakable()
q.text("byte_count = ");
q.text("%#x" % self.byte_count)
q.breakable()
q.text('}')
message.subtypes[11] = flow_removed
class flow_stats_reply(stats_reply):
version = 1
type = 17
stats_type = 1
def __init__(self, xid=None, flags=None, entries=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if entries != None:
self.entries = entries
else:
self.entries = []
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
packed.append(loxi.generic_util.pack_list(self.entries))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = flow_stats_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 17)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 1)
obj.flags = reader.read("!H")[0]
obj.entries = loxi.generic_util.unpack_list(reader, ofp.common.flow_stats_entry.unpack)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.entries != other.entries: return False
return True
def pretty_print(self, q):
q.text("flow_stats_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("entries = ");
q.pp(self.entries)
q.breakable()
q.text('}')
stats_reply.subtypes[1] = flow_stats_reply
class flow_stats_request(stats_request):
version = 1
type = 16
stats_type = 1
def __init__(self, xid=None, flags=None, match=None, table_id=None, out_port=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if match != None:
self.match = match
else:
self.match = ofp.match()
if table_id != None:
self.table_id = table_id
else:
self.table_id = 0
if out_port != None:
self.out_port = out_port
else:
self.out_port = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
packed.append(self.match.pack())
packed.append(struct.pack("!B", self.table_id))
packed.append('\x00' * 1)
packed.append(util.pack_port_no(self.out_port))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = flow_stats_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 16)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 1)
obj.flags = reader.read("!H")[0]
obj.match = ofp.match.unpack(reader)
obj.table_id = reader.read("!B")[0]
reader.skip(1)
obj.out_port = util.unpack_port_no(reader)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.match != other.match: return False
if self.table_id != other.table_id: return False
if self.out_port != other.out_port: return False
return True
def pretty_print(self, q):
q.text("flow_stats_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("match = ");
q.pp(self.match)
q.text(","); q.breakable()
q.text("table_id = ");
q.text("%#x" % self.table_id)
q.text(","); q.breakable()
q.text("out_port = ");
q.text(util.pretty_port(self.out_port))
q.breakable()
q.text('}')
stats_request.subtypes[1] = flow_stats_request
class get_config_reply(message):
version = 1
type = 8
def __init__(self, xid=None, flags=None, miss_send_len=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if miss_send_len != None:
self.miss_send_len = miss_send_len
else:
self.miss_send_len = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.flags))
packed.append(struct.pack("!H", self.miss_send_len))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = get_config_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 8)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.flags = reader.read("!H")[0]
obj.miss_send_len = reader.read("!H")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.miss_send_len != other.miss_send_len: return False
return True
def pretty_print(self, q):
q.text("get_config_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("miss_send_len = ");
q.text("%#x" % self.miss_send_len)
q.breakable()
q.text('}')
message.subtypes[8] = get_config_reply
class get_config_request(message):
version = 1
type = 7
def __init__(self, xid=None):
if xid != None:
self.xid = xid
else:
self.xid = None
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = get_config_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 7)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
return True
def pretty_print(self, q):
q.text("get_config_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.breakable()
q.text('}')
message.subtypes[7] = get_config_request
class hello(message):
version = 1
type = 0
def __init__(self, xid=None):
if xid != None:
self.xid = xid
else:
self.xid = None
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = hello()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 0)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
return True
def pretty_print(self, q):
q.text("hello {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.breakable()
q.text('}')
message.subtypes[0] = hello
class hello_failed_error_msg(error_msg):
version = 1
type = 1
err_type = 0
def __init__(self, xid=None, code=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if code != None:
self.code = code
else:
self.code = 0
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.err_type))
packed.append(struct.pack("!H", self.code))
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = hello_failed_error_msg()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 1)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_err_type = reader.read("!H")[0]
assert(_err_type == 0)
obj.code = reader.read("!H")[0]
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.code != other.code: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("hello_failed_error_msg {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("code = ");
q.text("%#x" % self.code)
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
error_msg.subtypes[0] = hello_failed_error_msg
class nicira_header(experimenter):
subtypes = {}
version = 1
type = 4
experimenter = 8992
def __init__(self, xid=None, subtype=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if subtype != None:
self.subtype = subtype
else:
self.subtype = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
subtype, = reader.peek('!L', 12)
subclass = nicira_header.subtypes.get(subtype)
if subclass:
return subclass.unpack(reader)
obj = nicira_header()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 8992)
obj.subtype = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.subtype != other.subtype: return False
return True
def pretty_print(self, q):
q.text("nicira_header {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.breakable()
q.text('}')
experimenter.subtypes[8992] = nicira_header
class nicira_controller_role_reply(nicira_header):
version = 1
type = 4
experimenter = 8992
subtype = 11
def __init__(self, xid=None, role=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if role != None:
self.role = role
else:
self.role = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.role))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = nicira_controller_role_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 8992)
_subtype = reader.read("!L")[0]
assert(_subtype == 11)
obj.role = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.role != other.role: return False
return True
def pretty_print(self, q):
q.text("nicira_controller_role_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("role = ");
q.text("%#x" % self.role)
q.breakable()
q.text('}')
nicira_header.subtypes[11] = nicira_controller_role_reply
class nicira_controller_role_request(nicira_header):
version = 1
type = 4
experimenter = 8992
subtype = 10
def __init__(self, xid=None, role=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if role != None:
self.role = role
else:
self.role = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.experimenter))
packed.append(struct.pack("!L", self.subtype))
packed.append(struct.pack("!L", self.role))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = nicira_controller_role_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 4)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_experimenter = reader.read("!L")[0]
assert(_experimenter == 8992)
_subtype = reader.read("!L")[0]
assert(_subtype == 10)
obj.role = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.role != other.role: return False
return True
def pretty_print(self, q):
q.text("nicira_controller_role_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("role = ");
q.text("%#x" % self.role)
q.breakable()
q.text('}')
nicira_header.subtypes[10] = nicira_controller_role_request
class packet_in(message):
version = 1
type = 10
def __init__(self, xid=None, buffer_id=None, total_len=None, in_port=None, reason=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if buffer_id != None:
self.buffer_id = buffer_id
else:
self.buffer_id = 0
if total_len != None:
self.total_len = total_len
else:
self.total_len = 0
if in_port != None:
self.in_port = in_port
else:
self.in_port = 0
if reason != None:
self.reason = reason
else:
self.reason = 0
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.buffer_id))
packed.append(struct.pack("!H", self.total_len))
packed.append(util.pack_port_no(self.in_port))
packed.append(struct.pack("!B", self.reason))
packed.append('\x00' * 1)
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = packet_in()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 10)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.buffer_id = reader.read("!L")[0]
obj.total_len = reader.read("!H")[0]
obj.in_port = util.unpack_port_no(reader)
obj.reason = reader.read("!B")[0]
reader.skip(1)
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.buffer_id != other.buffer_id: return False
if self.total_len != other.total_len: return False
if self.in_port != other.in_port: return False
if self.reason != other.reason: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("packet_in {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("buffer_id = ");
q.text("%#x" % self.buffer_id)
q.text(","); q.breakable()
q.text("total_len = ");
q.text("%#x" % self.total_len)
q.text(","); q.breakable()
q.text("in_port = ");
q.text(util.pretty_port(self.in_port))
q.text(","); q.breakable()
q.text("reason = ");
q.text("%#x" % self.reason)
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
message.subtypes[10] = packet_in
class packet_out(message):
version = 1
type = 13
def __init__(self, xid=None, buffer_id=None, in_port=None, actions=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if buffer_id != None:
self.buffer_id = buffer_id
else:
self.buffer_id = 0
if in_port != None:
self.in_port = in_port
else:
self.in_port = 0
if actions != None:
self.actions = actions
else:
self.actions = []
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!L", self.buffer_id))
packed.append(util.pack_port_no(self.in_port))
packed.append(struct.pack("!H", 0)) # placeholder for actions_len at index 6
packed.append(loxi.generic_util.pack_list(self.actions))
packed[6] = struct.pack("!H", len(packed[-1]))
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = packet_out()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 13)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.buffer_id = reader.read("!L")[0]
obj.in_port = util.unpack_port_no(reader)
_actions_len = reader.read("!H")[0]
obj.actions = loxi.generic_util.unpack_list(reader.slice(_actions_len), ofp.action.action.unpack)
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.buffer_id != other.buffer_id: return False
if self.in_port != other.in_port: return False
if self.actions != other.actions: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("packet_out {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("buffer_id = ");
q.text("%#x" % self.buffer_id)
q.text(","); q.breakable()
q.text("in_port = ");
q.text(util.pretty_port(self.in_port))
q.text(","); q.breakable()
q.text("actions = ");
q.pp(self.actions)
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
message.subtypes[13] = packet_out
class port_mod(message):
version = 1
type = 15
def __init__(self, xid=None, port_no=None, hw_addr=None, config=None, mask=None, advertise=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if port_no != None:
self.port_no = port_no
else:
self.port_no = 0
if hw_addr != None:
self.hw_addr = hw_addr
else:
self.hw_addr = [0,0,0,0,0,0]
if config != None:
self.config = config
else:
self.config = 0
if mask != None:
self.mask = mask
else:
self.mask = 0
if advertise != None:
self.advertise = advertise
else:
self.advertise = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(util.pack_port_no(self.port_no))
packed.append(struct.pack("!6B", *self.hw_addr))
packed.append(struct.pack("!L", self.config))
packed.append(struct.pack("!L", self.mask))
packed.append(struct.pack("!L", self.advertise))
packed.append('\x00' * 4)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = port_mod()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 15)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.port_no = util.unpack_port_no(reader)
obj.hw_addr = list(reader.read('!6B'))
obj.config = reader.read("!L")[0]
obj.mask = reader.read("!L")[0]
obj.advertise = reader.read("!L")[0]
reader.skip(4)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.port_no != other.port_no: return False
if self.hw_addr != other.hw_addr: return False
if self.config != other.config: return False
if self.mask != other.mask: return False
if self.advertise != other.advertise: return False
return True
def pretty_print(self, q):
q.text("port_mod {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("port_no = ");
q.text(util.pretty_port(self.port_no))
q.text(","); q.breakable()
q.text("hw_addr = ");
q.text(util.pretty_mac(self.hw_addr))
q.text(","); q.breakable()
q.text("config = ");
q.text("%#x" % self.config)
q.text(","); q.breakable()
q.text("mask = ");
q.text("%#x" % self.mask)
q.text(","); q.breakable()
q.text("advertise = ");
q.text("%#x" % self.advertise)
q.breakable()
q.text('}')
message.subtypes[15] = port_mod
class port_mod_failed_error_msg(error_msg):
version = 1
type = 1
err_type = 4
def __init__(self, xid=None, code=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if code != None:
self.code = code
else:
self.code = 0
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.err_type))
packed.append(struct.pack("!H", self.code))
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = port_mod_failed_error_msg()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 1)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_err_type = reader.read("!H")[0]
assert(_err_type == 4)
obj.code = reader.read("!H")[0]
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.code != other.code: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("port_mod_failed_error_msg {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("code = ");
q.text("%#x" % self.code)
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
error_msg.subtypes[4] = port_mod_failed_error_msg
class port_stats_reply(stats_reply):
version = 1
type = 17
stats_type = 4
def __init__(self, xid=None, flags=None, entries=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if entries != None:
self.entries = entries
else:
self.entries = []
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
packed.append(loxi.generic_util.pack_list(self.entries))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = port_stats_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 17)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 4)
obj.flags = reader.read("!H")[0]
obj.entries = loxi.generic_util.unpack_list(reader, ofp.common.port_stats_entry.unpack)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.entries != other.entries: return False
return True
def pretty_print(self, q):
q.text("port_stats_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("entries = ");
q.pp(self.entries)
q.breakable()
q.text('}')
stats_reply.subtypes[4] = port_stats_reply
class port_stats_request(stats_request):
version = 1
type = 16
stats_type = 4
def __init__(self, xid=None, flags=None, port_no=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if port_no != None:
self.port_no = port_no
else:
self.port_no = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
packed.append(util.pack_port_no(self.port_no))
packed.append('\x00' * 6)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = port_stats_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 16)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 4)
obj.flags = reader.read("!H")[0]
obj.port_no = util.unpack_port_no(reader)
reader.skip(6)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.port_no != other.port_no: return False
return True
def pretty_print(self, q):
q.text("port_stats_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("port_no = ");
q.text(util.pretty_port(self.port_no))
q.breakable()
q.text('}')
stats_request.subtypes[4] = port_stats_request
class port_status(message):
version = 1
type = 12
def __init__(self, xid=None, reason=None, desc=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if reason != None:
self.reason = reason
else:
self.reason = 0
if desc != None:
self.desc = desc
else:
self.desc = ofp.port_desc()
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!B", self.reason))
packed.append('\x00' * 7)
packed.append(self.desc.pack())
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = port_status()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 12)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.reason = reader.read("!B")[0]
reader.skip(7)
obj.desc = ofp.port_desc.unpack(reader)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.reason != other.reason: return False
if self.desc != other.desc: return False
return True
def pretty_print(self, q):
q.text("port_status {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("reason = ");
q.text("%#x" % self.reason)
q.text(","); q.breakable()
q.text("desc = ");
q.pp(self.desc)
q.breakable()
q.text('}')
message.subtypes[12] = port_status
class queue_get_config_reply(message):
version = 1
type = 21
def __init__(self, xid=None, port=None, queues=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if port != None:
self.port = port
else:
self.port = 0
if queues != None:
self.queues = queues
else:
self.queues = []
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(util.pack_port_no(self.port))
packed.append('\x00' * 6)
packed.append(loxi.generic_util.pack_list(self.queues))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = queue_get_config_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 21)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.port = util.unpack_port_no(reader)
reader.skip(6)
obj.queues = loxi.generic_util.unpack_list(reader, ofp.common.packet_queue.unpack)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.port != other.port: return False
if self.queues != other.queues: return False
return True
def pretty_print(self, q):
q.text("queue_get_config_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("port = ");
q.text(util.pretty_port(self.port))
q.text(","); q.breakable()
q.text("queues = ");
q.pp(self.queues)
q.breakable()
q.text('}')
message.subtypes[21] = queue_get_config_reply
class queue_get_config_request(message):
version = 1
type = 20
def __init__(self, xid=None, port=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if port != None:
self.port = port
else:
self.port = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(util.pack_port_no(self.port))
packed.append('\x00' * 2)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = queue_get_config_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 20)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.port = util.unpack_port_no(reader)
reader.skip(2)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.port != other.port: return False
return True
def pretty_print(self, q):
q.text("queue_get_config_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("port = ");
q.text(util.pretty_port(self.port))
q.breakable()
q.text('}')
message.subtypes[20] = queue_get_config_request
class queue_op_failed_error_msg(error_msg):
version = 1
type = 1
err_type = 5
def __init__(self, xid=None, code=None, data=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if code != None:
self.code = code
else:
self.code = 0
if data != None:
self.data = data
else:
self.data = ''
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.err_type))
packed.append(struct.pack("!H", self.code))
packed.append(self.data)
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = queue_op_failed_error_msg()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 1)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_err_type = reader.read("!H")[0]
assert(_err_type == 5)
obj.code = reader.read("!H")[0]
obj.data = str(reader.read_all())
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.code != other.code: return False
if self.data != other.data: return False
return True
def pretty_print(self, q):
q.text("queue_op_failed_error_msg {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("code = ");
q.text("%#x" % self.code)
q.text(","); q.breakable()
q.text("data = ");
q.pp(self.data)
q.breakable()
q.text('}')
error_msg.subtypes[5] = queue_op_failed_error_msg
class queue_stats_reply(stats_reply):
version = 1
type = 17
stats_type = 5
def __init__(self, xid=None, flags=None, entries=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if entries != None:
self.entries = entries
else:
self.entries = []
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
packed.append(loxi.generic_util.pack_list(self.entries))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = queue_stats_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 17)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 5)
obj.flags = reader.read("!H")[0]
obj.entries = loxi.generic_util.unpack_list(reader, ofp.common.queue_stats_entry.unpack)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.entries != other.entries: return False
return True
def pretty_print(self, q):
q.text("queue_stats_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("entries = ");
q.pp(self.entries)
q.breakable()
q.text('}')
stats_reply.subtypes[5] = queue_stats_reply
class queue_stats_request(stats_request):
version = 1
type = 16
stats_type = 5
def __init__(self, xid=None, flags=None, port_no=None, queue_id=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if port_no != None:
self.port_no = port_no
else:
self.port_no = 0
if queue_id != None:
self.queue_id = queue_id
else:
self.queue_id = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
packed.append(util.pack_port_no(self.port_no))
packed.append('\x00' * 2)
packed.append(struct.pack("!L", self.queue_id))<|fim▁hole|>
@staticmethod
def unpack(reader):
obj = queue_stats_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 16)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 5)
obj.flags = reader.read("!H")[0]
obj.port_no = util.unpack_port_no(reader)
reader.skip(2)
obj.queue_id = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.port_no != other.port_no: return False
if self.queue_id != other.queue_id: return False
return True
def pretty_print(self, q):
q.text("queue_stats_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("port_no = ");
q.text(util.pretty_port(self.port_no))
q.text(","); q.breakable()
q.text("queue_id = ");
q.text("%#x" % self.queue_id)
q.breakable()
q.text('}')
stats_request.subtypes[5] = queue_stats_request
class set_config(message):
version = 1
type = 9
def __init__(self, xid=None, flags=None, miss_send_len=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if miss_send_len != None:
self.miss_send_len = miss_send_len
else:
self.miss_send_len = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.flags))
packed.append(struct.pack("!H", self.miss_send_len))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = set_config()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 9)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.flags = reader.read("!H")[0]
obj.miss_send_len = reader.read("!H")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.miss_send_len != other.miss_send_len: return False
return True
def pretty_print(self, q):
q.text("set_config {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("miss_send_len = ");
q.text("%#x" % self.miss_send_len)
q.breakable()
q.text('}')
message.subtypes[9] = set_config
class table_mod(message):
version = 1
type = 22
def __init__(self, xid=None, table_id=None, config=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if table_id != None:
self.table_id = table_id
else:
self.table_id = 0
if config != None:
self.config = config
else:
self.config = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!B", self.table_id))
packed.append('\x00' * 3)
packed.append(struct.pack("!L", self.config))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = table_mod()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 22)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
obj.table_id = reader.read("!B")[0]
reader.skip(3)
obj.config = reader.read("!L")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.table_id != other.table_id: return False
if self.config != other.config: return False
return True
def pretty_print(self, q):
q.text("table_mod {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("table_id = ");
q.text("%#x" % self.table_id)
q.text(","); q.breakable()
q.text("config = ");
q.text("%#x" % self.config)
q.breakable()
q.text('}')
message.subtypes[22] = table_mod
class table_stats_reply(stats_reply):
version = 1
type = 17
stats_type = 3
def __init__(self, xid=None, flags=None, entries=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
if entries != None:
self.entries = entries
else:
self.entries = []
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
packed.append(loxi.generic_util.pack_list(self.entries))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = table_stats_reply()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 17)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 3)
obj.flags = reader.read("!H")[0]
obj.entries = loxi.generic_util.unpack_list(reader, ofp.common.table_stats_entry.unpack)
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
if self.entries != other.entries: return False
return True
def pretty_print(self, q):
q.text("table_stats_reply {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.text(","); q.breakable()
q.text("entries = ");
q.pp(self.entries)
q.breakable()
q.text('}')
stats_reply.subtypes[3] = table_stats_reply
class table_stats_request(stats_request):
version = 1
type = 16
stats_type = 3
def __init__(self, xid=None, flags=None):
if xid != None:
self.xid = xid
else:
self.xid = None
if flags != None:
self.flags = flags
else:
self.flags = 0
return
def pack(self):
packed = []
packed.append(struct.pack("!B", self.version))
packed.append(struct.pack("!B", self.type))
packed.append(struct.pack("!H", 0)) # placeholder for length at index 2
packed.append(struct.pack("!L", self.xid))
packed.append(struct.pack("!H", self.stats_type))
packed.append(struct.pack("!H", self.flags))
length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed)
@staticmethod
def unpack(reader):
obj = table_stats_request()
_version = reader.read("!B")[0]
assert(_version == 1)
_type = reader.read("!B")[0]
assert(_type == 16)
_length = reader.read("!H")[0]
orig_reader = reader
reader = orig_reader.slice(_length, 4)
obj.xid = reader.read("!L")[0]
_stats_type = reader.read("!H")[0]
assert(_stats_type == 3)
obj.flags = reader.read("!H")[0]
return obj
def __eq__(self, other):
if type(self) != type(other): return False
if self.xid != other.xid: return False
if self.flags != other.flags: return False
return True
def pretty_print(self, q):
q.text("table_stats_request {")
with q.group():
with q.indent(2):
q.breakable()
q.text("xid = ");
if self.xid != None:
q.text("%#x" % self.xid)
else:
q.text('None')
q.text(","); q.breakable()
q.text("flags = ");
q.text("%#x" % self.flags)
q.breakable()
q.text('}')
stats_request.subtypes[3] = table_stats_request
def parse_header(buf):
if len(buf) < 8:
raise loxi.ProtocolError("too short to be an OpenFlow message")
return struct.unpack_from("!BBHL", buf)
def parse_message(buf):
msg_ver, msg_type, msg_len, msg_xid = parse_header(buf)
if msg_ver != ofp.OFP_VERSION and msg_type != ofp.OFPT_HELLO:
raise loxi.ProtocolError("wrong OpenFlow version (expected %d, got %d)" % (ofp.OFP_VERSION, msg_ver))
if len(buf) != msg_len:
raise loxi.ProtocolError("incorrect message size")
return message.unpack(loxi.generic_util.OFReader(buf))<|fim▁end|> | length = sum([len(x) for x in packed])
packed[2] = struct.pack("!H", length)
return ''.join(packed) |
<|file_name|>issue-13620-2.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-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.
extern crate "issue-13620-1" as crate1;<|fim▁hole|>
pub static FOO2: crate1::Foo = crate1::FOO;<|fim▁end|> | |
<|file_name|>demo.py<|end_file_name|><|fim▁begin|>"""
Demo platform that has two fake binary sensors.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/demo/
"""
import homeassistant.util.dt as dt_util
from homeassistant.components.calendar import CalendarEventDevice
from homeassistant.components.google import CONF_DEVICE_ID, CONF_NAME
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Demo Calendar platform."""
calendar_data_future = DemoGoogleCalendarDataFuture()
calendar_data_current = DemoGoogleCalendarDataCurrent()
add_devices([
DemoGoogleCalendar(hass, calendar_data_future, {
CONF_NAME: 'Future Event',
CONF_DEVICE_ID: 'future_event',
}),
DemoGoogleCalendar(hass, calendar_data_current, {
CONF_NAME: 'Current Event',
CONF_DEVICE_ID: 'current_event',
}),
])
class DemoGoogleCalendarData(object):
"""Representation of a Demo Calendar element."""
# pylint: disable=no-self-use
def update(self):
"""Return true so entity knows we have new data."""
return True
class DemoGoogleCalendarDataFuture(DemoGoogleCalendarData):
"""Representation of a Demo Calendar for a future event."""
def __init__(self):
"""Set the event to a future event."""
one_hour_from_now = dt_util.now() \
+ dt_util.dt.timedelta(minutes=30)
self.event = {
'start': {
'dateTime': one_hour_from_now.isoformat()
},
'end': {
'dateTime': (one_hour_from_now + dt_util.dt.
timedelta(minutes=60)).isoformat()
},
'summary': 'Future Event',
}
class DemoGoogleCalendarDataCurrent(DemoGoogleCalendarData):
"""Representation of a Demo Calendar for a current event."""
def __init__(self):
"""Set the event data."""
middle_of_event = dt_util.now() \
- dt_util.dt.timedelta(minutes=30)
self.event = {
'start': {
'dateTime': middle_of_event.isoformat()
},
'end': {
'dateTime': (middle_of_event + dt_util.dt.
timedelta(minutes=60)).isoformat()
},
'summary': 'Current Event',
}
class DemoGoogleCalendar(CalendarEventDevice):
"""Representation of a Demo Calendar element."""
def __init__(self, hass, calendar_data, data):
<|fim▁hole|><|fim▁end|> | """Initialize Google Calendar but without the API calls."""
self.data = calendar_data
super().__init__(hass, data) |
<|file_name|>Post.ts<|end_file_name|><|fim▁begin|>import {Entity} from "../../../../src/decorator/entity/Entity";
import {BaseEntity} from "../../../../src/repository/BaseEntity";
import {PrimaryGeneratedColumn} from "../../../../src/decorator/columns/PrimaryGeneratedColumn";
import {Column} from "../../../../src/decorator/columns/Column";
import {ManyToMany, JoinTable} from "../../../../src";
import {Category} from "./Category";
@Entity()
export class Post extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()<|fim▁hole|> default: "This is default text."
})
text: string;
@ManyToMany(type => Category)
@JoinTable()
categories: Category[];
}<|fim▁end|> | title: string;
@Column({ |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Generated file. Do not edit
__author__="drone"
from Abs import Abs
from And import And
from Average import Average
from Ceil import Ceil
from Cube import Cube
from Divide import Divide
from Double import Double
from Equal import Equal
from Even import Even
from Floor import Floor
from Greaterorequal import Greaterorequal
from Greaterthan import Greaterthan
from Half import Half
from If import If
from Increment import Increment
from Lessorequal import Lessorequal
from Lessthan import Lessthan
from Max import Max
from Min import Min
from Module import Module
from Multiply import Multiply
from Negate import Negate
from Not import Not
from Odd import Odd
from One import One
from Positive import Positive
from Quadruple import Quadruple
from Sign import Sign
from Sub import Sub<|fim▁hole|>from Zero import Zero
__all__ = ['Abs', 'And', 'Average', 'Ceil', 'Cube', 'Divide', 'Double', 'Equal', 'Even', 'Floor', 'Greaterorequal', 'Greaterthan', 'Half', 'If', 'Increment', 'Lessorequal', 'Lessthan', 'Max', 'Min', 'Module', 'Multiply', 'Negate', 'Not', 'Odd', 'One', 'Positive', 'Quadruple', 'Sign', 'Sub', 'Sum', 'Two', 'Zero']<|fim▁end|> | from Sum import Sum
from Two import Two |
<|file_name|>notebookListUpdater.ts<|end_file_name|><|fim▁begin|>import { Notebook } from './notebook';
import { SectionGroup } from './sectionGroup';
import { Section } from './section';
import { Page } from './page';
import { OneNoteItemUtils } from './oneNoteItemUtils';
type SectionParent = Notebook | SectionGroup;
/**
* Responsible for updating the notebook list object in a controlled manner.
* In particular, preserves expanded state. There is no guarantee that the
* internal notebook list object * will be modified or replaced. Logic relying
* on this class should use the getter as the most recent source of truth.
*/<|fim▁hole|>
constructor(initialNotebooks: Notebook[]) {
this.notebooks = initialNotebooks;
}
/**
* Gets the notebook list
*/
get(): Notebook[] {
return this.notebooks;
}
/**
* Updates the internal notebooks with a more recent version of the notebooks,
* returned from the API.
* @param apiNotebooks The API notebooks to update the internal notebooks with.
*/
updateNotebookList(newNotebooks: Notebook[]) {
const oldNotebooks = this.notebooks;
this.notebooks = newNotebooks;
if (oldNotebooks.length === 0) {
return;
}
// TODO (machiam) cut down on repeat code after we have UTs
for (let newNotebook of newNotebooks) {
const originalNotebook = oldNotebooks.find(notebook => notebook.id === newNotebook.id);
if (!!originalNotebook) {
this.preserveSectionParent(originalNotebook, newNotebook);
}
}
}
addNotebook(newNotebook: Notebook) {
// Always prepend
const newNotebooks = [newNotebook, ...this.notebooks];
this.notebooks = newNotebooks;
}
addSection(newSection: Section) {
const loneParent = newSection.parent!;
const parentInHierarchy = OneNoteItemUtils.find(this.notebooks, item => item.id === loneParent.id) as SectionParent | undefined;
if (parentInHierarchy && parentInHierarchy.sections) {
// Establish two-way reference
parentInHierarchy.sections = [newSection, ...parentInHierarchy.sections];
newSection.parent = parentInHierarchy;
}
}
private preserveSectionParent(original: SectionParent, next: SectionParent) {
// Preserve properties we want to keep from the original object ...
next.expanded = original.expanded;
if (!original.sections || !original.sectionGroups ||
!next.sections || !next.sectionGroups) {
return;
}
// ... then recurse through the children
for (let newSectionGroup of next.sectionGroups) {
const originalSectionGroup = original.sectionGroups.find(sg => sg.id === newSectionGroup.id);
if (!!originalSectionGroup) {
this.preserveSectionParent(originalSectionGroup, newSectionGroup);
}
}
// TODO (machiam) cut down on repeat code after we have UTs
for (let newSection of next.sections) {
const originalSection = original.sections.find(section => section.id === newSection.id);
if (!!originalSection) {
newSection.expanded = originalSection.expanded;
}
}
}
/**
* Updates the internal notebooks' section with a more recent version of its
* sections.
* @param parentSectionId Parent section id.
* @param apiPages The API pages to update the internal notebooks' matching section with.
*/
updatePages(parentSectionId: string, newPages: Page[]) {
if (!this.notebooks) {
return;
}
const sectionRef = this.getSectionRefFromNotebooks(parentSectionId, this.notebooks);
if (!sectionRef) {
return;
}
sectionRef.pages = newPages;
}
private getSectionRefFromNotebooks(sectionId: string, notebooks: Notebook[]): Section | undefined {
for (let notebook of notebooks) {
const sectionRef = this.getSectionRefFromSectionParent(sectionId, notebook);
if (!!sectionRef) {
return sectionRef;
}
}
// We couldn't find the section in this subtree
return undefined;
}
private getSectionRefFromSectionParent(sectionId: string, sectionParent: SectionParent): Section | undefined {
if (!sectionParent.sections || !sectionParent.sectionGroups) {
return undefined;
}
// Search this parent's sections for the matching id ...
for (let childSection of sectionParent.sections) {
if (childSection.id === sectionId) {
return childSection;
}
}
// ... then recurse through section groups
for (let childSectionParent of sectionParent.sectionGroups) {
const sectionRef = this.getSectionRefFromSectionParent(sectionId, childSectionParent);
if (!!sectionRef) {
return sectionRef;
}
}
// We couldn't find the section in this subtree
return undefined;
}
}<|fim▁end|> | export class NotebookListUpdater {
// TODO (machiam) Currently we don't support updating shared notebooks the react way
private notebooks: Notebook[]; |
<|file_name|>scene01.cpp<|end_file_name|><|fim▁begin|>/**
* This file is part of a demo that shows how to use RT2D, a 2D OpenGL framework.
*
* - Copyright 2015 Rik Teerling <[email protected]>
* - Initial commit
* - Copyright 2015 Your Name <[email protected]>
* - What you did
*/
#include "scene01.h"
Scene01::Scene01() : SuperScene()
{
// Start Timer t
t.start();
text[0]->message("Scene01: Parent/child, Sprite, Spritesheet, blendcolor");
text[4]->message("<SPACE> reset UV animation");
text[5]->message("<Arrow keys> move camera");
// Create an Entity with a custom pivot point.
default_entity = new BasicEntity();
default_entity->addSprite("assets/default.tga", 0.75f, 0.25f, 3, 0); // custom pivot point, filter, wrap (0=repeat, 1=mirror, 2=clamp)
default_entity->position = Point2(SWIDTH/3, SHEIGHT/2);
// To create a Sprite with specific properties, create it first, then add it to an Entity later.
// It will be unique once you added it to an Entity. Except for non-dynamic Texture wrapping/filtering if it's loaded from disk and handled by the ResourceManager.
// You must delete it yourself after you've added it to all the Entities you want.
Sprite* f_spr = new Sprite();
f_spr->setupSprite("assets/grayscale.tga", 0.5f, 0.5f, 1.0f, 1.0f, 1, 2); // filename, pivot.x, pivot.y, uvdim.x, uvdim.y, filter, wrap<|fim▁hole|> child1_entity->position = Point2(100, -100); // position relative to parent (default_entity)
child1_entity->addSprite(f_spr);
delete f_spr;
// Create an Entity that's going to be a Child of default_entity.
// Easiest way to create a Sprite with sensible defaults. @see Sprite::setupSprite()
child2_entity = new BasicEntity();
child2_entity->addSprite("assets/grayscale.tga");
child2_entity->sprite()->color = RED; // red
child2_entity->position = Point2(64, 64); // position relative to parent (child1_entity)
// An example of using a SpriteSheet ("animated texture").
// Remember you can also animate UV's of any Sprite (uvoffset).
animated_entity = new BasicEntity();
animated_entity->addLine("assets/default.line"); // Add a line (default line fits nicely)
animated_entity->addSpriteSheet("assets/spritesheet.tga", 4, 4); // divide Texture in 4x4 slices
animated_entity->position = Point2(SWIDTH/3*2, SHEIGHT/2);
// Create a UI entity
ui_element = new BasicEntity();
//ui_element->position = Point2(SWIDTH-150, 20); // sticks to camera in update()
// filter + wrap inherited from default_entity above (is per texturename. "assets/default.tga" already loaded).
ui_element->addSprite("assets/default.tga", 0.5f, 0.0f); // Default texture. Pivot point top middle. Pivot(0,0) is top left.
ui_element->sprite()->size = Point2(256, 64); // texture is 512x512. Make Mesh half the width, 1 row of squares (512/8).
ui_element->sprite()->uvdim = Point2(0.5f, 0.125f); // UV 1/8 of the height.
ui_element->sprite()->uvoffset = Point2(0.0f, 0.0f); // Show bottom row. UV(0,0) is bottom left.
// create a tree-structure to send to the Renderer
// by adding them to each other and/or the scene ('this', or one of the layers[])
child1_entity->addChild(child2_entity);
default_entity->addChild(child1_entity);
layers[1]->addChild(default_entity);
layers[1]->addChild(animated_entity);
layers[top_layer]->addChild(ui_element);
}
Scene01::~Scene01()
{
// deconstruct and delete the Tree
child1_entity->removeChild(child2_entity);
default_entity->removeChild(child1_entity);
layers[1]->removeChild(default_entity);
layers[1]->removeChild(animated_entity);
layers[top_layer]->removeChild(ui_element);
delete animated_entity;
delete child2_entity;
delete child1_entity;
delete default_entity;
delete ui_element;
}
void Scene01::update(float deltaTime)
{
// ###############################################################
// Make SuperScene do what it needs to do
// - Escape key stops Scene
// - Move Camera
// ###############################################################
SuperScene::update(deltaTime);
SuperScene::moveCamera(deltaTime);
// ###############################################################
// Mouse cursor in screen coordinates
// ###############################################################
int mousex = input()->getMouseX();
int mousey = input()->getMouseY();
std::string cursortxt = "cursor (";
cursortxt.append(std::to_string(mousex));
cursortxt.append(",");
cursortxt.append(std::to_string(mousey));
cursortxt.append(")");
text[9]->message(cursortxt);
// ###############################################################
// Rotate default_entity
// ###############################################################
default_entity->rotation -= 90 * DEG_TO_RAD * deltaTime; // 90 deg. per sec.
if (default_entity->rotation < TWO_PI) { default_entity->rotation += TWO_PI; }
// ###############################################################
// alpha child1_entity + child2_entity
// ###############################################################
static float counter = 0;
child1_entity->sprite()->color.a = abs(sin(counter)*255);
child2_entity->sprite()->color.a = abs(cos(counter)*255);
counter+=deltaTime/2; if (counter > TWO_PI) { counter = 0; }
// ###############################################################
// Animate animated_entity
// ###############################################################
animated_entity->rotation += 22.5 * DEG_TO_RAD * deltaTime;
if (animated_entity->rotation > -TWO_PI) { animated_entity->rotation -= TWO_PI; }
static int f = 0;
if (f > 15) { f = 0; }
animated_entity->sprite()->frame(f);
if (t.seconds() > 0.25f) {
static RGBAColor rgb = RED;
animated_entity->sprite()->color = rgb;
rgb = Color::rotate(rgb, 0.025f);
f++;
t.start();
}
// ###############################################################
// ui_element uvoffset
// ###############################################################
static float xoffset = 0.0f;
xoffset += deltaTime / 2;
if (input()->getKey( GLFW_KEY_SPACE )) {
xoffset = 0.0f;
}
ui_element->sprite()->uvoffset.x = xoffset;
ui_element->position = Point2(camera()->position.x + SWIDTH/2 - 150, camera()->position.y - SHEIGHT/2 + 20);
}<|fim▁end|> | f_spr->color = GREEN; // green
child1_entity = new BasicEntity(); |
<|file_name|>comprehension.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, traceback, Ice, threading, time, os
import IceStorm
# Ctrl+c handling
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
# Qt interface
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtSvg import *
# Check that RoboComp has been correctly detected
ROBOCOMP = ''
try:
ROBOCOMP = os.environ['ROBOCOMP']
except:
pass
if len(ROBOCOMP)<1:
print 'ROBOCOMP environment variable not set! Exiting.'
sys.exit()
Ice.loadSlice("-I"+ROBOCOMP+"/interfaces/ --all "+ROBOCOMP+"/interfaces/ASRPublish.ice")
import RoboCompASRPublish
Ice.loadSlice("-I"+ROBOCOMP+"/interfaces/ --all "+ROBOCOMP+"/interfaces/ASRCommand.ice")
import RoboCompASRCommand
Ice.loadSlice("-I"+ROBOCOMP+"/interfaces/ --all "+ROBOCOMP+"/interfaces/ASRComprehension.ice")
import RoboCompASRComprehension
class MainClass(object):
def __init__(self, commandTopic):
print 'Esta clase podria ser la clase principal del programa'
self.commandTopic = commandTopic
def newText(self, text, current=None):
print 'Nos ha llegado', text
command = RoboCompASRCommand.Command()
partes = text.split()
if len(partes) > 0:
command.action = partes[0]
if len(partes) > 1:
command.complements = partes[1:]
print 'Action', command.action, '(', command.complements,')'
else:
print 'Action', command.action
self.commandTopic.newCommand(command)
else:
print 'Comando vacio?'
def mode(self, text):
print 'Nos llega por la interfaz ASRComprehension', text
class ASRPublishTopicI (RoboCompASRPublish.ASRPublish):
def __init__(self, _handler):
self.handler = _handler
def newText(self, text, current=None):
self.handler.newText(text)
class ASRComprehensionI (RoboCompASRComprehension.ASRComprehension):
def __init__(self, _handler):
self.handler = _handler
def mode(self, text, current=None):
self.handler.mode(text)
class Server (Ice.Application):
def run (self, argv):
status = 0
try:
# Proxy to publish ASRCommand
proxy = self.communicator().getProperties().getProperty("IceStormProxy")
obj = self.communicator().stringToProxy(proxy)
topicManager = IceStorm.TopicManagerPrx.checkedCast(obj)
try:
topic = False
topic = topicManager.retrieve("ASRCommand")
except:
pass
while not topic:
try:
topic = topicManager.retrieve("ASRCommand")
except IceStorm.NoSuchTopic:
try:
topic = topicManager.create("ASRCommand")
except:
print 'Another client created the ASRCommand topic... ok'
pub = topic.getPublisher().ice_oneway()
commandTopic = RoboCompASRCommand.ASRCommandPrx.uncheckedCast(pub)
mainObject = MainClass(commandTopic)
# Subscribe to ASRPublishTopic
proxy = self.communicator().getProperties().getProperty( "IceStormProxy")
topicManager = IceStorm.TopicManagerPrx.checkedCast(self.communicator().stringToProxy(proxy))
adapterT = self.communicator().createObjectAdapter("ASRPublishTopic")
asrTopic = ASRPublishTopicI(mainObject)
proxyT = adapterT.addWithUUID(asrTopic).ice_oneway()
ASRPublishTopic_subscription = False
while not ASRPublishTopic_subscription:
try:
topic = topicManager.retrieve("ASRPublishTopic")
qos = {}
topic.subscribeAndGetPublisher(qos, proxyT)
adapterT.activate()
ASRPublishTopic_subscription = True
except IceStorm.NoSuchTopic:
print "Error! No topic found! Sleeping for a while..."
time.sleep(1)<|fim▁hole|> print 'ASRPublishTopic subscription ok'
# Implement ASRComprehension
asrcomprehensionI = ASRComprehensionI(mainObject)
adapterASRComprehension = self.communicator().createObjectAdapter('ASRComprehension')
adapterASRComprehension.add(asrcomprehensionI, self.communicator().stringToIdentity('asrcomprehension'))
adapterASRComprehension.activate()
self.communicator().waitForShutdown()
except:
traceback.print_exc()
status = 1
if self.communicator():
try:
self.communicator().destroy()
except:
traceback.print_exc()
status = 1
Server( ).main(sys.argv)<|fim▁end|> | |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>#To-DO:NEXT: Write the show_keys email command [admin level]
#To-Do:NEXT: Write the other templates
#To-Do:NEXT: write the connect command [user level]
#TO-DO:NEXT: Fix subject bug.
#To-DO:NEXT: Make the html emails look prettier somehow.
#listening script
from core import *
import codebase
<|fim▁hole|>import poplib
import email
import email.header
import sched, time
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
orders = []
log = []
e = str(raw_input('Enter the email id :'))
p = str(raw_input('Enter the password : '))
def send_email(user, body):
fromaddr = e
to = user
body = unicode(body)
msg = MIMEMultipart('alternative')
msg['From'] = str(fromaddr)
msg['To'] = str(to)
msg['Subject'] = 'EMS' #not working. Why?
chunk = MIMEText(body,'html')
msg.attach(chunk)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(e, p)
server.sendmail(e, user, chunk.as_string())
server.quit()
def check_for_orders(emailid, password):
#we only check for max 10 orders every refresh
max_orders = 10
#log into pop
pop_conn = poplib.POP3_SSL('pop.gmail.com')
pop_conn.user(emailid)
pop_conn.pass_(password)
#counting number of messages
msgcount = pop_conn.stat()[0]
#main loop checking the subjects and adding them to orders list
for i in range(msgcount, max(0, msgcount - max_orders), -1):
response, msg_as_list, size = pop_conn.retr(i)
msg = email.message_from_string('\r\n'.join(msg_as_list))
if "subject" in msg:
decheader = email.header.decode_header(msg["subject"])
subject = decheader[0][0]
charset = decheader[0][1]
if charset:
subject = subject.decode(charset)
orders.append(subject)
orders.reverse() #for sequence
pop_conn.quit()
def mainloop(emailid, password):
check_for_orders(emailid, password)
if orders == []:
log.append('Searching for orders...')
else:
for items in orders:
#admin command to create key -> crea [x] [MASTERKEY]
if str(items)[0:4] == 'CREA':
codebase.keys_create(int(str(items)[5:6]), str(items)[7:len(items)])
log.append(items)
print '\tKey(s) created.'
orders.remove(items)
#admin command to stop the program -> EXIT [MASTERKEY]
if str(items)[0:4] == 'EXIT':
mkey = str(items)[5:len(str(items))]
if codebase.inv.key_mcheck(mkey) is 1:
exit()
#user command to activate a key -> acti [key] [ph|em|pk]
if str(items)[0:4] == 'acti':
key = str(items)[5:9]
otherstuff = str(items)[10:len(str(items))]
ph = otherstuff.split('|')[0]
em = otherstuff.split('|')[1]
pk = otherstuff.split('|')[2]
for keys in codebase.inv.keys:
if key == keys:
for pkeys in codebase.inv.keys:
try:
if codebase.inv.mappedkeys[key] == pk:
print 'Pkey already exists.' #nevergonnahappen
except KeyError:
codebase.inv.map_keys(key, ph, em)
codebase.inv.map_pkey(key, pk)
log.append(items)
orders.remove(items)
#user command to add item -> add [key] [name|pricepu|quan|units|pkey]
if str(items)[0:3] == 'add':
log.append(items)
key = str(items)[4:8]
otherstuff = str(items)[9:len(str(items))]
name = otherstuff.split('|')[0]
pricepu = otherstuff.split('|')[1]
quan = otherstuff.split('|')[2]
units = otherstuff.split('|')[3]
pkey = otherstuff.split('|')[4]
for keys in codebase.inv.keys:
if key == keys:
for pkeys in codebase.inv.pkeys:
try:
if codebase.inv.decpt(codebase.inv.pkeys[key], codebase.inv.enckey, 'NA', 'NA') == pkey:
codebase.inv.add_item(codebase.item(name, pricepu, quan, units, key, 'NA'))
except KeyError:
print '\tOops.'
orders.remove(items)
if str(items)[0:4] == 'show':
key = str(items)[5:9]
try:
useremail = codebase.inv.mappedkeys[key].split('|')[1]
thetext = str(codebase.inv.create_html_Market(key))
body = MIMEText(thetext, 'html')
send_email(useremail, body)
print 'IREmail sent to : ' + str(useremail)
except KeyError:
print '\tOops'
orders.remove(items)
#user command to update item -> updt [key] [label|pricepu|quan|units|pkey]
if str(items)[0:4] == 'updt':
log.append(items)
key = str(items)[5:9]
otherstuff = str(items)[10:len(str(items))]
name = otherstuff.split('|')[0]
pricepu = otherstuff.split('|')[1]
quan = otherstuff.split('|')[2]
units = otherstuff.split('|')[3]
pkey = otherstuff.split('|')[4]
for keys in codebase.inv.keys:
if key == keys:
for pkeys in codebase.inv.pkeys:
try:
if codebase.inv.decpt(codebase.inv.pkeys[key], codebase.inv.enckey, 'NA', 'NA') == pkey:
codebase.inv.update(name, pricepu, quan, key)
print 'item updated'
except KeyError:
print '\tOops.'
orders.remove(items)
if str(items)[0:4] == 'BACK':
log.append(items)
key = str(items)[5:len(str(items))]
if codebase.inv.key_mcheck(key) is 1:
codebase.inv.back_up(key)
print 'Backed up'
orders.remove(items)
if str(items)[0:3] == 'BAN':
log.append(items)
bankey = str(items)[4:8]
masterkey = str(items)[9:len(str(items))]
if codebase.inv.key_mcheck(masterkey) is 1:
codebase.inv.remove_key(bankey, masterkey)
print 'Removed: ' + str(bankey)
orders.remove(items)
s.enter(120,1,mainloop(emailid, password), (sc,)) #change 1 -> 10 or 20
choice = int(raw_input('1 - Start new \n2 - Backup old\nEnter choice : '))
if choice is 1:
initialMkey = str(raw_input('Set the MASTERKEY: '))
codebase.int_m(initialMkey)
print 'Masterkey Created. EMS service online. Receiving Orders'
log.append('Masterkey Created. EMS service started. Receiving Orders:')
if choice is 2:
old_key = str(raw_input('Enter mkey of the backup : '))
codebase.inv.restore(old_key)
else:
print 'Unrecognized command'
s = sched.scheduler(time.time, time.sleep)
s.enter(120,1,mainloop(e, p), (sc,))
s.run<|fim▁end|> | |
<|file_name|>test_reload_button_provider.py<|end_file_name|><|fim▁begin|>import pytest
from cfme.containers.provider import ContainersProvider
from utils import testgen, version
from cfme.web_ui import toolbar as tb
from utils.appliance.implementations.ui import navigate_to
pytestmark = [
pytest.mark.uncollectif(
lambda: version.current_version() < "5.6"),
pytest.mark.usefixtures('setup_provider'),
pytest.mark.tier(2)]
pytest_generate_tests = testgen.generate([ContainersProvider], scope='function')
@pytest.mark.polarion('CMP-9878')
def test_reload_button_provider(provider):
""" This test verifies the data integrity of the fields in
the Relationships table after clicking the "reload"
button. Fields that are being verified as part of provider.validate.stats():
Projects, Routes, Container Services, Replicators, Pods, Containers, and Nodes.
Images are being validated separately, since the total
number of images in CFME 5.7 includes all images from the OSE registry as well
as the images that are being created from the running pods. The images are searched
according to the @sha. Image Registries are also validated separately.<|fim▁hole|> tb.select('Reload Current Display')
provider.validate_stats(ui=True)
list_img_from_registry = provider.mgmt.list_image()
list_img_from_registry_splitted = [i.id.split(
'@sha256:')[-1] for i in list_img_from_registry]
list_img_from_openshift = provider.mgmt.list_image_openshift()
list_img_from_openshift_splitted = [d['name']
for d in list_img_from_openshift]
list_img_from_openshift_parsed = [i[7:].split(
'@sha256:')[-1] for i in list_img_from_openshift_splitted]
list_img_from_registry_splitted_new = set(list_img_from_registry_splitted)
list_img_from_openshift_parsed_new = set(list_img_from_openshift_parsed)
list_img_from_openshift_parsed_new.update(list_img_from_registry_splitted_new)
num_img_in_cfme = provider.num_image()
# TODO Fix num_image_ui()
num_img_cfme_56 = len(provider.mgmt.list_image())
num_img_cfme_57 = len(list_img_from_openshift_parsed_new)
assert num_img_in_cfme == version.pick({version.LOWEST: num_img_cfme_56,
'5.7': num_img_cfme_57})
# validate the number of image registries
list_all_rgstr = provider.mgmt.list_image_registry()
list_all_rgstr_revised = [i.host for i in list_all_rgstr]
list_all_rgstr_new = filter(lambda ch: 'openshift3' not in ch, list_all_rgstr_revised)
num_rgstr_in_cfme = provider.summary.relationships.image_registries.value
assert len(list_all_rgstr_new) == num_rgstr_in_cfme<|fim▁end|> | """
navigate_to(provider, 'Details') |
<|file_name|>origins.go<|end_file_name|><|fim▁begin|>package cdn
// 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"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// OriginsClient is the use these APIs to manage Azure CDN resources through the Azure Resource Manager. You must make
// sure that requests made to these resources are secure.
type OriginsClient struct {
BaseClient
}
// NewOriginsClient creates an instance of the OriginsClient client.
func NewOriginsClient(subscriptionID string) OriginsClient {
return NewOriginsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewOriginsClientWithBaseURI creates an instance of the OriginsClient client.
func NewOriginsClientWithBaseURI(baseURI string, subscriptionID string) OriginsClient {
return OriginsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Get gets an existing origin within an endpoint.
//
// resourceGroupName is name of the Resource group within the Azure subscription. profileName is name of the CDN
// profile which is unique within the resource group. endpointName is name of the endpoint under the profile which
// is unique globally. originName is name of the origin which is unique within the endpoint.
func (client OriginsClient) Get(ctx context.Context, resourceGroupName string, profileName string, endpointName string, originName string) (result Origin, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("cdn.OriginsClient", "Get", err.Error())
}
req, err := client.GetPreparer(ctx, resourceGroupName, profileName, endpointName, originName)
if err != nil {
err = autorest.NewErrorWithError(err, "cdn.OriginsClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cdn.OriginsClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cdn.OriginsClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client OriginsClient) GetPreparer(ctx context.Context, resourceGroupName string, profileName string, endpointName string, originName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"endpointName": autorest.Encode("path", endpointName),
"originName": autorest.Encode("path", originName),
"profileName": autorest.Encode("path", profileName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-02"
queryParameters := map[string]interface{}{
"api-version": APIVersion,<|fim▁hole|> }
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client OriginsClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client OriginsClient) GetResponder(resp *http.Response) (result Origin, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByEndpoint lists all of the existing origins within an endpoint.
//
// resourceGroupName is name of the Resource group within the Azure subscription. profileName is name of the CDN
// profile which is unique within the resource group. endpointName is name of the endpoint under the profile which
// is unique globally.
func (client OriginsClient) ListByEndpoint(ctx context.Context, resourceGroupName string, profileName string, endpointName string) (result OriginListResultPage, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("cdn.OriginsClient", "ListByEndpoint", err.Error())
}
result.fn = client.listByEndpointNextResults
req, err := client.ListByEndpointPreparer(ctx, resourceGroupName, profileName, endpointName)
if err != nil {
err = autorest.NewErrorWithError(err, "cdn.OriginsClient", "ListByEndpoint", nil, "Failure preparing request")
return
}
resp, err := client.ListByEndpointSender(req)
if err != nil {
result.olr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "cdn.OriginsClient", "ListByEndpoint", resp, "Failure sending request")
return
}
result.olr, err = client.ListByEndpointResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cdn.OriginsClient", "ListByEndpoint", resp, "Failure responding to request")
}
return
}
// ListByEndpointPreparer prepares the ListByEndpoint request.
func (client OriginsClient) ListByEndpointPreparer(ctx context.Context, resourceGroupName string, profileName string, endpointName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"endpointName": autorest.Encode("path", endpointName),
"profileName": autorest.Encode("path", profileName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-02"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByEndpointSender sends the ListByEndpoint request. The method will close the
// http.Response Body if it receives an error.
func (client OriginsClient) ListByEndpointSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListByEndpointResponder handles the response to the ListByEndpoint request. The method always
// closes the http.Response Body.
func (client OriginsClient) ListByEndpointResponder(resp *http.Response) (result OriginListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByEndpointNextResults retrieves the next set of results, if any.
func (client OriginsClient) listByEndpointNextResults(lastResults OriginListResult) (result OriginListResult, err error) {
req, err := lastResults.originListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "cdn.OriginsClient", "listByEndpointNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByEndpointSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "cdn.OriginsClient", "listByEndpointNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByEndpointResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "cdn.OriginsClient", "listByEndpointNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByEndpointComplete enumerates all values, automatically crossing page boundaries as required.
func (client OriginsClient) ListByEndpointComplete(ctx context.Context, resourceGroupName string, profileName string, endpointName string) (result OriginListResultIterator, err error) {
result.page, err = client.ListByEndpoint(ctx, resourceGroupName, profileName, endpointName)
return
}
// Update updates an existing origin within an endpoint.
//
// resourceGroupName is name of the Resource group within the Azure subscription. profileName is name of the CDN
// profile which is unique within the resource group. endpointName is name of the endpoint under the profile which
// is unique globally. originName is name of the origin which is unique within the endpoint. originUpdateProperties
// is origin properties
func (client OriginsClient) Update(ctx context.Context, resourceGroupName string, profileName string, endpointName string, originName string, originUpdateProperties OriginUpdateParameters) (result OriginsUpdateFuture, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("cdn.OriginsClient", "Update", err.Error())
}
req, err := client.UpdatePreparer(ctx, resourceGroupName, profileName, endpointName, originName, originUpdateProperties)
if err != nil {
err = autorest.NewErrorWithError(err, "cdn.OriginsClient", "Update", nil, "Failure preparing request")
return
}
result, err = client.UpdateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "cdn.OriginsClient", "Update", result.Response(), "Failure sending request")
return
}
return
}
// UpdatePreparer prepares the Update request.
func (client OriginsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, profileName string, endpointName string, originName string, originUpdateProperties OriginUpdateParameters) (*http.Request, error) {
pathParameters := map[string]interface{}{
"endpointName": autorest.Encode("path", endpointName),
"originName": autorest.Encode("path", originName),
"profileName": autorest.Encode("path", profileName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-02"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPatch(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}", pathParameters),
autorest.WithJSON(originUpdateProperties),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client OriginsClient) UpdateSender(req *http.Request) (future OriginsUpdateFuture, err error) {
sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
future.Future = azure.NewFuture(req)
future.req = req
_, err = future.Done(sender)
if err != nil {
return
}
err = autorest.Respond(future.Response(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted))
return
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client OriginsClient) UpdateResponder(resp *http.Response) (result Origin, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}<|fim▁end|> | |
<|file_name|>fixed.rs<|end_file_name|><|fim▁begin|>// This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use Container;
use Widget;
use ffi;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct Fixed(Object<ffi::GtkFixed>): Container, Widget;
match fn {
get_type => || ffi::gtk_fixed_get_type(),
}
}
impl Fixed {
pub fn new() -> Fixed {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_fixed_new()).downcast_unchecked()
}
}
}
pub trait FixedExt {<|fim▁hole|> fn move_<P: IsA<Widget>>(&self, widget: &P, x: i32, y: i32);
fn put<P: IsA<Widget>>(&self, widget: &P, x: i32, y: i32);
fn get_child_x<T: IsA<Widget>>(&self, item: &T) -> i32;
fn set_child_x<T: IsA<Widget>>(&self, item: &T, x: i32);
fn get_child_y<T: IsA<Widget>>(&self, item: &T) -> i32;
fn set_child_y<T: IsA<Widget>>(&self, item: &T, y: i32);
}
impl<O: IsA<Fixed> + IsA<Container>> FixedExt for O {
fn move_<P: IsA<Widget>>(&self, widget: &P, x: i32, y: i32) {
unsafe {
ffi::gtk_fixed_move(self.to_glib_none().0, widget.to_glib_none().0, x, y);
}
}
fn put<P: IsA<Widget>>(&self, widget: &P, x: i32, y: i32) {
unsafe {
ffi::gtk_fixed_put(self.to_glib_none().0, widget.to_glib_none().0, x, y);
}
}
fn get_child_x<T: IsA<Widget>>(&self, item: &T) -> i32 {
let mut value = Value::from(&0);
unsafe {
ffi::gtk_container_child_get_property(self.to_glib_none().0, item.to_glib_none().0, "x".to_glib_none().0, value.to_glib_none_mut().0);
}
value.get().unwrap()
}
fn set_child_x<T: IsA<Widget>>(&self, item: &T, x: i32) {
unsafe {
ffi::gtk_container_child_set_property(self.to_glib_none().0, item.to_glib_none().0, "x".to_glib_none().0, Value::from(&x).to_glib_none().0);
}
}
fn get_child_y<T: IsA<Widget>>(&self, item: &T) -> i32 {
let mut value = Value::from(&0);
unsafe {
ffi::gtk_container_child_get_property(self.to_glib_none().0, item.to_glib_none().0, "y".to_glib_none().0, value.to_glib_none_mut().0);
}
value.get().unwrap()
}
fn set_child_y<T: IsA<Widget>>(&self, item: &T, y: i32) {
unsafe {
ffi::gtk_container_child_set_property(self.to_glib_none().0, item.to_glib_none().0, "y".to_glib_none().0, Value::from(&y).to_glib_none().0);
}
}
}<|fim▁end|> | |
<|file_name|>website.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2015 Serv. Tecnol. Avanzados (http://www.serviciosbaeza.com)
# Pedro M. Baeza <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.<|fim▁hole|>#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import models, api
class Website(models.Model):
_inherit = 'website'
@api.multi
def sale_get_order(self, force_create=False, code=None,
update_pricelist=None):
res = super(Website, self).sale_get_order(
force_create=force_create, code=code,
update_pricelist=update_pricelist)
return res if res is not None else self.env['sale.order']<|fim▁end|> | |
<|file_name|>DepthOfField.cpp<|end_file_name|><|fim▁begin|>//--------------------------------------------------------------------------------------
// File: DepthOfField.cpp
//
// Depth of field
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "DXUT.h"
#include "DXUTsettingsdlg.h"
#include "DXUTcamera.h"
#include "SDKmisc.h"
#include "resource.h"
//#define DEBUG_VS // Uncomment this line to debug vertex shaders
//#define DEBUG_PS // Uncomment this line to debug pixel shaders
//--------------------------------------------------------------------------------------
// Vertex format
//--------------------------------------------------------------------------------------
struct VERTEX
{
D3DXVECTOR4 pos;
DWORD clr;
D3DXVECTOR2 tex1;
D3DXVECTOR2 tex2;
D3DXVECTOR2 tex3;
D3DXVECTOR2 tex4;
D3DXVECTOR2 tex5;
D3DXVECTOR2 tex6;
static const DWORD FVF;
};
const DWORD VERTEX::FVF = D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX6;
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
ID3DXFont* g_pFont = NULL; // Font for drawing text
ID3DXSprite* g_pTextSprite = NULL; // Sprite for batching draw text calls
CFirstPersonCamera g_Camera; // A model viewing camera
bool g_bShowHelp = true; // If true, it renders the UI control text
CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs
CD3DSettingsDlg g_SettingsDlg; // Device settings dialog
CDXUTDialog g_HUD; // dialog for standard controls
CDXUTDialog g_SampleUI; // dialog for sample specific controls
VERTEX g_Vertex[4];
LPDIRECT3DTEXTURE9 g_pFullScreenTexture;
LPD3DXRENDERTOSURFACE g_pRenderToSurface;
LPDIRECT3DSURFACE9 g_pFullScreenTextureSurf;
LPD3DXMESH g_pScene1Mesh;
LPDIRECT3DTEXTURE9 g_pScene1MeshTexture;
LPD3DXMESH g_pScene2Mesh;
LPDIRECT3DTEXTURE9 g_pScene2MeshTexture;
int g_nCurrentScene;
LPD3DXEFFECT g_pEffect;
D3DXVECTOR4 g_vFocalPlane;
double g_fChangeTime;
int g_nShowMode;
DWORD g_dwBackgroundColor;
D3DVIEWPORT9 g_ViewportFB;
D3DVIEWPORT9 g_ViewportOffscreen;
FLOAT g_fBlurConst;
DWORD g_TechniqueIndex;
D3DXHANDLE g_hFocalPlane;
D3DXHANDLE g_hWorld;
D3DXHANDLE g_hWorldView;
D3DXHANDLE g_hWorldViewProjection;
D3DXHANDLE g_hMeshTexture;
D3DXHANDLE g_hTechWorldWithBlurFactor;
D3DXHANDLE g_hTechShowBlurFactor;
D3DXHANDLE g_hTechShowUnmodified;
D3DXHANDLE g_hTech[5];
static CHAR* g_TechniqueNames[] =
{
"UsePS20ThirteenLookups",
"UsePS20SevenLookups",
"UsePS20SixTexcoords"
};
const DWORD g_TechniqueCount = sizeof( g_TechniqueNames ) / sizeof( LPCSTR );
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
#define IDC_TOGGLEFULLSCREEN 1
#define IDC_TOGGLEREF 3
#define IDC_CHANGEDEVICE 4
#define IDC_CHANGE_SCENE 5
#define IDC_CHANGE_TECHNIQUE 6
#define IDC_SHOW_BLUR 7
#define IDC_CHANGE_BLUR 8
#define IDC_CHANGE_FOCAL 9
#define IDC_CHANGE_BLUR_STATIC 10
#define IDC_SHOW_UNBLURRED 11
#define IDC_SHOW_NORMAL 12
#define IDC_CHANGE_FOCAL_STATIC 13
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed,
void* pUserContext );
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext );
HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext );
HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext );
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext );
void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext );
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
void* pUserContext );
void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext );
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext );
void CALLBACK OnLostDevice( void* pUserContext );
void CALLBACK OnDestroyDevice( void* pUserContext );
void InitApp();
HRESULT LoadMesh( IDirect3DDevice9* pd3dDevice, WCHAR* strFileName, ID3DXMesh** ppMesh );
void RenderText();
void SetupQuad( const D3DSURFACE_DESC* pBackBufferSurfaceDesc );
HRESULT UpdateTechniqueSpecificVariables( const D3DSURFACE_DESC* pBackBufferSurfaceDesc );
//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
INT WINAPI wWinMain( HINSTANCE, HINSTANCE, LPWSTR, int )
{
// Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
// DXUT will create and use the best device (either D3D9 or D3D10)
// that is available on the system depending on which D3D callbacks are set below
// Set DXUT callbacks
DXUTSetCallbackD3D9DeviceAcceptable( IsDeviceAcceptable );
DXUTSetCallbackD3D9DeviceCreated( OnCreateDevice );
DXUTSetCallbackD3D9DeviceReset( OnResetDevice );
DXUTSetCallbackD3D9FrameRender( OnFrameRender );
DXUTSetCallbackD3D9DeviceLost( OnLostDevice );
DXUTSetCallbackD3D9DeviceDestroyed( OnDestroyDevice );
DXUTSetCallbackMsgProc( MsgProc );
DXUTSetCallbackKeyboard( KeyboardProc );
DXUTSetCallbackFrameMove( OnFrameMove );
DXUTSetCallbackDeviceChanging( ModifyDeviceSettings );
DXUTSetCursorSettings( true, true );
InitApp();
DXUTInit( true, true ); // Parse the command line and show msgboxes
DXUTSetHotkeyHandling( true, true, true );
DXUTCreateWindow( L"DepthOfField" );
DXUTCreateDevice( true, 640, 480 );
DXUTMainLoop();
return DXUTGetExitCode();
}
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
void InitApp()
{
g_pFont = NULL;
g_pFullScreenTexture = NULL;
g_pFullScreenTextureSurf = NULL;
g_pRenderToSurface = NULL;
g_pEffect = NULL;
g_vFocalPlane = D3DXVECTOR4( 0.0f, 0.0f, 1.0f, -2.5f );
g_fChangeTime = 0.0f;
g_pScene1Mesh = NULL;
g_pScene1MeshTexture = NULL;
g_pScene2Mesh = NULL;
g_pScene2MeshTexture = NULL;
g_nCurrentScene = 1;
g_nShowMode = 0;
g_bShowHelp = TRUE;
g_dwBackgroundColor = 0x00003F3F;
g_fBlurConst = 4.0f;
g_TechniqueIndex = 0;
g_hFocalPlane = NULL;
g_hWorld = NULL;
g_hWorldView = NULL;
g_hWorldViewProjection = NULL;
g_hMeshTexture = NULL;
g_hTechWorldWithBlurFactor = NULL;
g_hTechShowBlurFactor = NULL;
g_hTechShowUnmodified = NULL;
ZeroMemory( g_hTech, sizeof( g_hTech ) );
// Initialize dialogs
g_SettingsDlg.Init( &g_DialogResourceManager );
g_HUD.Init( &g_DialogResourceManager );
g_SampleUI.Init( &g_DialogResourceManager );
g_HUD.SetCallback( OnGUIEvent ); int iY = 10;
g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, iY, 125, 22 );
g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 35, iY += 24, 125, 22 );
g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY += 24, 125, 22, VK_F2 );
g_SampleUI.SetCallback( OnGUIEvent ); iY = 10;
g_SampleUI.AddButton( IDC_CHANGE_SCENE, L"Change Scene", 35, iY += 24, 125, 22, 'P' );
g_SampleUI.AddButton( IDC_CHANGE_TECHNIQUE, L"Change Technique", 35, iY += 24, 125, 22, 'N' );
g_SampleUI.AddRadioButton( IDC_SHOW_NORMAL, 1, L"Show Normal", 35, iY += 24, 125, 22, true );
g_SampleUI.AddRadioButton( IDC_SHOW_BLUR, 1, L"Show Blur Factor", 35, iY += 24, 125, 22 );
g_SampleUI.AddRadioButton( IDC_SHOW_UNBLURRED, 1, L"Show Unblurred", 35, iY += 24, 125, 22 );
iY += 24;
WCHAR sz[100];
swprintf_s( sz, 100, L"Focal Distance: %0.2f", -g_vFocalPlane.w ); sz[99] = 0;
g_SampleUI.AddStatic( IDC_CHANGE_FOCAL_STATIC, sz, 35, iY += 24, 125, 22 );
g_SampleUI.AddSlider( IDC_CHANGE_FOCAL, 50, iY += 24, 100, 22, 0, 100, ( int )( -g_vFocalPlane.w * 10.0f ) );
iY += 24;
swprintf_s( sz, 100, L"Blur Factor: %0.2f", g_fBlurConst ); sz[99] = 0;
g_SampleUI.AddStatic( IDC_CHANGE_BLUR_STATIC, sz, 35, iY += 24, 125, 22 );
g_SampleUI.AddSlider( IDC_CHANGE_BLUR, 50, iY += 24, 100, 22, 0, 100, ( int )( g_fBlurConst * 10.0f ) );
}
//--------------------------------------------------------------------------------------
// Rejects any D3D9 devices that aren't acceptable to the app by returning false
//--------------------------------------------------------------------------------------
bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat,
D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext )
{
// Skip backbuffer formats that don't support alpha blending
IDirect3D9* pD3D = DXUTGetD3D9Object();
if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat ) ) )
return false;
// Must support pixel shader 2.0
if( pCaps->PixelShaderVersion < D3DPS_VERSION( 2, 0 ) )
return false;
return true;
}
//--------------------------------------------------------------------------------------
// Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext )
{
assert( DXUT_D3D9_DEVICE == pDeviceSettings->ver );
HRESULT hr;
IDirect3D9* pD3D = DXUTGetD3D9Object();
D3DCAPS9 caps;
V( pD3D->GetDeviceCaps( pDeviceSettings->d3d9.AdapterOrdinal,
pDeviceSettings->d3d9.DeviceType,
&caps ) );
// If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW
// then switch to SWVP.
if( ( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) == 0 ||
caps.VertexShaderVersion < D3DVS_VERSION( 1, 1 ) )
{
pDeviceSettings->d3d9.BehaviorFlags = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
}
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
#ifdef DEBUG_VS
if( pDeviceSettings->d3d9.DeviceType != D3DDEVTYPE_REF )
{
pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING;
pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_PUREDEVICE;
pDeviceSettings->d3d9.BehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
}
#endif
#ifdef DEBUG_PS
pDeviceSettings->d3d9.DeviceType = D3DDEVTYPE_REF;
#endif
// For the first device created if its a REF device, optionally display a warning dialog box
static bool s_bFirstTime = true;
if( s_bFirstTime )
{
s_bFirstTime = false;
if( pDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF )
DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver );
}
return true;
}
//--------------------------------------------------------------------------------------
// Create any D3D9 resources that will live through a device reset (D3DPOOL_MANAGED)
// and aren't tied to the back buffer size
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext )
{
WCHAR str[MAX_PATH];
HRESULT hr;
V_RETURN( g_DialogResourceManager.OnD3D9CreateDevice( pd3dDevice ) );
V_RETURN( g_SettingsDlg.OnD3D9CreateDevice( pd3dDevice ) );
// Initialize the font
V_RETURN( D3DXCreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
L"Arial", &g_pFont ) );
// Load the meshs
V_RETURN( LoadMesh( pd3dDevice, TEXT( "tiger\\tiger.x" ), &g_pScene1Mesh ) );
V_RETURN( LoadMesh( pd3dDevice, TEXT( "misc\\sphere.x" ), &g_pScene2Mesh ) );
// Load the mesh textures
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"tiger\\tiger.bmp" ) );
V_RETURN( D3DXCreateTextureFromFile( pd3dDevice, str, &g_pScene1MeshTexture ) );
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"earth\\earth.bmp" ) );
V_RETURN( D3DXCreateTextureFromFile( pd3dDevice, str, &g_pScene2MeshTexture ) );
DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE;
#if defined( DEBUG ) || defined( _DEBUG )
dwShaderFlags |= D3DXSHADER_DEBUG;
#endif
#ifdef DEBUG_VS
dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
#endif
#ifdef DEBUG_PS
dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
#endif
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"DepthOfField.fx" ) );
V_RETURN( D3DXCreateEffectFromFile( pd3dDevice, str, NULL, NULL, dwShaderFlags,
NULL, &g_pEffect, NULL ) );
return S_OK;
}
//--------------------------------------------------------------------------------------
// This function loads the mesh and ensures the mesh has normals; it also optimizes the
// mesh for the graphics card's vertex cache, which improves performance by organizing
// the internal triangle list for less cache misses.
//--------------------------------------------------------------------------------------
HRESULT LoadMesh( IDirect3DDevice9* pd3dDevice, WCHAR* strFileName, ID3DXMesh** ppMesh )
{
ID3DXMesh* pMesh = NULL;
WCHAR str[MAX_PATH];
HRESULT hr;
// Load the mesh with D3DX and get back a ID3DXMesh*. For this
// sample we'll ignore the X file's embedded materials since we know
// exactly the model we're loading. See the mesh samples such as
// "OptimizedMesh" for a more generic mesh loading example.
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, strFileName ) );
V_RETURN( D3DXLoadMeshFromX( str, D3DXMESH_MANAGED, pd3dDevice, NULL, NULL, NULL, NULL, &pMesh ) );
DWORD* rgdwAdjacency = NULL;
// Make sure there are normals which are required for lighting
if( !( pMesh->GetFVF() & D3DFVF_NORMAL ) )
{
ID3DXMesh* pTempMesh;
V( pMesh->CloneMeshFVF( pMesh->GetOptions(),
pMesh->GetFVF() | D3DFVF_NORMAL,
pd3dDevice, &pTempMesh ) );
V( D3DXComputeNormals( pTempMesh, NULL ) );
SAFE_RELEASE( pMesh );
pMesh = pTempMesh;
}
// Optimize the mesh for this graphics card's vertex cache
// so when rendering the mesh's triangle list the vertices will
// cache hit more often so it won't have to re-execute the vertex shader
// on those vertices so it will improve perf.
rgdwAdjacency = new DWORD[pMesh->GetNumFaces() * 3];
if( rgdwAdjacency == NULL )
return E_OUTOFMEMORY;
V( pMesh->GenerateAdjacency( 1e-6f, rgdwAdjacency ) );
V( pMesh->OptimizeInplace( D3DXMESHOPT_VERTEXCACHE, rgdwAdjacency, NULL, NULL, NULL ) );
delete []rgdwAdjacency;
*ppMesh = pMesh;
return S_OK;
}
//--------------------------------------------------------------------------------------
// Create any D3D9 resources that won't live through a device reset (D3DPOOL_DEFAULT)
// or that are tied to the back buffer size
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice,
const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
{
HRESULT hr;
V_RETURN( g_DialogResourceManager.OnD3D9ResetDevice() );
V_RETURN( g_SettingsDlg.OnD3D9ResetDevice() );
if( g_pFont )
V_RETURN( g_pFont->OnResetDevice() );
if( g_pEffect )
V_RETURN( g_pEffect->OnResetDevice() );
// Setup the camera with view & projection matrix
D3DXVECTOR3 vecEye( 1.3f, 1.1f, -3.3f );
D3DXVECTOR3 vecAt ( 0.75f, 0.9f, -2.5f );
g_Camera.SetViewParams( &vecEye, &vecAt );
float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height;
g_Camera.SetProjParams( D3DXToRadian( 60.0f ), fAspectRatio, 0.5f, 100.0f );
pd3dDevice->GetViewport( &g_ViewportFB );
// Backbuffer viewport is identical to frontbuffer, except starting at 0, 0
g_ViewportOffscreen = g_ViewportFB;
g_ViewportOffscreen.X = 0;
g_ViewportOffscreen.Y = 0;
// Create fullscreen renders target texture
hr = D3DXCreateTexture( pd3dDevice, pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height,
1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_pFullScreenTexture );
if( FAILED( hr ) )
{
// Fallback to a non-RT texture
V_RETURN( D3DXCreateTexture( pd3dDevice, pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height,
1, 0, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_pFullScreenTexture ) );
}
D3DSURFACE_DESC desc;
g_pFullScreenTexture->GetSurfaceLevel( 0, &g_pFullScreenTextureSurf );
g_pFullScreenTextureSurf->GetDesc( &desc );
// Create a ID3DXRenderToSurface to help render to a texture on cards
// that don't support render targets
V_RETURN( D3DXCreateRenderToSurface( pd3dDevice, desc.Width, desc.Height,
desc.Format, TRUE, D3DFMT_D16, &g_pRenderToSurface ) );
// clear the surface alpha to 0 so that it does not bleed into a "blurry" background
// this is possible because of the avoidance of blurring in a non-blurred texel
if( SUCCEEDED( g_pRenderToSurface->BeginScene( g_pFullScreenTextureSurf, NULL ) ) )
{
pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, 0x00, 1.0f, 0 );
g_pRenderToSurface->EndScene( 0 );
}
D3DXCOLOR colorWhite( 1.0f, 1.0f, 1.0f, 1.0f );
D3DXCOLOR colorBlack( 0.0f, 0.0f, 0.0f, 1.0f );
D3DXCOLOR colorAmbient( 0.25f, 0.25f, 0.25f, 1.0f );
// Get D3DXHANDLEs to the parameters/techniques that are set every frame so
// D3DX doesn't spend time doing string compares. Doing this likely won't affect
// the perf of this simple sample but it should be done in complex engine.
g_hFocalPlane = g_pEffect->GetParameterByName( NULL, "vFocalPlane" );
g_hWorld = g_pEffect->GetParameterByName( NULL, "mWorld" );
g_hWorldView = g_pEffect->GetParameterByName( NULL, "mWorldView" );
g_hWorldViewProjection = g_pEffect->GetParameterByName( NULL, "mWorldViewProjection" );
g_hMeshTexture = g_pEffect->GetParameterByName( NULL, "MeshTexture" );
g_hTechWorldWithBlurFactor = g_pEffect->GetTechniqueByName( "WorldWithBlurFactor" );
g_hTechShowBlurFactor = g_pEffect->GetTechniqueByName( "ShowBlurFactor" );
g_hTechShowUnmodified = g_pEffect->GetTechniqueByName( "ShowUnmodified" );
for( int i = 0; i < g_TechniqueCount; i++ )
g_hTech[i] = g_pEffect->GetTechniqueByName( g_TechniqueNames[i] );
// Set the vars in the effect that doesn't change each frame
V_RETURN( g_pEffect->SetVector( "MaterialAmbientColor", ( D3DXVECTOR4* )&colorAmbient ) );
V_RETURN( g_pEffect->SetVector( "MaterialDiffuseColor", ( D3DXVECTOR4* )&colorWhite ) );
V_RETURN( g_pEffect->SetTexture( "RenderTargetTexture", g_pFullScreenTexture ) );
// Check if the current technique is valid for the new device/settings
// Start from the current technique, increment until we find one we can use.
DWORD OriginalTechnique = g_TechniqueIndex;
do
{
D3DXHANDLE hTech = g_pEffect->GetTechniqueByName( g_TechniqueNames[g_TechniqueIndex] );
if( SUCCEEDED( g_pEffect->ValidateTechnique( hTech ) ) )
break;
g_TechniqueIndex++;
if( g_TechniqueIndex == g_TechniqueCount )
g_TechniqueIndex = 0;
} while( OriginalTechnique != g_TechniqueIndex );
V_RETURN( UpdateTechniqueSpecificVariables( pBackBufferSurfaceDesc ) );
g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 );
g_HUD.SetSize( 170, 170 );
g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 170, pBackBufferSurfaceDesc->Height - 300 );
g_SampleUI.SetSize( 170, 250 );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Certain parameters need to be specified for specific techniques
//--------------------------------------------------------------------------------------
HRESULT UpdateTechniqueSpecificVariables( const D3DSURFACE_DESC* pBackBufferSurfaceDesc )
{
LPCSTR strInputArrayName, strOutputArrayName;
int nNumKernelEntries;
HRESULT hr;
D3DXHANDLE hAnnotation;
// Create the post-process quad and set the texcoords based on the blur factor
SetupQuad( pBackBufferSurfaceDesc );
// Get the handle to the current technique
D3DXHANDLE hTech = g_pEffect->GetTechniqueByName( g_TechniqueNames[g_TechniqueIndex] );
if( hTech == NULL )
return S_FALSE; // This will happen if the technique doesn't have this annotation
// Get the value of the annotation int named "NumKernelEntries" inside the technique
hAnnotation = g_pEffect->GetAnnotationByName( hTech, "NumKernelEntries" );
if( hAnnotation == NULL )
return S_FALSE; // This will happen if the technique doesn't have this annotation
V_RETURN( g_pEffect->GetInt( hAnnotation, &nNumKernelEntries ) );
// Get the value of the annotation string named "KernelInputArray" inside the technique
hAnnotation = g_pEffect->GetAnnotationByName( hTech, "KernelInputArray" );
if( hAnnotation == NULL )
return S_FALSE; // This will happen if the technique doesn't have this annotation
V_RETURN( g_pEffect->GetString( hAnnotation, &strInputArrayName ) );
// Get the value of the annotation string named "KernelOutputArray" inside the technique
hAnnotation = g_pEffect->GetAnnotationByName( hTech, "KernelOutputArray" );
if( hAnnotation == NULL )
return S_FALSE; // This will happen if the technique doesn't have this annotation
if( FAILED( hr = g_pEffect->GetString( hAnnotation, &strOutputArrayName ) ) )
return hr;
// Create a array to store the input array
D3DXVECTOR2* aKernel = new D3DXVECTOR2[nNumKernelEntries];
if( aKernel == NULL )
return E_OUTOFMEMORY;
// Get the input array
V_RETURN( g_pEffect->GetValue( strInputArrayName, aKernel, sizeof( D3DXVECTOR2 ) * nNumKernelEntries ) );
// Get the size of the texture
D3DSURFACE_DESC desc;
g_pFullScreenTextureSurf->GetDesc( &desc );
// Calculate the scale factor to convert the input array to screen space
FLOAT fWidthMod = g_fBlurConst / ( FLOAT )desc.Width;
FLOAT fHeightMod = g_fBlurConst / ( FLOAT )desc.Height;
// Scale the effect's kernel from pixel space to tex coord space
// In pixel space 1 unit = one pixel and in tex coord 1 unit = width/height of texture
for( int iEntry = 0; iEntry < nNumKernelEntries; iEntry++ )
{
aKernel[iEntry].x *= fWidthMod;
aKernel[iEntry].y *= fHeightMod;
}
// Pass the updated array values to the effect file
V_RETURN( g_pEffect->SetValue( strOutputArrayName, aKernel, sizeof( D3DXVECTOR2 ) * nNumKernelEntries ) );
SAFE_DELETE_ARRAY( aKernel );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Sets up a quad to render the fullscreen render target to the backbuffer
// so it can run a fullscreen pixel shader pass that blurs based
// on the depth of the objects. It set the texcoords based on the blur factor
//--------------------------------------------------------------------------------------
void SetupQuad( const D3DSURFACE_DESC* pBackBufferSurfaceDesc )
{
D3DSURFACE_DESC desc;
g_pFullScreenTextureSurf->GetDesc( &desc );
FLOAT fWidth5 = ( FLOAT )pBackBufferSurfaceDesc->Width - 0.5f;
FLOAT fHeight5 = ( FLOAT )pBackBufferSurfaceDesc->Height - 0.5f;
FLOAT fHalf = g_fBlurConst;
FLOAT fOffOne = fHalf * 0.5f;
FLOAT fOffTwo = fOffOne * sqrtf( 3.0f );
FLOAT fTexWidth1 = ( FLOAT )pBackBufferSurfaceDesc->Width / ( FLOAT )desc.Width;
FLOAT fTexHeight1 = ( FLOAT )pBackBufferSurfaceDesc->Height / ( FLOAT )desc.Height;
FLOAT fWidthMod = 1.0f / ( FLOAT )desc.Width;
FLOAT fHeightMod = 1.0f / ( FLOAT )desc.Height;
// Create vertex buffer.
// g_Vertex[0].tex1 == full texture coverage
// g_Vertex[0].tex2 == full texture coverage, but shifted y by -fHalf*fHeightMod
// g_Vertex[0].tex3 == full texture coverage, but shifted x by -fOffTwo*fWidthMod & y by -fOffOne*fHeightMod
// g_Vertex[0].tex4 == full texture coverage, but shifted x by +fOffTwo*fWidthMod & y by -fOffOne*fHeightMod
// g_Vertex[0].tex5 == full texture coverage, but shifted x by -fOffTwo*fWidthMod & y by +fOffOne*fHeightMod
// g_Vertex[0].tex6 == full texture coverage, but shifted x by +fOffTwo*fWidthMod & y by +fOffOne*fHeightMod
g_Vertex[0].pos = D3DXVECTOR4( fWidth5, -0.5f, 0.0f, 1.0f );
g_Vertex[0].clr = D3DXCOLOR( 0.5f, 0.5f, 0.5f, 0.66666f );
g_Vertex[0].tex1 = D3DXVECTOR2( fTexWidth1, 0.0f );
g_Vertex[0].tex2 = D3DXVECTOR2( fTexWidth1, 0.0f - fHalf * fHeightMod );
g_Vertex[0].tex3 = D3DXVECTOR2( fTexWidth1 - fOffTwo * fWidthMod, 0.0f - fOffOne * fHeightMod );
g_Vertex[0].tex4 = D3DXVECTOR2( fTexWidth1 + fOffTwo * fWidthMod, 0.0f - fOffOne * fHeightMod );
g_Vertex[0].tex5 = D3DXVECTOR2( fTexWidth1 - fOffTwo * fWidthMod, 0.0f + fOffOne * fHeightMod );
g_Vertex[0].tex6 = D3DXVECTOR2( fTexWidth1 + fOffTwo * fWidthMod, 0.0f + fOffOne * fHeightMod );
g_Vertex[1].pos = D3DXVECTOR4( fWidth5, fHeight5, 0.0f, 1.0f );
g_Vertex[1].clr = D3DXCOLOR( 0.5f, 0.5f, 0.5f, 0.66666f );
g_Vertex[1].tex1 = D3DXVECTOR2( fTexWidth1, fTexHeight1 );
g_Vertex[1].tex2 = D3DXVECTOR2( fTexWidth1, fTexHeight1 - fHalf * fHeightMod );
g_Vertex[1].tex3 = D3DXVECTOR2( fTexWidth1 - fOffTwo * fWidthMod, fTexHeight1 - fOffOne * fHeightMod );
g_Vertex[1].tex4 = D3DXVECTOR2( fTexWidth1 + fOffTwo * fWidthMod, fTexHeight1 - fOffOne * fHeightMod );
g_Vertex[1].tex5 = D3DXVECTOR2( fTexWidth1 - fOffTwo * fWidthMod, fTexHeight1 + fOffOne * fHeightMod );
g_Vertex[1].tex6 = D3DXVECTOR2( fTexWidth1 + fOffTwo * fWidthMod, fTexHeight1 + fOffOne * fHeightMod );
g_Vertex[2].pos = D3DXVECTOR4( -0.5f, -0.5f, 0.0f, 1.0f );
g_Vertex[2].clr = D3DXCOLOR( 0.5f, 0.5f, 0.5f, 0.66666f );
g_Vertex[2].tex1 = D3DXVECTOR2( 0.0f, 0.0f );
g_Vertex[2].tex2 = D3DXVECTOR2( 0.0f, 0.0f - fHalf * fHeightMod );
g_Vertex[2].tex3 = D3DXVECTOR2( 0.0f - fOffTwo * fWidthMod, 0.0f - fOffOne * fHeightMod );
g_Vertex[2].tex4 = D3DXVECTOR2( 0.0f + fOffTwo * fWidthMod, 0.0f - fOffOne * fHeightMod );
g_Vertex[2].tex5 = D3DXVECTOR2( 0.0f - fOffTwo * fWidthMod, 0.0f + fOffOne * fHeightMod );
g_Vertex[2].tex6 = D3DXVECTOR2( 0.0f + fOffTwo * fWidthMod, 0.0f + fOffOne * fHeightMod );
g_Vertex[3].pos = D3DXVECTOR4( -0.5f, fHeight5, 0.0f, 1.0f );
g_Vertex[3].clr = D3DXCOLOR( 0.5f, 0.5f, 0.5f, 0.66666f );
g_Vertex[3].tex1 = D3DXVECTOR2( 0.0f, fTexHeight1 );
g_Vertex[3].tex2 = D3DXVECTOR2( 0.0f, fTexHeight1 - fHalf * fHeightMod );
g_Vertex[3].tex3 = D3DXVECTOR2( 0.0f - fOffTwo * fWidthMod, fTexHeight1 - fOffOne * fHeightMod );
g_Vertex[3].tex4 = D3DXVECTOR2( 0.0f + fOffTwo * fWidthMod, fTexHeight1 - fOffOne * fHeightMod );
g_Vertex[3].tex5 = D3DXVECTOR2( 0.0f + fOffTwo * fWidthMod, fTexHeight1 + fOffOne * fHeightMod );
g_Vertex[3].tex6 = D3DXVECTOR2( 0.0f - fOffTwo * fWidthMod, fTexHeight1 + fOffOne * fHeightMod );
}
//--------------------------------------------------------------------------------------
// Handle updates to the scene. This is called regardless of which D3D API is used
//--------------------------------------------------------------------------------------
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext )
{
// Update the camera's position based on user input
g_Camera.FrameMove( fElapsedTime );
}
//--------------------------------------------------------------------------------------
// Render the scene using the D3D9 device
//--------------------------------------------------------------------------------------
void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext )
{
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if( g_SettingsDlg.IsActive() )
{
g_SettingsDlg.OnRender( fElapsedTime );
return;
}
HRESULT hr;
UINT iPass, cPasses;
// First render the world on the rendertarget g_pFullScreenTexture.
if( SUCCEEDED( g_pRenderToSurface->BeginScene( g_pFullScreenTextureSurf, &g_ViewportOffscreen ) ) )
{
V( pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, g_dwBackgroundColor, 1.0f, 0 ) );
// Get the view & projection matrix from camera
D3DXMATRIXA16 matWorld;
D3DXMATRIXA16 matView = *g_Camera.GetViewMatrix();
D3DXMATRIXA16 matProj = *g_Camera.GetProjMatrix();
D3DXMATRIXA16 matViewProj = matView * matProj;
// Update focal plane
g_pEffect->SetVector( g_hFocalPlane, &g_vFocalPlane );
// Set world render technique
V( g_pEffect->SetTechnique( g_hTechWorldWithBlurFactor ) );
// Set the mesh texture
LPD3DXMESH pSceneMesh;
int nNumObjectsInScene;
if( g_nCurrentScene == 1 )
{
V( g_pEffect->SetTexture( g_hMeshTexture, g_pScene1MeshTexture ) );
pSceneMesh = g_pScene1Mesh;
nNumObjectsInScene = 25;
}
else
{
V( g_pEffect->SetTexture( g_hMeshTexture, g_pScene2MeshTexture ) );
pSceneMesh = g_pScene2Mesh;
nNumObjectsInScene = 3;
}
static const D3DXVECTOR3 mScene2WorldPos[3] =
{
D3DXVECTOR3( -0.5f, -0.5f, -0.5f ),
D3DXVECTOR3( 1.0f, 1.0f, 2.0f ),
D3DXVECTOR3( 3.0f, 3.0f, 5.0f )
};
for( int iObject = 0; iObject < nNumObjectsInScene; iObject++ )
{
// setup the world matrix for the current world
if( g_nCurrentScene == 1 )
{
D3DXMatrixTranslation( &matWorld, -( iObject % 5 ) * 1.0f, 0.0f, ( iObject / 5 ) * 3.0f );<|fim▁hole|> else
{
D3DXMATRIXA16 matRot, matPos;
D3DXMatrixRotationY( &matRot, ( float )fTime * 0.66666f );
D3DXMatrixTranslation( &matPos, mScene2WorldPos[iObject].x, mScene2WorldPos[iObject].y,
mScene2WorldPos[iObject].z );
matWorld = matRot * matPos;
}
// Update effect vars
D3DXMATRIXA16 matWorldViewProj = matWorld * matViewProj;
D3DXMATRIXA16 matWorldView = matWorld * matView;
V( g_pEffect->SetMatrix( g_hWorld, &matWorld ) );
V( g_pEffect->SetMatrix( g_hWorldView, &matWorldView ) );
V( g_pEffect->SetMatrix( g_hWorldViewProjection, &matWorldViewProj ) );
// Draw the mesh on the rendertarget
V( g_pEffect->Begin( &cPasses, 0 ) );
for( iPass = 0; iPass < cPasses; iPass++ )
{
V( g_pEffect->BeginPass( iPass ) );
V( pSceneMesh->DrawSubset( 0 ) );
V( g_pEffect->EndPass() );
}
V( g_pEffect->End() );
}
V( g_pRenderToSurface->EndScene( 0 ) );
}
// Clear the backbuffer
V( pd3dDevice->Clear( 0L, NULL, D3DCLEAR_TARGET, 0x00000000, 1.0f, 0L ) );
// Begin the scene, rendering to the backbuffer
if( SUCCEEDED( pd3dDevice->BeginScene() ) )
{
pd3dDevice->SetViewport( &g_ViewportFB );
// Set the post process technique
switch( g_nShowMode )
{
case 0:
V( g_pEffect->SetTechnique( g_hTech[g_TechniqueIndex] ) ); break;
case 1:
V( g_pEffect->SetTechnique( g_hTechShowBlurFactor ) ); break;
case 2:
V( g_pEffect->SetTechnique( g_hTechShowUnmodified ) ); break;
}
// Render the fullscreen quad on to the backbuffer
V( g_pEffect->Begin( &cPasses, 0 ) );
for( iPass = 0; iPass < cPasses; iPass++ )
{
V( g_pEffect->BeginPass( iPass ) );
V( pd3dDevice->SetFVF( VERTEX::FVF ) );
V( pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP, 2, g_Vertex, sizeof( VERTEX ) ) );
V( g_pEffect->EndPass() );
}
V( g_pEffect->End() );
V( g_HUD.OnRender( fElapsedTime ) );
V( g_SampleUI.OnRender( fElapsedTime ) );
// Render the text
RenderText();
// End the scene.
pd3dDevice->EndScene();
}
}
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
void RenderText()
{
CDXUTTextHelper txtHelper( g_pFont, g_pTextSprite, 15 );
// Output statistics
txtHelper.Begin();
txtHelper.SetInsertionPos( 5, 5 );
txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) );
txtHelper.DrawTextLine( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) );
txtHelper.DrawTextLine( DXUTGetDeviceStats() );
txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) );
switch( g_nShowMode )
{
case 0:
txtHelper.DrawFormattedTextLine( L"Technique: %S", g_TechniqueNames[g_TechniqueIndex] ); break;
case 1:
txtHelper.DrawTextLine( L"Technique: ShowBlurFactor" ); break;
case 2:
txtHelper.DrawTextLine( L"Technique: ShowUnmodified" ); break;
}
txtHelper.DrawFormattedTextLine( L"Focal Plane: (%0.1f,%0.1f,%0.1f,%0.1f)", g_vFocalPlane.x, g_vFocalPlane.y,
g_vFocalPlane.z, g_vFocalPlane.w );
// Draw help
if( g_bShowHelp )
{
const D3DSURFACE_DESC* pd3dsdBackBuffer = DXUTGetD3D9BackBufferSurfaceDesc();
txtHelper.SetInsertionPos( 2, pd3dsdBackBuffer->Height - 15 * 6 );
txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 0.75f, 0.0f, 1.0f ) );
txtHelper.DrawTextLine( L"Controls (F1 to hide):" );
txtHelper.SetInsertionPos( 20, pd3dsdBackBuffer->Height - 15 * 5 );
txtHelper.DrawTextLine( L"Look: Left drag mouse\n"
L"Move: A,W,S,D or Arrow Keys\n"
L"Move up/down: Q,E or PgUp,PgDn\n"
L"Reset camera: Home\n" );
}
else
{
txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) );
txtHelper.DrawTextLine( L"Press F1 for help" );
}
txtHelper.End();
}
//--------------------------------------------------------------------------------------
// Handle messages to the application
//--------------------------------------------------------------------------------------
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
void* pUserContext )
{
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
*pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam );
if( *pbNoFurtherProcessing )
return 0;
if( g_SettingsDlg.IsActive() )
{
g_SettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam );
return 0;
}
// Give the dialogs a chance to handle the message first
*pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam );
if( *pbNoFurtherProcessing )
return 0;
*pbNoFurtherProcessing = g_SampleUI.MsgProc( hWnd, uMsg, wParam, lParam );
if( *pbNoFurtherProcessing )
return 0;
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam );
return 0;
}
//--------------------------------------------------------------------------------------
// Handle key presses
//--------------------------------------------------------------------------------------
void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext )
{
if( bKeyDown )
{
switch( nChar )
{
case VK_F1:
g_bShowHelp = !g_bShowHelp; break;
}
}
}
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext )
{
switch( nControlID )
{
case IDC_TOGGLEFULLSCREEN:
DXUTToggleFullScreen(); break;
case IDC_TOGGLEREF:
DXUTToggleREF(); break;
case IDC_CHANGEDEVICE:
g_SettingsDlg.SetActive( !g_SettingsDlg.IsActive() ); break;
case IDC_CHANGE_TECHNIQUE:
{
DWORD OriginalTechnique = g_TechniqueIndex;
do
{
g_TechniqueIndex++;
if( g_TechniqueIndex == g_TechniqueCount )
{
g_TechniqueIndex = 0;
}
D3DXHANDLE hTech = g_pEffect->GetTechniqueByName( g_TechniqueNames[g_TechniqueIndex] );
if( SUCCEEDED( g_pEffect->ValidateTechnique( hTech ) ) )
{
break;
}
} while( OriginalTechnique != g_TechniqueIndex );
UpdateTechniqueSpecificVariables( DXUTGetD3D9BackBufferSurfaceDesc() );
break;
}
case IDC_CHANGE_SCENE:
{
g_nCurrentScene %= 2;
g_nCurrentScene++;
switch( g_nCurrentScene )
{
case 1:
{
D3DXVECTOR3 vecEye( 0.75f, 0.8f, -2.3f );
D3DXVECTOR3 vecAt ( 0.2f, 0.75f, -1.5f );
g_Camera.SetViewParams( &vecEye, &vecAt );
break;
}
case 2:
{
D3DXVECTOR3 vecEye( 0.0f, 0.0f, -3.0f );
D3DXVECTOR3 vecAt ( 0.0f, 0.0f, 0.0f );
g_Camera.SetViewParams( &vecEye, &vecAt );
break;
}
}
break;
}
case IDC_CHANGE_FOCAL:
{
WCHAR sz[100];
g_vFocalPlane.w = -g_SampleUI.GetSlider( IDC_CHANGE_FOCAL )->GetValue() / 10.0f;
swprintf_s( sz, 100, L"Focal Distance: %0.2f", -g_vFocalPlane.w ); sz[99] = 0;
g_SampleUI.GetStatic( IDC_CHANGE_FOCAL_STATIC )->SetText( sz );
UpdateTechniqueSpecificVariables( DXUTGetD3D9BackBufferSurfaceDesc() );
break;
}
case IDC_SHOW_NORMAL:
g_nShowMode = 0;
break;
case IDC_SHOW_BLUR:
g_nShowMode = 1;
break;
case IDC_SHOW_UNBLURRED:
g_nShowMode = 2;
break;
case IDC_CHANGE_BLUR:
{
WCHAR sz[100];
g_fBlurConst = g_SampleUI.GetSlider( IDC_CHANGE_BLUR )->GetValue() / 10.0f;
swprintf_s( sz, 100, L"Blur Factor: %0.2f", g_fBlurConst ); sz[99] = 0;
g_SampleUI.GetStatic( IDC_CHANGE_BLUR_STATIC )->SetText( sz );
UpdateTechniqueSpecificVariables( DXUTGetD3D9BackBufferSurfaceDesc() );
break;
}
}
}
//--------------------------------------------------------------------------------------
// Release D3D9 resources created in the OnD3D9ResetDevice callback
//--------------------------------------------------------------------------------------
void CALLBACK OnLostDevice( void* pUserContext )
{
g_DialogResourceManager.OnD3D9LostDevice();
g_SettingsDlg.OnD3D9LostDevice();
if( g_pFont )
g_pFont->OnLostDevice();
if( g_pEffect )
g_pEffect->OnLostDevice();
SAFE_RELEASE( g_pTextSprite );
SAFE_RELEASE( g_pFullScreenTextureSurf );
SAFE_RELEASE( g_pFullScreenTexture );
SAFE_RELEASE( g_pRenderToSurface );
}
//--------------------------------------------------------------------------------------
// Release D3D9 resources created in the OnD3D9CreateDevice callback
//--------------------------------------------------------------------------------------
void CALLBACK OnDestroyDevice( void* pUserContext )
{
g_DialogResourceManager.OnD3D9DestroyDevice();
g_SettingsDlg.OnD3D9DestroyDevice();
SAFE_RELEASE( g_pEffect );
SAFE_RELEASE( g_pFont );
SAFE_RELEASE( g_pFullScreenTextureSurf );
SAFE_RELEASE( g_pFullScreenTexture );
SAFE_RELEASE( g_pRenderToSurface );
SAFE_RELEASE( g_pScene1Mesh );
SAFE_RELEASE( g_pScene1MeshTexture );
SAFE_RELEASE( g_pScene2Mesh );
SAFE_RELEASE( g_pScene2MeshTexture );
}<|fim▁end|> | } |
<|file_name|>zinc_compile.py<|end_file_name|><|fim▁begin|># coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import textwrap
from contextlib import closing
from xml.etree import ElementTree
from pants.backend.jvm.subsystems.scala_platform import ScalaPlatform<|fim▁hole|>from pants.backend.jvm.targets.jar_dependency import JarDependency
from pants.backend.jvm.tasks.jvm_compile.analysis_tools import AnalysisTools
from pants.backend.jvm.tasks.jvm_compile.jvm_compile import JvmCompile
from pants.backend.jvm.tasks.jvm_compile.scala.zinc_analysis import ZincAnalysis
from pants.backend.jvm.tasks.jvm_compile.scala.zinc_analysis_parser import ZincAnalysisParser
from pants.base.build_environment import get_buildroot
from pants.base.exceptions import TaskError
from pants.base.hash_utils import hash_file
from pants.base.workunit import WorkUnitLabel
from pants.java.distribution.distribution import DistributionLocator
from pants.option.custom_types import dict_option
from pants.util.contextutil import open_zip
from pants.util.dirutil import relativize_paths, safe_open
# Well known metadata file required to register scalac plugins with nsc.
_PLUGIN_INFO_FILE = 'scalac-plugin.xml'
class ZincCompile(JvmCompile):
"""Compile Scala and Java code using Zinc."""
_ZINC_MAIN = 'org.pantsbuild.zinc.Main'
_name = 'zinc'
_supports_concurrent_execution = True
@staticmethod
def write_plugin_info(resources_dir, target):
root = os.path.join(resources_dir, target.id)
plugin_info_file = os.path.join(root, _PLUGIN_INFO_FILE)
with safe_open(plugin_info_file, 'w') as f:
f.write(textwrap.dedent("""
<plugin>
<name>{}</name>
<classname>{}</classname>
</plugin>
""".format(target.plugin, target.classname)).strip())
return root, plugin_info_file
@classmethod
def subsystem_dependencies(cls):
return super(ZincCompile, cls).subsystem_dependencies() + (ScalaPlatform, DistributionLocator)
@classmethod
def get_args_default(cls, bootstrap_option_values):
return ('-S-encoding', '-SUTF-8', '-S-g:vars')
@classmethod
def get_warning_args_default(cls):
return ('-S-deprecation', '-S-unchecked')
@classmethod
def get_no_warning_args_default(cls):
return ('-S-nowarn',)
@classmethod
def register_options(cls, register):
super(ZincCompile, cls).register_options(register)
register('--plugins', advanced=True, action='append', fingerprint=True,
help='Use these scalac plugins.')
register('--plugin-args', advanced=True, type=dict_option, default={}, fingerprint=True,
help='Map from plugin name to list of arguments for that plugin.')
register('--name-hashing', advanced=True, action='store_true', default=False, fingerprint=True,
help='Use zinc name hashing.')
cls.register_jvm_tool(register,
'zinc',
classpath=[
JarDependency('org.pantsbuild', 'zinc', '1.0.8')
],
main=cls._ZINC_MAIN,
custom_rules=[
# The compiler-interface and sbt-interface tool jars carry xsbt and
# xsbti interfaces that are used across the shaded tool jar boundary so
# we preserve these root packages wholesale along with the core scala
# APIs.
Shader.exclude_package('scala', recursive=True),
Shader.exclude_package('xsbt', recursive=True),
Shader.exclude_package('xsbti', recursive=True),
])
def sbt_jar(name, **kwargs):
return JarDependency(org='com.typesafe.sbt', name=name, rev='0.13.9', **kwargs)
cls.register_jvm_tool(register,
'compiler-interface',
classpath=[
sbt_jar(name='compiler-interface',
classifier='sources',
# We just want the single compiler-interface jar and not its
# dep on scala-lang
intransitive=True)
])
cls.register_jvm_tool(register,
'sbt-interface',
classpath=[
sbt_jar(name='sbt-interface',
# We just want the single sbt-interface jar and not its dep
# on scala-lang
intransitive=True)
])
# By default we expect no plugin-jars classpath_spec is filled in by the user, so we accept an
# empty classpath.
cls.register_jvm_tool(register, 'plugin-jars', classpath=[])
def select(self, target):
return target.has_sources('.java') or target.has_sources('.scala')
def select_source(self, source_file_path):
return source_file_path.endswith('.java') or source_file_path.endswith('.scala')
def __init__(self, *args, **kwargs):
super(ZincCompile, self).__init__(*args, **kwargs)
# A directory independent of any other classpath which can contain per-target
# plugin resource files.
self._plugin_info_dir = os.path.join(self.workdir, 'scalac-plugin-info')
self._lazy_plugin_args = None
def create_analysis_tools(self):
return AnalysisTools(DistributionLocator.cached().real_home, ZincAnalysisParser(), ZincAnalysis)
def zinc_classpath(self):
# Zinc takes advantage of tools.jar if it's presented in classpath.
# For example com.sun.tools.javac.Main is used for in process java compilation.
def locate_tools_jar():
try:
return DistributionLocator.cached(jdk=True).find_libs(['tools.jar'])
except DistributionLocator.Error:
self.context.log.info('Failed to locate tools.jar. '
'Install a JDK to increase performance of Zinc.')
return []
return self.tool_classpath('zinc') + locate_tools_jar()
def compiler_classpath(self):
return ScalaPlatform.global_instance().compiler_classpath(self.context.products)
def extra_compile_time_classpath_elements(self):
# Classpath entries necessary for our compiler plugins.
return self.plugin_jars()
def plugin_jars(self):
"""The classpath entries for jars containing code for enabled plugins."""
if self.get_options().plugins:
return self.tool_classpath('plugin-jars')
else:
return []
def plugin_args(self):
if self._lazy_plugin_args is None:
self._lazy_plugin_args = self._create_plugin_args()
return self._lazy_plugin_args
def _create_plugin_args(self):
if not self.get_options().plugins:
return []
plugin_args = self.get_options().plugin_args
active_plugins = self._find_plugins()
ret = []
for name, jar in active_plugins.items():
ret.append('-S-Xplugin:{}'.format(jar))
for arg in plugin_args.get(name, []):
ret.append('-S-P:{}:{}'.format(name, arg))
return ret
def _find_plugins(self):
"""Returns a map from plugin name to plugin jar."""
# Allow multiple flags and also comma-separated values in a single flag.
plugin_names = set([p for val in self.get_options().plugins for p in val.split(',')])
plugins = {}
buildroot = get_buildroot()
for jar in self.plugin_jars():
with open_zip(jar, 'r') as jarfile:
try:
with closing(jarfile.open(_PLUGIN_INFO_FILE, 'r')) as plugin_info_file:
plugin_info = ElementTree.parse(plugin_info_file).getroot()
if plugin_info.tag != 'plugin':
raise TaskError(
'File {} in {} is not a valid scalac plugin descriptor'.format(_PLUGIN_INFO_FILE,
jar))
name = plugin_info.find('name').text
if name in plugin_names:
if name in plugins:
raise TaskError('Plugin {} defined in {} and in {}'.format(name, plugins[name], jar))
# It's important to use relative paths, as the compiler flags get embedded in the zinc
# analysis file, and we port those between systems via the artifact cache.
plugins[name] = os.path.relpath(jar, buildroot)
except KeyError:
pass
unresolved_plugins = plugin_names - set(plugins.keys())
if unresolved_plugins:
raise TaskError('Could not find requested plugins: {}'.format(list(unresolved_plugins)))
return plugins
def extra_products(self, target):
"""Override extra_products to produce a plugin information file."""
ret = []
if target.is_scalac_plugin and target.classname:
# NB: We don't yet support explicit in-line compilation of scala compiler plugins from
# the workspace to be used in subsequent compile rounds like we do for annotation processors
# with javac. This would require another GroupTask similar to AptCompile, but for scala.
root, plugin_info_file = self.write_plugin_info(self._plugin_info_dir, target)
ret.append((root, [plugin_info_file]))
return ret
def compile(self, args, classpath, sources, classes_output_dir, upstream_analysis, analysis_file,
log_file, settings):
# We add compiler_classpath to ensure the scala-library jar is on the classpath.
# TODO: This also adds the compiler jar to the classpath, which compiled code shouldn't
# usually need. Be more selective?
# TODO(John Sirois): Do we need to do this at all? If adding scala-library to the classpath is
# only intended to allow target authors to omit a scala-library dependency, then ScalaLibrary
# already overrides traversable_dependency_specs to achieve the same end; arguably at a more
# appropriate level and certainly at a more appropriate granularity.
relativized_classpath = relativize_paths(self.compiler_classpath() + classpath, get_buildroot())
zinc_args = []
zinc_args.extend([
'-log-level', self.get_options().level,
'-analysis-cache', analysis_file,
'-classpath', ':'.join(relativized_classpath),
'-d', classes_output_dir
])
if not self.get_options().colors:
zinc_args.append('-no-color')
if not self.get_options().name_hashing:
zinc_args.append('-no-name-hashing')
if log_file:
zinc_args.extend(['-capture-log', log_file])
zinc_args.extend(['-compiler-interface', self.tool_jar('compiler-interface')])
zinc_args.extend(['-sbt-interface', self.tool_jar('sbt-interface')])
zinc_args.extend(['-scala-path', ':'.join(self.compiler_classpath())])
zinc_args += self.plugin_args()
if upstream_analysis:
zinc_args.extend(['-analysis-map',
','.join('{}:{}'.format(*kv) for kv in upstream_analysis.items())])
zinc_args += args
zinc_args.extend([
'-C-source', '-C{}'.format(settings.source_level),
'-C-target', '-C{}'.format(settings.target_level),
])
zinc_args.extend(settings.args)
jvm_options = list(self._jvm_options)
zinc_args.extend(sources)
self.log_zinc_file(analysis_file)
if self.runjava(classpath=self.zinc_classpath(),
main=self._ZINC_MAIN,
jvm_options=jvm_options,
args=zinc_args,
workunit_name='zinc',
workunit_labels=[WorkUnitLabel.COMPILER]):
raise TaskError('Zinc compile failed.')
def log_zinc_file(self, analysis_file):
self.context.log.debug('Calling zinc on: {} ({})'
.format(analysis_file,
hash_file(analysis_file).upper()
if os.path.exists(analysis_file)
else 'nonexistent'))<|fim▁end|> | from pants.backend.jvm.subsystems.shader import Shader |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>mod parser;
pub use self::parser::parse_expressions;
pub enum Expression {<|fim▁hole|> Variable(String),
BinaryOp(String, Box<Expression>, Box<Expression>),
UnaryOp(String, Box<Expression>),
NullaryOp(String),
Function(String, Vec<Expression>),
FunctionDefinition(String, Vec<String>, Vec<Expression>),
VariableAssignment(Vec<(String, Expression)>, Vec<Expression>),
Conditional(Box<Expression>,Vec<Expression>,Vec<Expression>)
}<|fim▁end|> | Integer(i64), |
<|file_name|>test_basic.py<|end_file_name|><|fim▁begin|># Copyright (c) 2008, Stefano Taschini <[email protected]>
# All rights reserved.
# See LICENSE for details.
import unittest
from interval import interval, fpu
class FpuTestCase(unittest.TestCase):
def test_third(self):
"Nearest rounding of 1/3 is downwards."
self.assertEqual(1/3.0, fpu.down(lambda: 1.0 / 3.0))
self.assertTrue(1/3.0 < fpu.up(lambda: 1.0 / 3.0))
self.assertEqual(-1/3.0, fpu.up(lambda: 1.0 / -3.0))
self.assertTrue(-1/3.0 > fpu.down(lambda: 1.0 / -3.0))
def test_fourth(self):
" 1/4 is exact."
self.assertEqual(1/4.0, fpu.down(lambda: 1.0 / 4.0))
self.assertEqual(1/4.0, fpu.up(lambda: 1.0 / 4.0))
self.assertEqual(-1/4.0, fpu.up(lambda: 1.0 / -4.0))
self.assertEqual(-1/4.0, fpu.down(lambda: 1.0 / -4.0))
def test_fifth(self):
"Nearest rounding of 1/5 is upwards."
self.assertEqual(1/5.0, fpu.up(lambda: 1.0 / 5.0))
self.assertTrue(1/5.0 > fpu.down(lambda: 1.0 / 5.0))
self.assertEqual(-1/5.0, fpu.down(lambda: 1.0 / -5.0))
self.assertTrue(-1/5.0 < fpu.up(lambda: 1.0 / -5.0))
def test_ieee754(self):
"fpu.float respect ieee754 semantics."
self.assertEqual(fpu.infinity + fpu.infinity, fpu.infinity)
self.assertTrue(fpu.isnan(fpu.nan))
self.assertTrue(fpu.isnan(0.0 * fpu.infinity))
self.assertTrue(fpu.isnan(fpu.infinity - fpu.infinity))
def test_float_coercion(self):
"Only real-number scalars should be able to coerce as fpu.float"
self.assertRaises(Exception, lambda: float(1,2))
self.assertRaises(Exception, lambda: float((1,2)))
self.assertRaises(Exception, lambda: float([1,2]))
self.assertRaises(Exception, lambda: float('a'))
self.assertRaises(Exception, lambda: float(1+1j))
def test_min(self):
"Verify corner cases with nan, -inf, +inf"
self.assertEqual(fpu.min((1.0, 2.0)), 1.0)
self.assertEqual(fpu.min((1.0, fpu.infinity)), 1.0)
self.assertEqual(fpu.min((1.0, -fpu.infinity)), -fpu.infinity)
self.assertTrue(fpu.isnan(fpu.min((1.0, -fpu.nan))))
def test_max(self):
"Verify corner cases with nan, -inf, +inf"
self.assertEqual(fpu.max((1.0, 2.0)), 2.0)
self.assertEqual(fpu.max((1.0, fpu.infinity)), fpu.infinity)
self.assertEqual(fpu.max((1.0, -fpu.infinity)), 1.0)
self.assertTrue(fpu.isnan(fpu.max((1.0, fpu.nan))))
def test_power(self):
x = 1/3.0
# The cube of one third should depend on the rounding mode
self.assertTrue(fpu.down(lambda: x*x*x) < fpu.up(lambda: x*x*x))
# But using the built-in power operator, it doesn't necessarily do it
# print fpu.down(lambda: x**3) < fpu.up(lambda: x**3))
# So we define an integer power methods that does
self.assertTrue(fpu.power_rd(x, 3) < fpu.power_ru(x, 3))
self.assertTrue(fpu.power_rd(-x, 3) < fpu.power_ru(-x, 3))
self.assertTrue(fpu.power_rd(x, 4) < fpu.power_ru(x, 4))
self.assertTrue(fpu.power_rd(-x, 4) < fpu.power_ru(-x, 4))
self.assertEqual(
(fpu.down(lambda: x*x*x), fpu.up(lambda: x*x*x)),
(fpu.power_rd(x, 3), fpu.power_ru(x, 3)))
class ModuleTestCase(unittest.TestCase):
def test_namespace(self):
import interval
self.assertEqual(
dir(interval),
['__builtins__', '__doc__', '__file__', '__name__', '__path__', 'fpu', 'imath', 'inf', 'interval'])
class IntervalTestCase(unittest.TestCase):
def test_trivial_constructor(self):
self.assertEqual(interval[1], ((1, 1),))
self.assertEqual(interval(1), ((1, 1),))
self.assertEqual(interval[1, 2], ((1, 2),))
self.assertEqual(interval(1, 2), ((1, 1), (2, 2)))
self.assertEqual(interval([1, 2], [3, 4]), ((1, 2), (3, 4)))
self.assertEqual(interval([1,2]), interval(interval([1, 2])))
def test_nan_constructor(self):
self.assertEqual(interval[2, fpu.nan], ((-fpu.infinity, fpu.infinity),))
self.assertEqual(interval[2, fpu.nan], ((-fpu.infinity, fpu.infinity),))
self.assertEqual(interval(2, fpu.nan, 9), ((-fpu.infinity, fpu.infinity),))
def test_failing_constructor(self):
self.assertRaises(interval.ComponentError, lambda: interval[1, [2, 3]])
self.assertRaises(interval.ComponentError, lambda: interval[1, 2, 3])
self.assertRaises(interval.ComponentError, lambda: interval(0, [1, 2, 3]))
self.assertRaises(interval.ComponentError, lambda: interval(0, [1, [2, 3]]))
self.assertRaises(interval.ComponentError, lambda: interval['a', 1])
def test_canonical_constructor(self):
self.assertEqual(interval([1, 3], [4, 6], [2, 5], 9), ((1, 6), (9, 9)))
self.assertEqual(interval[2 ** (52 + 1) - 1], interval[9007199254740991.0])
self.assertEqual(interval[2 ** (52 + 1) + 1], interval[4503599627370496 * 2.0, 4503599627370497 * 2.0])
self.assertEqual(interval[-2 ** (52 + 1) + 1], interval[-9007199254740991.0])
self.assertEqual(interval[-2 ** (52 + 1) - 1], interval[-4503599627370497 * 2.0, -4503599627370496 * 2.0])
self.assertEqual(interval[2 ** (52 + 2) + 1], interval[4503599627370496 * 4.0, 4503599627370497 * 4.0])
self.assertEqual(interval[2 ** (52 + 2) + 2], interval[4503599627370496 * 4.0, 4503599627370497 * 4.0])
self.assertEqual(interval[2 ** (52 + 2) + 3], interval[4503599627370496 * 4.0, 4503599627370497 * 4.0])
self.assertEqual(interval[-2 ** (52 + 2) - 1], interval[-4503599627370497 * 4.0, -4503599627370496 * 4.0])
self.assertEqual(interval[-2 ** (52 + 2) - 2], interval[-4503599627370497 * 4.0, -4503599627370496 * 4.0])
self.assertEqual(interval[-2 ** (52 + 2) - 3], interval[-4503599627370497 * 4.0, -4503599627370496 * 4.0])
def test_unary(self):
self.assertEqual(interval[1, 2], +interval[1, 2])
self.assertEqual(interval[-2, -1], -interval[1, 2])
def test_sum(self):
self.assertEqual(interval[-fpu.infinity, +fpu.infinity], interval[-fpu.infinity] + interval[fpu.infinity])
self.assertEqual(interval[4, 6], interval[1, 2] + interval[3, 4])
self.assertEqual(interval[3, fpu.infinity], interval[1, fpu.infinity] + interval[2])
self.assertEqual(interval[-fpu.infinity, +fpu.infinity], interval[-fpu.infinity, -1] + interval[2, +fpu.infinity])
self.assertEqual(interval[-fpu.infinity, +fpu.infinity], interval[-fpu.infinity] + interval[8, +fpu.infinity])
self.assertEqual(interval([1, 2], [10, fpu.infinity]) + interval([1,9],[-2,-1]), interval([-1, 1], [2, fpu.infinity]))
self.assertEqual(interval[1, 9] + interval([1, 2], [10, fpu.infinity]), interval[2, fpu.infinity])
def test_sum_coercion(self):
self.assertEqual(interval[1,2] + 2, interval[3, 4])
self.assertRaises(TypeError, lambda: interval[1,2] + 1j)
self.assertEqual(1 + interval[4, 5], interval[5, 6])
self.assertRaises(TypeError, lambda: (1, 2) + interval[1,2])
self.assertEqual(fpu.infinity + interval[4, 5], interval[fpu.infinity])
def test_sub(self):
self.assertEqual(interval[1, 2] - interval[3, 4], interval[-3.0, -1.0])
self.assertEqual(interval[1, 2] - 0.5, interval[0.5, 1.5])
self.assertEqual(1.5 - interval[1, 2], interval[-0.5, 0.5])
def test_mul(self):
self.assertEqual(interval[-fpu.infinity, +fpu.infinity], fpu.infinity * interval[0])
self.assertEqual(interval[+fpu.infinity], interval[+fpu.infinity] * interval[3])
self.assertEqual(interval[-8, +10], interval[1, 2] * interval[-4, 5])
self.assertEqual(interval[3, 8], interval[1, 2] * interval[3, 4])
self.assertEqual(interval[-fpu.infinity, +fpu.infinity], interval[0,1 ] * interval[2, +fpu.infinity])
self.assertEqual(interval[2, fpu.infinity], interval[-fpu.infinity,-2] * interval[-fpu.infinity,-1])
self.assertEqual(interval([1, 2], [3, 4]) * interval[0.5, 2], interval[0.5, 8])
self.assertEqual(interval[1, 2] * 2, interval[2, 4])
def test_inverse(self):
self.assertEqual(interval[0.5, 1], interval[1, 2].inverse())
self.assertEqual(interval[-1, -0.5],(-interval[1, 2]).inverse())
self.assertEqual(interval([-fpu.infinity, -1], [0.5, +fpu.infinity]), interval[-1,2].inverse())
self.assertEqual(interval(-fpu.infinity, [1, +fpu.infinity]), interval[0,1].inverse())
self.assertEqual(interval([-fpu.infinity, -2.0], [0.0, fpu.infinity]),
interval([-0.5, 0.5], [0.2, fpu.infinity]).inverse())
def test_division(self):
self.assertEqual(interval[-fpu.infinity, fpu.infinity], interval[0,1] / interval[0,1])
self.assertEqual(interval[0.5], interval[1] / 2)
self.assertEqual(interval[0.5], 1 / interval[2])
def test_power(self):
self.assertRaises(TypeError, lambda: interval[1, 2] ** (1.3))
self.assertEqual((-interval[1, 2]).inverse(), (-interval[1, 2]) ** -1)
self.assertEqual(interval[0, 4], interval[-1, 2] ** 2)
self.assertEqual(interval[-27, 8], interval[-3, 2] ** 3)
self.assertEqual(interval[-1, 2], (interval[-1,2]**-1)**-1)
self.assertEqual(interval([-0.38712442133802405]) ** 3, interval([-0.058016524353106828, -0.058016524353106808]))
self.assertEqual(
interval[fpu.down(lambda: (1/3.0)*(1/3.0)), fpu.up(lambda: (1/3.0)*(1/3.0))],
(interval[1]/3.0) ** 2)
self.assertEqual(
interval[fpu.down(lambda: (1/3.0)*(1/3.0)*(1/3.0)), fpu.up(lambda: (1/3.0)*(1/3.0)*(1/3.0))],
(interval[1]/3.0) ** 3)
def test_format(self):
for x in interval[1], interval[1,2], interval([1,2], [3,4]):
self.assertEqual(x, eval(repr(x)))
def test_intersection(self):
self.assertEqual(interval[1, 2] & interval[0, 3], interval[1, 2])
self.assertEqual(interval[1.1, 1.9] & interval[1.3, 2.5], interval[1.3, 1.9])
self.assertEqual(interval[1.1, 1.9] & interval[0.3, 0.7], interval())
self.assertEqual(interval([1, 3], [4, 5]) & interval[2], interval[2])
self.assertEqual(interval([1, 3], [4, 5]) & interval(2,4.5), interval(2, 4.5))
self.assertEqual(interval[1, 2] & 1.2, interval(1.2))
self.assertEqual(2.1 & interval[1, 2], interval())
def test_union(self):
self.assertEqual(interval([1, 6], 9), interval([1, 3], [4, 6]) | interval([2, 5], 9))
self.assertEqual(interval[1, 2] | 2.1, interval([1, 2], 2.1))
self.assertEqual(2.1 | interval[1, 2], interval([1, 2], 2.1))
def test_hull(self):
self.assertEqual(interval([1, 9]), interval.hull((interval([1, 3], [4, 6]), interval([2, 5], 9))))
def test_inclusion(self):
def verify_in(x, y):
self.assertTrue(x in y)
self.assertEqual(x & y, interval(x))
verify_in(1.5, interval[1, 2])
verify_in(1, interval[1, 2])
verify_in(2, interval[1, 2])
verify_in(interval[1, 2], interval[1, 2])
verify_in(interval[1.1, 2], interval[1, 2])
verify_in(interval[1, 1.8], interval[1, 2])
verify_in(interval([1.1, 2.2], [3.3, 4.4]), interval(-1, [0, 2.5], [3, 5], [7, 9]))
def verify_out(x, y):
self.assertFalse(x in y)
self.assertNotEqual(x & y, x)
verify_out(0, interval[1, 2])
verify_out(4, interval[1, 2])
verify_out(interval[1, 3], interval[2, 4])
verify_out(interval(1, 3), interval(2, 4))
def test_extrema(self):
self.assertEqual(interval(1, [2, 3], 4).extrema, interval(1, 2, 3, 4))
def test_midpoint(self):
self.assertEqual(interval[0, 4].midpoint, interval[2])
self.assertEqual(interval(-1, 1, 4), interval(-1, [0, 2], [3, 5]).midpoint)<|fim▁hole|>
class NewtonTestCase(unittest.TestCase):
def test_opts(self):
self.assertRaises(TypeError, lambda: interval(0,1).newton(None, None, nonexisting=True))
def test_cubic(self):
self.assertEqual(
interval[-2, 2].newton(lambda x: x**3 - x, lambda x: 3*x**2-1),
interval(-1, 0, 1))
self.assertEqual(
interval[-5, 5].newton(lambda x: x**3 + x - 10, lambda x: 3*x**2 + 1),
interval[2])
self.assertEqual(
interval[-5, 5].newton(lambda x: x**3 + x - 15, lambda x: 3*x**2 + 1),
interval[5249383869325653 * 2.0 ** -51, 5249383869325655 * 2.0 ** -51])
# The sharpest result would be with 5249383869325654 * 2.0 ** -51 as sup.
def test_sqrt2(self):
import math
f, p = lambda x: x**2 - 2, lambda x: 2 * x
u, v = 6369051672525772 * 2.0 **-52, 6369051672525773 * 2.0 **-52
self.assertEqual(v, math.sqrt(2))
s = interval[u, v]
self.assertEqual(s, interval[0.1, 5].newton(f, p))
self.assertEqual(s, interval[0, 2].newton(f, p))
self.assertEqual(s, interval[-1, 10].newton(f, p))
self.assertEqual(interval(), interval[2, 5].newton(f, p))
self.assertEqual(-s, interval[-5, 0].newton(f, p))
self.assertEqual(-s|s, interval[-5, +5].newton(f, p))
if __name__ == '__main__':
unittest.main()<|fim▁end|> | |
<|file_name|>task.js<|end_file_name|><|fim▁begin|>var mongoose = require('mongoose'),<|fim▁hole|> Schema = mongoose.Schema;
/**
* Task Schema
* @type {Object}
*/
var TaskSchema = new Schema({
title: {
type: String,
default: '',
trim: true
},
project: {
type: String,
default: '',
trim: true
},
date: {
type: Date
},
created: {
type: Date
},
user: {
type: String
}
});
/**
* Validations
*/
TaskSchema.path('title').validate(function(title) {
"use strict";
return title.length;
}, 'Titulo em branco');
TaskSchema.path('project').validate(function(project) {
"use strict";
return project.length;
}, 'Projeto em branco');
/**
* Statics
*/
TaskSchema.statics = {
load: function(id, cb) {
"use strict";
this.findOne({
_id: id
}).populate('user', 'name username').exec(cb);
}
};
mongoose.model('Task', TaskSchema);<|fim▁end|> | |
<|file_name|>MoQiang.cpp<|end_file_name|><|fim▁begin|>#include "MoQiang.h"
enum CAUSE{
AN_ZHI_JIE_FANG=2901,
HUAN_YING_XING_CHEN=2902,
HEI_AN_SHU_FU=2903,
AN_ZHI_ZHANG_BI=2904,
CHONG_YING=2905,
CHONG_YING_DISCARD = 29051,
QI_HEI_ZHI_QIANG=2906
};
MoQiang::MoQiang()
{
makeConnection();
setMyRole(this);
Button *chongying;
chongying=new Button(3,QStringLiteral("充盈"));
buttonArea->addButton(chongying);
connect(chongying,SIGNAL(buttonSelected(int)),this,SLOT(ChongYing()));
}
void MoQiang::normal()
{
Role::normal();
handArea->disableMagic();
if(!jieFangFirst)
{
if(handArea->checkElement("thunder") || handArea->checkType("magic"))
buttonArea->enable(3);
}
unactionalCheck();
}
void MoQiang::AnZhiJieFang()
{
state=AN_ZHI_JIE_FANG;
gui->reset();
SafeList<Card*> handcards=dataInterface->getHandCards();
bool flag=true;
int magicCount = 0;
int cardCount = handcards.size();
decisionArea->enable(1);
for(int i = 0;i < cardCount;i++)
{
if(handcards[i]->getType() == "magic")
{
magicCount++;
}
}
if(magicCount == cardCount)
{
flag = false;
}
tipArea->setMsg(QStringLiteral("是否发动暗之解放?"));
if(flag)
{
decisionArea->enable(0);
}
else
{
decisionArea->disable(0);
}
}
void MoQiang::HuanYingXingChen()
{
state=HUAN_YING_XING_CHEN;
gui->reset();
tipArea->setMsg(QStringLiteral("是否发动幻影星辰?"));
playerArea->enableAll();
playerArea->setQuota(1);
decisionArea->enable(1);
}
void MoQiang::AnZhiBiZhang()
{
state=AN_ZHI_ZHANG_BI;
tipArea->setMsg(QStringLiteral("是否发动暗之障壁?"));
handArea->setQuota(1,7);
decisionArea->enable(1);
decisionArea->disable(0);
handArea->enableElement("thunder");
handArea->enableMagic();
}
void MoQiang::QiHeiZhiQiang()
{
state= QI_HEI_ZHI_QIANG;
tipArea->reset();
tipArea->setMsg(QStringLiteral("是否发动漆黑之枪?如是请选择发动能量数:"));
decisionArea->enable(0);
decisionArea->enable(1);
Player* myself=dataInterface->getMyself();
int min=myself->getEnergy();
for(;min>0;min--)
tipArea->addBoxItem(QString::number(min));
tipArea->showBox();
}
void MoQiang::ChongYing()
{
state=CHONG_YING;
playerArea->reset();
handArea->reset();
tipArea->reset();
handArea->enableElement("thunder");
handArea->enableMagic();
handArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void MoQiang::cardAnalyse()
{
SafeList<Card*> selectedCards;
Role::cardAnalyse();
selectedCards=handArea->getSelectedCards();
try{
switch(state)
{
case AN_ZHI_ZHANG_BI:
{
bool thunder = true;
bool magic = true;
for(int i=0;i<selectedCards.size();i++)
{
if(selectedCards[i]->getElement()!= "thunder")
{
thunder = false;
}
if(selectedCards[i]->getType() != "magic")
{
magic = false;
}
}
if(thunder || magic){
decisionArea->enable(0);
}
else{
playerArea->reset();
decisionArea->disable(0);
}
break;
}
case CHONG_YING:
decisionArea->enable(0);
break;
}
}catch(int error){
logic->onError(error);
}
}
void MoQiang::playerAnalyse()
{
Role::playerAnalyse();
switch(state)
{
case HUAN_YING_XING_CHEN:
decisionArea->enable(0);
break;
}
}
void MoQiang::turnBegin()
{
Role::turnBegin();
jieFangFirst=false;
usingChongYing = false;
}
void MoQiang::askForSkill(Command* cmd)
{
switch(cmd->respond_id())
{
case AN_ZHI_JIE_FANG:
AnZhiJieFang();
break;
case HUAN_YING_XING_CHEN:
HuanYingXingChen();
break;
case QI_HEI_ZHI_QIANG:
QiHeiZhiQiang();
break;
case AN_ZHI_ZHANG_BI:
AnZhiBiZhang();
break;
default:
Role::askForSkill(cmd);
}
}
void MoQiang::onOkClicked()
{
Role::onOkClicked();
SafeList<Card*> selectedCards;
SafeList<Player*>selectedPlayers;
selectedCards=handArea->getSelectedCards();
selectedPlayers=playerArea->getSelectedPlayers();
network::Action* action;
network::Respond* respond;
try{
switch(state)
{
case AN_ZHI_JIE_FANG:
respond = new Respond();
respond->set_src_id(myID);
respond->set_respond_id(AN_ZHI_JIE_FANG);
respond->add_args(1);
jieFangFirst=true;
start = true;
gui->reset();
emit sendCommand(network::MSG_RESPOND, respond);
break;
case HUAN_YING_XING_CHEN:
respond = newRespond(HUAN_YING_XING_CHEN);
respond->add_args(2);
respond->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_RESPOND, respond);
start = true;
gui->reset();
break;
case AN_ZHI_ZHANG_BI:
respond = newRespond(AN_ZHI_ZHANG_BI);
respond->add_args(1);
for(int i=0;i<selectedCards.size();i++)
{
respond->add_card_ids(selectedCards[i]->getID());
}
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case QI_HEI_ZHI_QIANG:
respond = newRespond(QI_HEI_ZHI_QIANG);
respond->add_args(1);
respond->add_args(tipArea->getBoxCurrentText().toInt());
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case CHONG_YING:
action = newAction(ACTION_MAGIC_SKILL,CHONG_YING);
action->add_card_ids(selectedCards[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
usingChongYing = true;
gui->reset();
break;
}
}catch(int error){
logic->onError(error);
}
}
void MoQiang::onCancelClicked()
{
Role::onCancelClicked();
network::Respond* respond;
switch(state)
{
case AN_ZHI_JIE_FANG:
respond = new Respond();
respond->set_src_id(myID);
respond->set_respond_id(AN_ZHI_JIE_FANG);
respond->add_args(0);
gui->reset();
emit sendCommand(network::MSG_RESPOND, respond);
break;
case HUAN_YING_XING_CHEN:
respond = newRespond(HUAN_YING_XING_CHEN);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case AN_ZHI_ZHANG_BI:
respond = newRespond(AN_ZHI_ZHANG_BI);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case QI_HEI_ZHI_QIANG:
respond = newRespond(QI_HEI_ZHI_QIANG);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case CHONG_YING:
normal();
break;
}
}
void MoQiang::attacked(QString element, int hitRate)
{
<|fim▁hole|>
void MoQiang::moDaned(int nextID,int sourceID, int howMany)
{
Role::moDaned(nextID,sourceID,howMany);
handArea->disableMagic();
}<|fim▁end|> | Role::attacked(element,hitRate);
handArea->disableMagic();
}
|
<|file_name|>document.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use document_loader::{DocumentLoader, LoadType};
use dom::attr::{Attr, AttrHelpers, AttrValue};
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::DocumentBinding;
use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, DocumentReadyState};
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::Bindings::NodeFilterBinding::NodeFilter;
use dom::bindings::codegen::Bindings::PerformanceBinding::PerformanceMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::InheritTypes::{DocumentDerived, EventCast, HTMLBodyElementCast};
use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLHeadElementCast, ElementCast, HTMLIFrameElementCast};
use dom::bindings::codegen::InheritTypes::{DocumentTypeCast, HTMLHtmlElementCast, NodeCast};
use dom::bindings::codegen::InheritTypes::{EventTargetCast, HTMLAnchorElementCast};
use dom::bindings::codegen::InheritTypes::{HTMLAnchorElementDerived, HTMLAppletElementDerived};
use dom::bindings::codegen::InheritTypes::{HTMLAreaElementDerived, HTMLEmbedElementDerived};
use dom::bindings::codegen::InheritTypes::{HTMLFormElementDerived, HTMLImageElementDerived};
use dom::bindings::codegen::InheritTypes::{HTMLScriptElementDerived, HTMLTitleElementDerived};
use dom::bindings::codegen::InheritTypes::ElementDerived;
use dom::bindings::codegen::UnionTypes::NodeOrString;
use dom::bindings::error::{ErrorResult, Fallible};
use dom::bindings::error::Error::{NotSupported, InvalidCharacter, Security};
use dom::bindings::error::Error::HierarchyRequest;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, Root, LayoutJS, MutNullableHeap};
use dom::bindings::js::RootedReference;
use dom::bindings::refcounted::Trusted;
use dom::bindings::trace::RootedVec;
use dom::bindings::utils::{reflect_dom_object, Reflectable};
use dom::bindings::utils::{xml_name_type, validate_and_extract};
use dom::bindings::utils::XMLName::InvalidXMLName;
use dom::comment::Comment;
use dom::customevent::CustomEvent;
use dom::documentfragment::DocumentFragment;
use dom::documenttype::DocumentType;
use dom::domimplementation::DOMImplementation;
use dom::element::{Element, ElementCreator, ElementHelpers, AttributeHandlers};
use dom::element::{ElementTypeId, ActivationElementHelpers, FocusElementHelpers};
use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers};
use dom::eventtarget::{EventTarget, EventTargetTypeId, EventTargetHelpers};
use dom::htmlanchorelement::HTMLAnchorElement;
use dom::htmlcollection::{HTMLCollection, CollectionFilter};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::htmlheadelement::HTMLHeadElement;
use dom::htmlhtmlelement::HTMLHtmlElement;
use dom::htmliframeelement::HTMLIFrameElement;
use dom::htmlscriptelement::HTMLScriptElement;
use dom::location::Location;
use dom::mouseevent::MouseEvent;
use dom::keyboardevent::KeyboardEvent;
use dom::messageevent::MessageEvent;
use dom::node::{self, Node, NodeHelpers, NodeTypeId, CloneChildrenFlag, NodeDamage, window_from_node};
use dom::nodelist::NodeList;
use dom::nodeiterator::NodeIterator;
use dom::text::Text;
use dom::processinginstruction::ProcessingInstruction;
use dom::range::Range;
use dom::servohtmlparser::ServoHTMLParser;
use dom::treewalker::TreeWalker;
use dom::uievent::UIEvent;
use dom::window::{Window, WindowHelpers, ReflowReason};
use layout_interface::{HitTestResponse, MouseOverResponse};
use msg::compositor_msg::ScriptListener;
use msg::constellation_msg::AnimationState;
use msg::constellation_msg::Msg as ConstellationMsg;
use msg::constellation_msg::{ConstellationChan, FocusType, Key, KeyState, KeyModifiers, MozBrowserEvent, SubpageId};
use msg::constellation_msg::{SUPER, ALT, SHIFT, CONTROL};
use net_traits::CookieSource::NonHTTP;
use net_traits::ControlMsg::{SetCookiesForUrl, GetCookiesForUrl};
use net_traits::{Metadata, PendingAsyncLoad, AsyncResponseTarget};
use script_task::Runnable;
use script_traits::{MouseButton, UntrustedNodeAddress};
use util::opts;
use util::str::{DOMString, split_html_space_chars};
use layout_interface::{ReflowGoal, ReflowQueryType};
use euclid::point::Point2D;
use html5ever::tree_builder::{QuirksMode, NoQuirks, LimitedQuirks, Quirks};
use ipc_channel::ipc;
use layout_interface::{LayoutChan, Msg};
use string_cache::{Atom, QualName};
use url::Url;
use js::jsapi::{JSContext, JSObject, JSRuntime};
use num::ToPrimitive;
use std::iter::FromIterator;
use std::borrow::ToOwned;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::ascii::AsciiExt;
use std::cell::{Cell, Ref, RefMut, RefCell};
use std::default::Default;
use std::ptr;
use std::sync::mpsc::channel;
use std::rc::Rc;
use time;
#[derive(JSTraceable, PartialEq)]
pub enum IsHTMLDocument {
HTMLDocument,
NonHTMLDocument,
}
// https://dom.spec.whatwg.org/#document
#[dom_struct]
#[derive(HeapSizeOf)]
pub struct Document {
node: Node,
window: JS<Window>,
idmap: DOMRefCell<HashMap<Atom, Vec<JS<Element>>>>,
implementation: MutNullableHeap<JS<DOMImplementation>>,
location: MutNullableHeap<JS<Location>>,
content_type: DOMString,
last_modified: Option<DOMString>,
encoding_name: DOMRefCell<DOMString>,
is_html_document: bool,
url: Url,
quirks_mode: Cell<QuirksMode>,
images: MutNullableHeap<JS<HTMLCollection>>,
embeds: MutNullableHeap<JS<HTMLCollection>>,
links: MutNullableHeap<JS<HTMLCollection>>,
forms: MutNullableHeap<JS<HTMLCollection>>,
scripts: MutNullableHeap<JS<HTMLCollection>>,
anchors: MutNullableHeap<JS<HTMLCollection>>,
applets: MutNullableHeap<JS<HTMLCollection>>,
ready_state: Cell<DocumentReadyState>,
/// The element that has most recently requested focus for itself.
possibly_focused: MutNullableHeap<JS<Element>>,
/// The element that currently has the document focus context.
focused: MutNullableHeap<JS<Element>>,
/// The script element that is currently executing.
current_script: MutNullableHeap<JS<HTMLScriptElement>>,
/// https://html.spec.whatwg.org/multipage/#concept-n-noscript
/// True if scripting is enabled for all scripts in this document
scripting_enabled: Cell<bool>,
/// https://html.spec.whatwg.org/multipage/#animation-frame-callback-identifier
/// Current identifier of animation frame callback
animation_frame_ident: Cell<i32>,
/// https://html.spec.whatwg.org/multipage/#list-of-animation-frame-callbacks
/// List of animation frame callbacks
#[ignore_heap_size_of = "closures are hard"]
animation_frame_list: RefCell<HashMap<i32, Box<Fn(f64)>>>,
/// Tracks all outstanding loads related to this document.
loader: DOMRefCell<DocumentLoader>,
/// The current active HTML parser, to allow resuming after interruptions.
current_parser: MutNullableHeap<JS<ServoHTMLParser>>,
/// When we should kick off a reflow. This happens during parsing.
reflow_timeout: Cell<Option<u64>>,
}
impl PartialEq for Document {
fn eq(&self, other: &Document) -> bool {
self as *const Document == &*other
}
}
impl DocumentDerived for EventTarget {
fn is_document(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Document)
}
}
#[derive(JSTraceable)]
struct ImagesFilter;
impl CollectionFilter for ImagesFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
elem.is_htmlimageelement()
}
}
#[derive(JSTraceable)]
struct EmbedsFilter;
impl CollectionFilter for EmbedsFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
elem.is_htmlembedelement()
}
}
#[derive(JSTraceable)]
struct LinksFilter;
impl CollectionFilter for LinksFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
(elem.is_htmlanchorelement() || elem.is_htmlareaelement()) &&
elem.has_attribute(&atom!("href"))
}
}
#[derive(JSTraceable)]
struct FormsFilter;
impl CollectionFilter for FormsFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
elem.is_htmlformelement()
}
}
#[derive(JSTraceable)]
struct ScriptsFilter;
impl CollectionFilter for ScriptsFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
elem.is_htmlscriptelement()
}
}
#[derive(JSTraceable)]
struct AnchorsFilter;
impl CollectionFilter for AnchorsFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
elem.is_htmlanchorelement() && elem.has_attribute(&atom!("href"))
}
}
#[derive(JSTraceable)]
struct AppletsFilter;
impl CollectionFilter for AppletsFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
elem.is_htmlappletelement()
}
}
pub trait DocumentHelpers<'a> {
fn loader(&self) -> Ref<DocumentLoader>;
fn mut_loader(&self) -> RefMut<DocumentLoader>;
fn window(self) -> Root<Window>;
fn encoding_name(self) -> Ref<'a, DOMString>;
fn is_html_document(self) -> bool;
fn is_fully_active(self) -> bool;
fn url(self) -> Url;
fn quirks_mode(self) -> QuirksMode;
fn set_quirks_mode(self, mode: QuirksMode);
fn set_encoding_name(self, name: DOMString);
fn content_changed(self, node: &Node, damage: NodeDamage);
fn content_and_heritage_changed(self, node: &Node, damage: NodeDamage);
fn reflow_if_reflow_timer_expired(self);
fn set_reflow_timeout(self, timeout: u64);
fn disarm_reflow_timeout(self);
fn unregister_named_element(self, to_unregister: &Element, id: Atom);
fn register_named_element(self, element: &Element, id: Atom);
fn load_anchor_href(self, href: DOMString);
fn find_fragment_node(self, fragid: DOMString) -> Option<Root<Element>>;
fn hit_test(self, point: &Point2D<f32>) -> Option<UntrustedNodeAddress>;
fn get_nodes_under_mouse(self, point: &Point2D<f32>) -> Vec<UntrustedNodeAddress>;
fn set_ready_state(self, state: DocumentReadyState);
fn get_focused_element(self) -> Option<Root<Element>>;
fn is_scripting_enabled(self) -> bool;
fn begin_focus_transaction(self);
fn request_focus(self, elem: &Element);
fn commit_focus_transaction(self, focus_type: FocusType);
fn title_changed(self);
fn send_title_to_compositor(self);
fn dirty_all_nodes(self);
fn dispatch_key_event(self,
key: Key,
state: KeyState,
modifiers: KeyModifiers,
compositor: &mut ScriptListener);
fn node_from_nodes_and_strings(self, nodes: Vec<NodeOrString>)
-> Fallible<Root<Node>>;
fn get_body_attribute(self, local_name: &Atom) -> DOMString;
fn set_body_attribute(self, local_name: &Atom, value: DOMString);
fn fire_mouse_event(self, point: Point2D<f32>,
target: &EventTarget,
event_name: String);
fn handle_mouse_event(self, js_runtime: *mut JSRuntime,
button: MouseButton, point: Point2D<f32>,
mouse_event_type: MouseEventType);
/// Handles a mouse-move event coming from the compositor.
fn handle_mouse_move_event(self,
js_runtime: *mut JSRuntime,
point: Point2D<f32>,
prev_mouse_over_targets: &mut RootedVec<JS<Node>>);
fn set_current_script(self, script: Option<&HTMLScriptElement>);
fn trigger_mozbrowser_event(self, event: MozBrowserEvent);
/// https://w3c.github.io/animation-timing/#dom-windowanimationtiming-requestanimationframe
fn request_animation_frame(self, callback: Box<Fn(f64, )>) -> i32;
/// https://w3c.github.io/animation-timing/#dom-windowanimationtiming-cancelanimationframe
fn cancel_animation_frame(self, ident: i32);
/// https://w3c.github.io/animation-timing/#dfn-invoke-callbacks-algorithm
fn invoke_animation_callbacks(self);
fn prepare_async_load(self, load: LoadType) -> PendingAsyncLoad;
fn load_async(self, load: LoadType, listener: AsyncResponseTarget);
fn load_sync(self, load: LoadType) -> Result<(Metadata, Vec<u8>), String>;
fn finish_load(self, load: LoadType);
fn set_current_parser(self, script: Option<&ServoHTMLParser>);
fn get_current_parser(self) -> Option<Root<ServoHTMLParser>>;
fn find_iframe(self, subpage_id: SubpageId) -> Option<Root<HTMLIFrameElement>>;
}
impl<'a> DocumentHelpers<'a> for &'a Document {
#[inline]
fn loader(&self) -> Ref<DocumentLoader> {
self.loader.borrow()
}
#[inline]
fn mut_loader(&self) -> RefMut<DocumentLoader> {
self.loader.borrow_mut()
}
#[inline]
fn window(self) -> Root<Window> {
self.window.root()
}
#[inline]
fn encoding_name(self) -> Ref<'a, DOMString> {
self.encoding_name.borrow()
}
#[inline]
fn is_html_document(self) -> bool {
self.is_html_document
}
// https://html.spec.whatwg.org/multipage/#fully-active
fn is_fully_active(self) -> bool {
let window = self.window.root();
let window = window.r();
let browsing_context = window.browsing_context();
let browsing_context = browsing_context.as_ref().unwrap();
let active_document = browsing_context.active_document();
if self != active_document.r() {
return false;
}
// FIXME: It should also check whether the browser context is top-level or not
true
}
// https://dom.spec.whatwg.org/#dom-document-url
fn url(self) -> Url {
self.url.clone()
}
fn quirks_mode(self) -> QuirksMode {<|fim▁hole|> }
fn set_quirks_mode(self, mode: QuirksMode) {
self.quirks_mode.set(mode);
if mode == Quirks {
let window = self.window.root();
let window = window.r();
let LayoutChan(ref layout_chan) = window.layout_chan();
layout_chan.send(Msg::SetQuirksMode).unwrap();
}
}
fn set_encoding_name(self, name: DOMString) {
*self.encoding_name.borrow_mut() = name;
}
fn content_changed(self, node: &Node, damage: NodeDamage) {
node.dirty(damage);
}
fn content_and_heritage_changed(self, node: &Node, damage: NodeDamage) {
node.force_dirty_ancestors(damage);
node.dirty(damage);
}
/// Reflows and disarms the timer if the reflow timer has expired.
fn reflow_if_reflow_timer_expired(self) {
if let Some(reflow_timeout) = self.reflow_timeout.get() {
if time::precise_time_ns() < reflow_timeout {
return
}
self.reflow_timeout.set(None);
let window = self.window.root();
window.r().reflow(ReflowGoal::ForDisplay,
ReflowQueryType::NoQuery,
ReflowReason::RefreshTick);
}
}
/// Schedules a reflow to be kicked off at the given `timeout` (in `time::precise_time_ns()`
/// units). This reflow happens even if the event loop is busy. This is used to display initial
/// page content during parsing.
fn set_reflow_timeout(self, timeout: u64) {
if let Some(existing_timeout) = self.reflow_timeout.get() {
if existing_timeout < timeout {
return
}
}
self.reflow_timeout.set(Some(timeout))
}
/// Disables any pending reflow timeouts.
fn disarm_reflow_timeout(self) {
self.reflow_timeout.set(None)
}
/// Remove any existing association between the provided id and any elements in this document.
fn unregister_named_element(self,
to_unregister: &Element,
id: Atom) {
debug!("Removing named element from document {:p}: {:p} id={}", self, to_unregister, id);
let mut idmap = self.idmap.borrow_mut();
let is_empty = match idmap.get_mut(&id) {
None => false,
Some(elements) => {
let position = elements.iter()
.map(|elem| elem.root())
.position(|element| element.r() == to_unregister)
.expect("This element should be in registered.");
elements.remove(position);
elements.is_empty()
}
};
if is_empty {
idmap.remove(&id);
}
}
/// Associate an element present in this document with the provided id.
fn register_named_element(self,
element: &Element,
id: Atom) {
debug!("Adding named element to document {:p}: {:p} id={}", self, element, id);
assert!({
let node = NodeCast::from_ref(element);
node.is_in_doc()
});
assert!(!id.is_empty());
let mut idmap = self.idmap.borrow_mut();
let root = self.GetDocumentElement().expect(
"The element is in the document, so there must be a document element.");
match idmap.entry(id) {
Vacant(entry) => {
entry.insert(vec![JS::from_ref(element)]);
}
Occupied(entry) => {
let elements = entry.into_mut();
let new_node = NodeCast::from_ref(element);
let mut head: usize = 0;
let root = NodeCast::from_ref(root.r());
for node in root.traverse_preorder() {
if let Some(elem) = ElementCast::to_ref(node.r()) {
if (*elements)[head].root().r() == elem {
head += 1;
}
if new_node == node.r() || head == elements.len() {
break;
}
}
}
elements.insert(head, JS::from_ref(element));
}
}
}
fn load_anchor_href(self, href: DOMString) {
let window = self.window.root();
window.r().load_url(href);
}
/// Attempt to find a named element in this page's document.
/// https://html.spec.whatwg.org/multipage/#the-indicated-part-of-the-document
fn find_fragment_node(self, fragid: DOMString) -> Option<Root<Element>> {
self.GetElementById(fragid.clone()).or_else(|| {
let check_anchor = |&node: &&HTMLAnchorElement| {
let elem = ElementCast::from_ref(node);
elem.get_attribute(&ns!(""), &atom!("name")).map_or(false, |attr| {
&**attr.r().value() == &*fragid
})
};
let doc_node = NodeCast::from_ref(self);
doc_node.traverse_preorder()
.filter_map(HTMLAnchorElementCast::to_root)
.find(|node| check_anchor(&node.r()))
.map(ElementCast::from_root)
})
}
fn hit_test(self, point: &Point2D<f32>) -> Option<UntrustedNodeAddress> {
let root = self.GetDocumentElement();
let root = match root.r() {
Some(root) => root,
None => return None,
};
let root = NodeCast::from_ref(root);
let win = self.window.root();
let address = match win.r().layout().hit_test(root.to_trusted_node_address(), *point) {
Ok(HitTestResponse(node_address)) => Some(node_address),
Err(()) => {
debug!("layout query error");
None
}
};
address
}
fn get_nodes_under_mouse(self, point: &Point2D<f32>) -> Vec<UntrustedNodeAddress> {
let root = self.GetDocumentElement();
let root = match root.r() {
Some(root) => root,
None => return vec!(),
};
let root = NodeCast::from_ref(root);
let win = self.window.root();
match win.r().layout().mouse_over(root.to_trusted_node_address(), *point) {
Ok(MouseOverResponse(node_address)) => node_address,
Err(()) => vec!(),
}
}
// https://html.spec.whatwg.org/multipage/#current-document-readiness
fn set_ready_state(self, state: DocumentReadyState) {
self.ready_state.set(state);
let window = self.window.root();
let event = Event::new(GlobalRef::Window(window.r()), "readystatechange".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
let target = EventTargetCast::from_ref(self);
let _ = event.r().fire(target);
}
/// Return whether scripting is enabled or not
fn is_scripting_enabled(self) -> bool {
self.scripting_enabled.get()
}
/// Return the element that currently has focus.
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#events-focusevent-doc-focus
fn get_focused_element(self) -> Option<Root<Element>> {
self.focused.get().map(Root::from_rooted)
}
/// Initiate a new round of checking for elements requesting focus. The last element to call
/// `request_focus` before `commit_focus_transaction` is called will receive focus.
fn begin_focus_transaction(self) {
self.possibly_focused.set(None);
}
/// Request that the given element receive focus once the current transaction is complete.
fn request_focus(self, elem: &Element) {
if elem.is_focusable_area() {
self.possibly_focused.set(Some(JS::from_ref(elem)))
}
}
/// Reassign the focus context to the element that last requested focus during this
/// transaction, or none if no elements requested it.
fn commit_focus_transaction(self, focus_type: FocusType) {
//TODO: dispatch blur, focus, focusout, and focusin events
if let Some(ref elem) = self.focused.get().map(|t| t.root()) {
let node = NodeCast::from_ref(elem.r());
node.set_focus_state(false);
}
self.focused.set(self.possibly_focused.get());
if let Some(ref elem) = self.focused.get().map(|t| t.root()) {
let node = NodeCast::from_ref(elem.r());
node.set_focus_state(true);
// Update the focus state for all elements in the focus chain.
// https://html.spec.whatwg.org/multipage/#focus-chain
if focus_type == FocusType::Element {
let window = self.window.root();
let ConstellationChan(ref chan) = window.r().constellation_chan();
let event = ConstellationMsg::Focus(window.r().pipeline());
chan.send(event).unwrap();
}
}
}
/// Handles any updates when the document's title has changed.
fn title_changed(self) {
// https://developer.mozilla.org/en-US/docs/Web/Events/mozbrowsertitlechange
self.trigger_mozbrowser_event(MozBrowserEvent::TitleChange(self.Title()));
self.send_title_to_compositor();
}
/// Sends this document's title to the compositor.
fn send_title_to_compositor(self) {
let window = self.window();
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let window = window.r();
let mut compositor = window.compositor();
compositor.set_title(window.pipeline(), Some(self.Title()));
}
fn dirty_all_nodes(self) {
let root = NodeCast::from_ref(self);
for node in root.traverse_preorder() {
node.r().dirty(NodeDamage::OtherNodeDamage)
}
}
fn handle_mouse_event(self, js_runtime: *mut JSRuntime,
_button: MouseButton, point: Point2D<f32>,
mouse_event_type: MouseEventType) {
let mouse_event_type_string = match mouse_event_type {
MouseEventType::Click => "click".to_owned(),
MouseEventType::MouseUp => "mouseup".to_owned(),
MouseEventType::MouseDown => "mousedown".to_owned(),
};
debug!("{}: at {:?}", mouse_event_type_string, point);
let node = match self.hit_test(&point) {
Some(node_address) => {
debug!("node address is {:?}", node_address.0);
node::from_untrusted_node_address(js_runtime, node_address)
},
None => return,
};
let el = match ElementCast::to_ref(node.r()) {
Some(el) => Root::from_ref(el),
None => {
let parent = node.r().GetParentNode();
match parent.and_then(ElementCast::to_root) {
Some(parent) => parent,
None => return,
}
},
};
let node = NodeCast::from_ref(el.r());
debug!("{} on {:?}", mouse_event_type_string, node.debug_str());
// Prevent click event if form control element is disabled.
if let MouseEventType::Click = mouse_event_type {
if node.click_event_filter_by_disabled_state() {
return;
}
self.begin_focus_transaction();
}
let window = self.window.root();
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-type-click
let x = point.x as i32;
let y = point.y as i32;
let clickCount = 1;
let event = MouseEvent::new(window.r(),
mouse_event_type_string,
EventBubbles::Bubbles,
EventCancelable::Cancelable,
Some(window.r()),
clickCount,
x, y, x, y,
false, false, false, false,
0i16,
None);
let event = EventCast::from_ref(event.r());
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#trusted-events
event.set_trusted(true);
// https://html.spec.whatwg.org/multipage/#run-authentic-click-activation-steps
match mouse_event_type {
MouseEventType::Click => el.authentic_click_activation(event),
_ => {
let target = EventTargetCast::from_ref(node);
event.fire(target);
},
}
if let MouseEventType::Click = mouse_event_type {
self.commit_focus_transaction(FocusType::Element);
}
window.r().reflow(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery, ReflowReason::MouseEvent);
}
fn fire_mouse_event(self,
point: Point2D<f32>,
target: &EventTarget,
event_name: String) {
let x = point.x.to_i32().unwrap_or(0);
let y = point.y.to_i32().unwrap_or(0);
let window = self.window.root();
let mouse_event = MouseEvent::new(window.r(),
event_name,
EventBubbles::Bubbles,
EventCancelable::Cancelable,
Some(window.r()),
0i32,
x, y, x, y,
false, false, false, false,
0i16,
None);
let event = EventCast::from_ref(mouse_event.r());
event.fire(target);
}
fn handle_mouse_move_event(self,
js_runtime: *mut JSRuntime,
point: Point2D<f32>,
prev_mouse_over_targets: &mut RootedVec<JS<Node>>) {
// Build a list of elements that are currently under the mouse.
let mouse_over_addresses = self.get_nodes_under_mouse(&point);
let mut mouse_over_targets: RootedVec<JS<Node>> = RootedVec::new();
for node_address in mouse_over_addresses.iter() {
let node = node::from_untrusted_node_address(js_runtime, *node_address);
mouse_over_targets.push(node.r().inclusive_ancestors()
.find(|node| node.r().is_element())
.map(|node| JS::from_rooted(&node)).unwrap());
};
// Remove hover from any elements in the previous list that are no longer
// under the mouse.
for target in prev_mouse_over_targets.iter() {
if !mouse_over_targets.contains(target) {
let target = target.root();
let target_ref = target.r();
if target_ref.get_hover_state() {
target_ref.set_hover_state(false);
let target = EventTargetCast::from_ref(target_ref);
self.fire_mouse_event(point, &target, "mouseout".to_owned());
}
}
}
// Set hover state for any elements in the current mouse over list.
// Check if any of them changed state to determine whether to
// force a reflow below.
for target in mouse_over_targets.r() {
if !target.get_hover_state() {
target.set_hover_state(true);
let target = EventTargetCast::from_ref(*target);
self.fire_mouse_event(point, target, "mouseover".to_owned());
}
}
// Send mousemove event to topmost target
if mouse_over_addresses.len() > 0 {
let top_most_node =
node::from_untrusted_node_address(js_runtime, mouse_over_addresses[0]);
let target = EventTargetCast::from_ref(top_most_node.r());
self.fire_mouse_event(point, target, "mousemove".to_owned());
}
// Store the current mouse over targets for next frame
prev_mouse_over_targets.clear();
prev_mouse_over_targets.append(&mut *mouse_over_targets);
let window = self.window.root();
window.r().reflow(ReflowGoal::ForDisplay,
ReflowQueryType::NoQuery,
ReflowReason::MouseEvent);
}
/// The entry point for all key processing for web content
fn dispatch_key_event(self,
key: Key,
state: KeyState,
modifiers: KeyModifiers,
compositor: &mut ScriptListener) {
let window = self.window.root();
let focused = self.get_focused_element();
let body = self.GetBody();
let target = match (&focused, &body) {
(&Some(ref focused), _) => EventTargetCast::from_ref(focused.r()),
(&None, &Some(ref body)) => EventTargetCast::from_ref(body.r()),
(&None, &None) => EventTargetCast::from_ref(window.r()),
};
let ctrl = modifiers.contains(CONTROL);
let alt = modifiers.contains(ALT);
let shift = modifiers.contains(SHIFT);
let meta = modifiers.contains(SUPER);
let is_composing = false;
let is_repeating = state == KeyState::Repeated;
let ev_type = match state {
KeyState::Pressed | KeyState::Repeated => "keydown",
KeyState::Released => "keyup",
}.to_owned();
let props = KeyboardEvent::key_properties(key, modifiers);
let keyevent = KeyboardEvent::new(window.r(), ev_type, true, true,
Some(window.r()), 0, Some(key),
props.key_string.to_owned(), props.code.to_owned(),
props.location, is_repeating, is_composing,
ctrl, alt, shift, meta,
None, props.key_code);
let event = EventCast::from_ref(keyevent.r());
event.fire(target);
let mut prevented = event.DefaultPrevented();
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keys-cancelable-keys
if state != KeyState::Released && props.is_printable() && !prevented {
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keypress-event-order
let event = KeyboardEvent::new(window.r(), "keypress".to_owned(),
true, true, Some(window.r()), 0, Some(key),
props.key_string.to_owned(), props.code.to_owned(),
props.location, is_repeating, is_composing,
ctrl, alt, shift, meta,
props.char_code, 0);
let ev = EventCast::from_ref(event.r());
ev.fire(target);
prevented = ev.DefaultPrevented();
// TODO: if keypress event is canceled, prevent firing input events
}
if !prevented {
compositor.send_key_event(key, state, modifiers);
}
// This behavior is unspecced
// We are supposed to dispatch synthetic click activation for Space and/or Return,
// however *when* we do it is up to us
// I'm dispatching it after the key event so the script has a chance to cancel it
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=27337
match key {
Key::Space if !prevented && state == KeyState::Released => {
let maybe_elem: Option<&Element> = ElementCast::to_ref(target);
maybe_elem.map(
|el| el.as_maybe_activatable().map(|a| a.synthetic_click_activation(ctrl, alt, shift, meta)));
}
Key::Enter if !prevented && state == KeyState::Released => {
let maybe_elem: Option<&Element> = ElementCast::to_ref(target);
maybe_elem.map(|el| el.as_maybe_activatable().map(|a| a.implicit_submission(ctrl, alt, shift, meta)));
}
_ => ()
}
window.r().reflow(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery, ReflowReason::KeyEvent);
}
fn node_from_nodes_and_strings(self, nodes: Vec<NodeOrString>)
-> Fallible<Root<Node>> {
if nodes.len() == 1 {
match nodes.into_iter().next().unwrap() {
NodeOrString::eNode(node) => Ok(node),
NodeOrString::eString(string) => {
Ok(NodeCast::from_root(self.CreateTextNode(string)))
},
}
} else {
let fragment = NodeCast::from_root(self.CreateDocumentFragment());
for node in nodes.into_iter() {
match node {
NodeOrString::eNode(node) => {
try!(fragment.r().AppendChild(node.r()));
},
NodeOrString::eString(string) => {
let node = NodeCast::from_root(self.CreateTextNode(string));
// No try!() here because appending a text node
// should not fail.
fragment.r().AppendChild(node.r()).unwrap();
}
}
}
Ok(fragment)
}
}
fn get_body_attribute(self, local_name: &Atom) -> DOMString {
match self.GetBody().and_then(HTMLBodyElementCast::to_root) {
Some(ref body) => {
ElementCast::from_ref(body.r()).get_string_attribute(local_name)
},
None => "".to_owned()
}
}
fn set_body_attribute(self, local_name: &Atom, value: DOMString) {
if let Some(ref body) = self.GetBody().and_then(HTMLBodyElementCast::to_root) {
ElementCast::from_ref(body.r()).set_string_attribute(local_name, value);
}
}
fn set_current_script(self, script: Option<&HTMLScriptElement>) {
self.current_script.set(script.map(JS::from_ref));
}
fn trigger_mozbrowser_event(self, event: MozBrowserEvent) {
if opts::experimental_enabled() {
let window = self.window.root();
if let Some((containing_pipeline_id, subpage_id)) = window.r().parent_info() {
let ConstellationChan(ref chan) = window.r().constellation_chan();
let event = ConstellationMsg::MozBrowserEvent(containing_pipeline_id,
subpage_id,
event);
chan.send(event).unwrap();
}
}
}
/// https://w3c.github.io/animation-timing/#dom-windowanimationtiming-requestanimationframe
fn request_animation_frame(self, callback: Box<Fn(f64, )>) -> i32 {
let window = self.window.root();
let window = window.r();
let ident = self.animation_frame_ident.get() + 1;
self.animation_frame_ident.set(ident);
self.animation_frame_list.borrow_mut().insert(ident, callback);
// TODO: Should tick animation only when document is visible
let ConstellationChan(ref chan) = window.constellation_chan();
let event = ConstellationMsg::ChangeRunningAnimationsState(window.pipeline(),
AnimationState::AnimationCallbacksPresent);
chan.send(event).unwrap();
ident
}
/// https://w3c.github.io/animation-timing/#dom-windowanimationtiming-cancelanimationframe
fn cancel_animation_frame(self, ident: i32) {
self.animation_frame_list.borrow_mut().remove(&ident);
if self.animation_frame_list.borrow().len() == 0 {
let window = self.window.root();
let window = window.r();
let ConstellationChan(ref chan) = window.constellation_chan();
let event = ConstellationMsg::ChangeRunningAnimationsState(window.pipeline(),
AnimationState::NoAnimationCallbacksPresent);
chan.send(event).unwrap();
}
}
/// https://w3c.github.io/animation-timing/#dfn-invoke-callbacks-algorithm
fn invoke_animation_callbacks(self) {
let animation_frame_list;
{
let mut list = self.animation_frame_list.borrow_mut();
animation_frame_list = Vec::from_iter(list.drain());
let window = self.window.root();
let window = window.r();
let ConstellationChan(ref chan) = window.constellation_chan();
let event = ConstellationMsg::ChangeRunningAnimationsState(window.pipeline(),
AnimationState::NoAnimationCallbacksPresent);
chan.send(event).unwrap();
}
let window = self.window.root();
let window = window.r();
let performance = window.Performance();
let performance = performance.r();
for (_, callback) in animation_frame_list {
callback(*performance.Now());
}
window.reflow(ReflowGoal::ForDisplay,
ReflowQueryType::NoQuery,
ReflowReason::RequestAnimationFrame);
}
fn prepare_async_load(self, load: LoadType) -> PendingAsyncLoad {
let mut loader = self.loader.borrow_mut();
loader.prepare_async_load(load)
}
fn load_async(self, load: LoadType, listener: AsyncResponseTarget) {
let mut loader = self.loader.borrow_mut();
loader.load_async(load, listener)
}
fn load_sync(self, load: LoadType) -> Result<(Metadata, Vec<u8>), String> {
let mut loader = self.loader.borrow_mut();
loader.load_sync(load)
}
fn finish_load(self, load: LoadType) {
let mut loader = self.loader.borrow_mut();
loader.finish_load(load);
}
fn set_current_parser(self, script: Option<&ServoHTMLParser>) {
self.current_parser.set(script.map(JS::from_ref));
}
fn get_current_parser(self) -> Option<Root<ServoHTMLParser>> {
self.current_parser.get().map(Root::from_rooted)
}
/// Find an iframe element in the document.
fn find_iframe(self, subpage_id: SubpageId) -> Option<Root<HTMLIFrameElement>> {
NodeCast::from_ref(self).traverse_preorder()
.filter_map(HTMLIFrameElementCast::to_root)
.find(|node| node.r().subpage_id() == Some(subpage_id))
}
}
pub enum MouseEventType {
Click,
MouseDown,
MouseUp,
}
#[derive(PartialEq)]
pub enum DocumentSource {
FromParser,
NotFromParser,
}
pub trait LayoutDocumentHelpers {
#[allow(unsafe_code)]
unsafe fn is_html_document_for_layout(&self) -> bool;
}
impl LayoutDocumentHelpers for LayoutJS<Document> {
#[allow(unrooted_must_root)]
#[inline]
#[allow(unsafe_code)]
unsafe fn is_html_document_for_layout(&self) -> bool {
(*self.unsafe_get()).is_html_document
}
}
impl Document {
fn new_inherited(window: &Window,
url: Option<Url>,
is_html_document: IsHTMLDocument,
content_type: Option<DOMString>,
last_modified: Option<DOMString>,
source: DocumentSource,
doc_loader: DocumentLoader) -> Document {
let url = url.unwrap_or_else(|| Url::parse("about:blank").unwrap());
let ready_state = if source == DocumentSource::FromParser {
DocumentReadyState::Loading
} else {
DocumentReadyState::Complete
};
Document {
node: Node::new_without_doc(NodeTypeId::Document),
window: JS::from_ref(window),
idmap: DOMRefCell::new(HashMap::new()),
implementation: Default::default(),
location: Default::default(),
content_type: match content_type {
Some(string) => string,
None => match is_html_document {
// https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument
IsHTMLDocument::HTMLDocument => "text/html".to_owned(),
// https://dom.spec.whatwg.org/#concept-document-content-type
IsHTMLDocument::NonHTMLDocument => "application/xml".to_owned()
}
},
last_modified: last_modified,
url: url,
// https://dom.spec.whatwg.org/#concept-document-quirks
quirks_mode: Cell::new(NoQuirks),
// https://dom.spec.whatwg.org/#concept-document-encoding
encoding_name: DOMRefCell::new("UTF-8".to_owned()),
is_html_document: is_html_document == IsHTMLDocument::HTMLDocument,
images: Default::default(),
embeds: Default::default(),
links: Default::default(),
forms: Default::default(),
scripts: Default::default(),
anchors: Default::default(),
applets: Default::default(),
ready_state: Cell::new(ready_state),
possibly_focused: Default::default(),
focused: Default::default(),
current_script: Default::default(),
scripting_enabled: Cell::new(true),
animation_frame_ident: Cell::new(0),
animation_frame_list: RefCell::new(HashMap::new()),
loader: DOMRefCell::new(doc_loader),
current_parser: Default::default(),
reflow_timeout: Cell::new(None),
}
}
// https://dom.spec.whatwg.org/#dom-document
pub fn Constructor(global: GlobalRef) -> Fallible<Root<Document>> {
let win = global.as_window();
let doc = win.Document();
let doc = doc.r();
let docloader = DocumentLoader::new(&*doc.loader());
Ok(Document::new(win, None,
IsHTMLDocument::NonHTMLDocument, None,
None, DocumentSource::NotFromParser, docloader))
}
pub fn new(window: &Window,
url: Option<Url>,
doctype: IsHTMLDocument,
content_type: Option<DOMString>,
last_modified: Option<DOMString>,
source: DocumentSource,
doc_loader: DocumentLoader) -> Root<Document> {
let document = reflect_dom_object(box Document::new_inherited(window, url, doctype,
content_type, last_modified,
source, doc_loader),
GlobalRef::Window(window),
DocumentBinding::Wrap);
{
let node = NodeCast::from_ref(document.r());
node.set_owner_doc(document.r());
}
document
}
}
trait PrivateDocumentHelpers {
fn create_node_list<F: Fn(&Node) -> bool>(self, callback: F) -> Root<NodeList>;
fn get_html_element(self) -> Option<Root<HTMLHtmlElement>>;
}
impl<'a> PrivateDocumentHelpers for &'a Document {
fn create_node_list<F: Fn(&Node) -> bool>(self, callback: F) -> Root<NodeList> {
let window = self.window.root();
let doc = self.GetDocumentElement();
let maybe_node = doc.r().map(NodeCast::from_ref);
let iter = maybe_node.iter().flat_map(|node| node.traverse_preorder())
.filter(|node| callback(node.r()));
NodeList::new_simple_list(window.r(), iter)
}
fn get_html_element(self) -> Option<Root<HTMLHtmlElement>> {
self.GetDocumentElement()
.r()
.and_then(HTMLHtmlElementCast::to_ref)
.map(Root::from_ref)
}
}
trait PrivateClickEventHelpers {
fn click_event_filter_by_disabled_state(self) -> bool;
}
impl<'a> PrivateClickEventHelpers for &'a Node {
fn click_event_filter_by_disabled_state(self) -> bool {
match self.type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) |
// NodeTypeId::Element(ElementTypeId::HTMLKeygenElement) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptionElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement))
if self.get_disabled_state() => true,
_ => false
}
}
}
impl<'a> DocumentMethods for &'a Document {
// https://dom.spec.whatwg.org/#dom-document-implementation
fn Implementation(self) -> Root<DOMImplementation> {
self.implementation.or_init(|| DOMImplementation::new(self))
}
// https://dom.spec.whatwg.org/#dom-document-url
fn URL(self) -> DOMString {
self.url().serialize()
}
// https://html.spec.whatwg.org/multipage/#dom-document-activeelement
fn GetActiveElement(self) -> Option<Root<Element>> {
// TODO: Step 2.
match self.get_focused_element() {
Some(element) => Some(element), // Step 3. and 4.
None => match self.GetBody() { // Step 5.
Some(body) => Some(ElementCast::from_root(body)),
None => self.GetDocumentElement(),
}
}
}
// https://dom.spec.whatwg.org/#dom-document-documenturi
fn DocumentURI(self) -> DOMString {
self.URL()
}
// https://dom.spec.whatwg.org/#dom-document-compatmode
fn CompatMode(self) -> DOMString {
match self.quirks_mode.get() {
LimitedQuirks | NoQuirks => "CSS1Compat".to_owned(),
Quirks => "BackCompat".to_owned()
}
}
// https://dom.spec.whatwg.org/#dom-document-characterset
fn CharacterSet(self) -> DOMString {
self.encoding_name.borrow().clone()
}
// https://dom.spec.whatwg.org/#dom-document-inputencoding
fn InputEncoding(self) -> DOMString {
self.encoding_name.borrow().clone()
}
// https://dom.spec.whatwg.org/#dom-document-content_type
fn ContentType(self) -> DOMString {
self.content_type.clone()
}
// https://dom.spec.whatwg.org/#dom-document-doctype
fn GetDoctype(self) -> Option<Root<DocumentType>> {
let node = NodeCast::from_ref(self);
node.children()
.filter_map(|c| DocumentTypeCast::to_ref(c.r()).map(Root::from_ref))
.next()
}
// https://dom.spec.whatwg.org/#dom-document-documentelement
fn GetDocumentElement(self) -> Option<Root<Element>> {
let node = NodeCast::from_ref(self);
node.child_elements().next()
}
// https://dom.spec.whatwg.org/#dom-document-getelementsbytagname
fn GetElementsByTagName(self, tag_name: DOMString) -> Root<HTMLCollection> {
let window = self.window.root();
HTMLCollection::by_tag_name(window.r(), NodeCast::from_ref(self), tag_name)
}
// https://dom.spec.whatwg.org/#dom-document-getelementsbytagnamens
fn GetElementsByTagNameNS(self, maybe_ns: Option<DOMString>, tag_name: DOMString)
-> Root<HTMLCollection> {
let window = self.window.root();
HTMLCollection::by_tag_name_ns(window.r(), NodeCast::from_ref(self), tag_name, maybe_ns)
}
// https://dom.spec.whatwg.org/#dom-document-getelementsbyclassname
fn GetElementsByClassName(self, classes: DOMString) -> Root<HTMLCollection> {
let window = self.window.root();
HTMLCollection::by_class_name(window.r(), NodeCast::from_ref(self), classes)
}
// https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid
fn GetElementById(self, id: DOMString) -> Option<Root<Element>> {
let id = Atom::from_slice(&id);
self.idmap.borrow().get(&id).map(|ref elements| (*elements)[0].root())
}
// https://dom.spec.whatwg.org/#dom-document-createelement
fn CreateElement(self, mut local_name: DOMString) -> Fallible<Root<Element>> {
if xml_name_type(&local_name) == InvalidXMLName {
debug!("Not a valid element name");
return Err(InvalidCharacter);
}
if self.is_html_document {
local_name = local_name.to_ascii_lowercase()
}
let name = QualName::new(ns!(HTML), Atom::from_slice(&local_name));
Ok(Element::create(name, None, self, ElementCreator::ScriptCreated))
}
// https://dom.spec.whatwg.org/#dom-document-createelementns
fn CreateElementNS(self,
namespace: Option<DOMString>,
qualified_name: DOMString) -> Fallible<Root<Element>> {
let (namespace, prefix, local_name) =
try!(validate_and_extract(namespace, &qualified_name));
let name = QualName::new(namespace, local_name);
Ok(Element::create(name, prefix, self, ElementCreator::ScriptCreated))
}
// https://dom.spec.whatwg.org/#dom-document-createattribute
fn CreateAttribute(self, local_name: DOMString) -> Fallible<Root<Attr>> {
if xml_name_type(&local_name) == InvalidXMLName {
debug!("Not a valid element name");
return Err(InvalidCharacter);
}
let window = self.window.root();
let name = Atom::from_slice(&local_name);
// repetition used because string_cache::atom::Atom is non-copyable
let l_name = Atom::from_slice(&local_name);
let value = AttrValue::String("".to_owned());
Ok(Attr::new(window.r(), name, value, l_name, ns!(""), None, None))
}
// https://dom.spec.whatwg.org/#dom-document-createattributens
fn CreateAttributeNS(self, namespace: Option<DOMString>, qualified_name: DOMString)
-> Fallible<Root<Attr>> {
let (namespace, prefix, local_name) =
try!(validate_and_extract(namespace, &qualified_name));
let window = self.window.root();
let value = AttrValue::String("".to_owned());
let qualified_name = Atom::from_slice(&qualified_name);
Ok(Attr::new(window.r(), local_name, value, qualified_name,
namespace, prefix, None))
}
// https://dom.spec.whatwg.org/#dom-document-createdocumentfragment
fn CreateDocumentFragment(self) -> Root<DocumentFragment> {
DocumentFragment::new(self)
}
// https://dom.spec.whatwg.org/#dom-document-createtextnode
fn CreateTextNode(self, data: DOMString) -> Root<Text> {
Text::new(data, self)
}
// https://dom.spec.whatwg.org/#dom-document-createcomment
fn CreateComment(self, data: DOMString) -> Root<Comment> {
Comment::new(data, self)
}
// https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction
fn CreateProcessingInstruction(self, target: DOMString, data: DOMString) ->
Fallible<Root<ProcessingInstruction>> {
// Step 1.
if xml_name_type(&target) == InvalidXMLName {
return Err(InvalidCharacter);
}
// Step 2.
if data.contains("?>") {
return Err(InvalidCharacter);
}
// Step 3.
Ok(ProcessingInstruction::new(target, data, self))
}
// https://dom.spec.whatwg.org/#dom-document-importnode
fn ImportNode(self, node: &Node, deep: bool) -> Fallible<Root<Node>> {
// Step 1.
if node.is_document() {
return Err(NotSupported);
}
// Step 2.
let clone_children = match deep {
true => CloneChildrenFlag::CloneChildren,
false => CloneChildrenFlag::DoNotCloneChildren
};
Ok(Node::clone(node, Some(self), clone_children))
}
// https://dom.spec.whatwg.org/#dom-document-adoptnode
fn AdoptNode(self, node: &Node) -> Fallible<Root<Node>> {
// Step 1.
if node.is_document() {
return Err(NotSupported);
}
// Step 2.
Node::adopt(node, self);
// Step 3.
Ok(Root::from_ref(node))
}
// https://dom.spec.whatwg.org/#dom-document-createevent
fn CreateEvent(self, interface: DOMString) -> Fallible<Root<Event>> {
let window = self.window.root();
match &*interface.to_ascii_lowercase() {
"uievents" | "uievent" => Ok(EventCast::from_root(
UIEvent::new_uninitialized(window.r()))),
"mouseevents" | "mouseevent" => Ok(EventCast::from_root(
MouseEvent::new_uninitialized(window.r()))),
"customevent" => Ok(EventCast::from_root(
CustomEvent::new_uninitialized(GlobalRef::Window(window.r())))),
"htmlevents" | "events" | "event" => Ok(Event::new_uninitialized(
GlobalRef::Window(window.r()))),
"keyboardevent" | "keyevents" => Ok(EventCast::from_root(
KeyboardEvent::new_uninitialized(window.r()))),
"messageevent" => Ok(EventCast::from_root(
MessageEvent::new_uninitialized(GlobalRef::Window(window.r())))),
_ => Err(NotSupported)
}
}
// https://html.spec.whatwg.org/#dom-document-lastmodified
fn LastModified(self) -> DOMString {
match self.last_modified {
Some(ref t) => t.clone(),
None => time::now().strftime("%m/%d/%Y %H:%M:%S").unwrap().to_string(),
}
}
// https://dom.spec.whatwg.org/#dom-document-createrange
fn CreateRange(self) -> Root<Range> {
Range::new_with_doc(self)
}
// https://dom.spec.whatwg.org/#dom-document-createnodeiteratorroot-whattoshow-filter
fn CreateNodeIterator(self, root: &Node, whatToShow: u32, filter: Option<Rc<NodeFilter>>)
-> Root<NodeIterator> {
NodeIterator::new(self, root, whatToShow, filter)
}
// https://dom.spec.whatwg.org/#dom-document-createtreewalker
fn CreateTreeWalker(self, root: &Node, whatToShow: u32, filter: Option<Rc<NodeFilter>>)
-> Root<TreeWalker> {
TreeWalker::new(self, root, whatToShow, filter)
}
// https://html.spec.whatwg.org/#document.title
fn Title(self) -> DOMString {
let title = self.GetDocumentElement().and_then(|root| {
if root.r().namespace() == &ns!(SVG) && root.r().local_name() == &atom!("svg") {
// Step 1.
NodeCast::from_ref(root.r()).child_elements().find(|node| {
node.r().namespace() == &ns!(SVG) &&
node.r().local_name() == &atom!("title")
}).map(NodeCast::from_root)
} else {
// Step 2.
NodeCast::from_ref(root.r())
.traverse_preorder()
.find(|node| node.r().is_htmltitleelement())
}
});
match title {
None => DOMString::new(),
Some(ref title) => {
// Steps 3-4.
let value = Node::collect_text_contents(title.r().children());
split_html_space_chars(&value).collect::<Vec<_>>().join(" ")
},
}
}
// https://html.spec.whatwg.org/#document.title
fn SetTitle(self, title: DOMString) {
let root = match self.GetDocumentElement() {
Some(root) => root,
None => return,
};
let elem = if root.r().namespace() == &ns!(SVG) &&
root.r().local_name() == &atom!("svg") {
let elem = NodeCast::from_ref(root.r()).child_elements().find(|node| {
node.r().namespace() == &ns!(SVG) &&
node.r().local_name() == &atom!("title")
});
match elem {
Some(elem) => NodeCast::from_root(elem),
None => {
let name = QualName::new(ns!(SVG), atom!("title"));
let elem = Element::create(name, None, self,
ElementCreator::ScriptCreated);
NodeCast::from_ref(root.r())
.AppendChild(NodeCast::from_ref(elem.r()))
.unwrap()
}
}
} else if root.r().namespace() == &ns!(HTML) {
let elem = NodeCast::from_ref(root.r())
.traverse_preorder()
.find(|node| node.r().is_htmltitleelement());
match elem {
Some(elem) => elem,
None => {
match self.GetHead() {
Some(head) => {
let name = QualName::new(ns!(HTML), atom!("title"));
let elem = Element::create(name, None, self,
ElementCreator::ScriptCreated);
NodeCast::from_ref(head.r())
.AppendChild(NodeCast::from_ref(elem.r()))
.unwrap()
},
None => return,
}
}
}
} else {
return
};
elem.r().SetTextContent(Some(title));
}
// https://html.spec.whatwg.org/#dom-document-head
fn GetHead(self) -> Option<Root<HTMLHeadElement>> {
self.get_html_element().and_then(|root| {
let node = NodeCast::from_ref(root.r());
node.children()
.filter_map(|c| HTMLHeadElementCast::to_ref(c.r()).map(Root::from_ref))
.next()
})
}
// https://html.spec.whatwg.org/#dom-document-currentscript
fn GetCurrentScript(self) -> Option<Root<HTMLScriptElement>> {
self.current_script.get().map(Root::from_rooted)
}
// https://html.spec.whatwg.org/#dom-document-body
fn GetBody(self) -> Option<Root<HTMLElement>> {
self.get_html_element().and_then(|root| {
let node = NodeCast::from_ref(root.r());
node.children().find(|child| {
match child.r().type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBodyElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFrameSetElement)) => true,
_ => false
}
}).map(|node| {
Root::from_ref(HTMLElementCast::to_ref(node.r()).unwrap())
})
})
}
// https://html.spec.whatwg.org/#dom-document-body
fn SetBody(self, new_body: Option<&HTMLElement>) -> ErrorResult {
// Step 1.
let new_body = match new_body {
Some(new_body) => new_body,
None => return Err(HierarchyRequest),
};
let node = NodeCast::from_ref(new_body);
match node.type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBodyElement)) |
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFrameSetElement)) => {}
_ => return Err(HierarchyRequest)
}
// Step 2.
let old_body = self.GetBody();
if old_body.as_ref().map(|body| body.r()) == Some(new_body) {
return Ok(());
}
match (self.get_html_element(), &old_body) {
// Step 3.
(Some(ref root), &Some(ref child)) => {
let root = NodeCast::from_ref(root.r());
let child = NodeCast::from_ref(child.r());
let new_body = NodeCast::from_ref(new_body);
assert!(root.ReplaceChild(new_body, child).is_ok())
},
// Step 4.
(None, _) => return Err(HierarchyRequest),
// Step 5.
(Some(ref root), &None) => {
let root = NodeCast::from_ref(root.r());
let new_body = NodeCast::from_ref(new_body);
assert!(root.AppendChild(new_body).is_ok());
}
}
Ok(())
}
// https://html.spec.whatwg.org/#dom-document-getelementsbyname
fn GetElementsByName(self, name: DOMString) -> Root<NodeList> {
self.create_node_list(|node| {
let element = match ElementCast::to_ref(node) {
Some(element) => element,
None => return false,
};
if element.namespace() != &ns!(HTML) {
return false;
}
element.get_attribute(&ns!(""), &atom!("name")).map_or(false, |attr| {
&**attr.r().value() == &*name
})
})
}
// https://html.spec.whatwg.org/#dom-document-images
fn Images(self) -> Root<HTMLCollection> {
self.images.or_init(|| {
let window = self.window.root();
let root = NodeCast::from_ref(self);
let filter = box ImagesFilter;
HTMLCollection::create(window.r(), root, filter)
})
}
// https://html.spec.whatwg.org/#dom-document-embeds
fn Embeds(self) -> Root<HTMLCollection> {
self.embeds.or_init(|| {
let window = self.window.root();
let root = NodeCast::from_ref(self);
let filter = box EmbedsFilter;
HTMLCollection::create(window.r(), root, filter)
})
}
// https://html.spec.whatwg.org/#dom-document-plugins
fn Plugins(self) -> Root<HTMLCollection> {
self.Embeds()
}
// https://html.spec.whatwg.org/#dom-document-links
fn Links(self) -> Root<HTMLCollection> {
self.links.or_init(|| {
let window = self.window.root();
let root = NodeCast::from_ref(self);
let filter = box LinksFilter;
HTMLCollection::create(window.r(), root, filter)
})
}
// https://html.spec.whatwg.org/#dom-document-forms
fn Forms(self) -> Root<HTMLCollection> {
self.forms.or_init(|| {
let window = self.window.root();
let root = NodeCast::from_ref(self);
let filter = box FormsFilter;
HTMLCollection::create(window.r(), root, filter)
})
}
// https://html.spec.whatwg.org/#dom-document-scripts
fn Scripts(self) -> Root<HTMLCollection> {
self.scripts.or_init(|| {
let window = self.window.root();
let root = NodeCast::from_ref(self);
let filter = box ScriptsFilter;
HTMLCollection::create(window.r(), root, filter)
})
}
// https://html.spec.whatwg.org/#dom-document-anchors
fn Anchors(self) -> Root<HTMLCollection> {
self.anchors.or_init(|| {
let window = self.window.root();
let root = NodeCast::from_ref(self);
let filter = box AnchorsFilter;
HTMLCollection::create(window.r(), root, filter)
})
}
// https://html.spec.whatwg.org/#dom-document-applets
fn Applets(self) -> Root<HTMLCollection> {
// FIXME: This should be return OBJECT elements containing applets.
self.applets.or_init(|| {
let window = self.window.root();
let root = NodeCast::from_ref(self);
let filter = box AppletsFilter;
HTMLCollection::create(window.r(), root, filter)
})
}
// https://html.spec.whatwg.org/#dom-document-location
fn Location(self) -> Root<Location> {
let window = self.window.root();
let window = window.r();
self.location.or_init(|| Location::new(window))
}
// https://dom.spec.whatwg.org/#dom-parentnode-children
fn Children(self) -> Root<HTMLCollection> {
let window = self.window.root();
HTMLCollection::children(window.r(), NodeCast::from_ref(self))
}
// https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild
fn GetFirstElementChild(self) -> Option<Root<Element>> {
NodeCast::from_ref(self).child_elements().next()
}
// https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild
fn GetLastElementChild(self) -> Option<Root<Element>> {
NodeCast::from_ref(self).rev_children().filter_map(ElementCast::to_root).next()
}
// https://dom.spec.whatwg.org/#dom-parentnode-childelementcount
fn ChildElementCount(self) -> u32 {
NodeCast::from_ref(self).child_elements().count() as u32
}
// https://dom.spec.whatwg.org/#dom-parentnode-prepend
fn Prepend(self, nodes: Vec<NodeOrString>) -> ErrorResult {
NodeCast::from_ref(self).prepend(nodes)
}
// https://dom.spec.whatwg.org/#dom-parentnode-append
fn Append(self, nodes: Vec<NodeOrString>) -> ErrorResult {
NodeCast::from_ref(self).append(nodes)
}
// https://dom.spec.whatwg.org/#dom-parentnode-queryselector
fn QuerySelector(self, selectors: DOMString) -> Fallible<Option<Root<Element>>> {
let root = NodeCast::from_ref(self);
root.query_selector(selectors)
}
// https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall
fn QuerySelectorAll(self, selectors: DOMString) -> Fallible<Root<NodeList>> {
let root = NodeCast::from_ref(self);
root.query_selector_all(selectors)
}
// https://html.spec.whatwg.org/multipage/#dom-document-readystate
fn ReadyState(self) -> DocumentReadyState {
self.ready_state.get()
}
// https://html.spec.whatwg.org/multipage/#dom-document-defaultview
fn DefaultView(self) -> Root<Window> {
self.window.root()
}
// https://html.spec.whatwg.org/multipage/#dom-document-cookie
fn GetCookie(self) -> Fallible<DOMString> {
//TODO: return empty string for cookie-averse Document
let url = self.url();
if !is_scheme_host_port_tuple(&url) {
return Err(Security);
}
let window = self.window.root();
let (tx, rx) = ipc::channel().unwrap();
let _ = window.r().resource_task().send(GetCookiesForUrl(url, tx, NonHTTP));
let cookies = rx.recv().unwrap();
Ok(cookies.unwrap_or("".to_owned()))
}
// https://html.spec.whatwg.org/multipage/#dom-document-cookie
fn SetCookie(self, cookie: DOMString) -> ErrorResult {
//TODO: ignore for cookie-averse Document
let url = self.url();
if !is_scheme_host_port_tuple(&url) {
return Err(Security);
}
let window = self.window.root();
let _ = window.r().resource_task().send(SetCookiesForUrl(url, cookie, NonHTTP));
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-document-bgcolor
fn BgColor(self) -> DOMString {
self.get_body_attribute(&atom!("bgcolor"))
}
// https://html.spec.whatwg.org/multipage/#dom-document-bgcolor
fn SetBgColor(self, value: DOMString) {
self.set_body_attribute(&atom!("bgcolor"), value)
}
// https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter
fn NamedGetter(self, _cx: *mut JSContext, name: DOMString, found: &mut bool)
-> *mut JSObject {
#[derive(JSTraceable)]
struct NamedElementFilter {
name: Atom,
}
impl CollectionFilter for NamedElementFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
filter_by_name(&self.name, NodeCast::from_ref(elem))
}
}
// https://html.spec.whatwg.org/#dom-document-nameditem-filter
fn filter_by_name(name: &Atom, node: &Node) -> bool {
let html_elem_type = match node.type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
_ => return false,
};
let elem = match ElementCast::to_ref(node) {
Some(elem) => elem,
None => return false,
};
match html_elem_type {
HTMLElementTypeId::HTMLAppletElement => {
match elem.get_attribute(&ns!(""), &atom!("name")) {
Some(ref attr) if attr.r().value().atom() == Some(name) => true,
_ => {
match elem.get_attribute(&ns!(""), &atom!("id")) {
Some(ref attr) => attr.r().value().atom() == Some(name),
None => false,
}
},
}
},
HTMLElementTypeId::HTMLFormElement => {
match elem.get_attribute(&ns!(""), &atom!("name")) {
Some(ref attr) => attr.r().value().atom() == Some(name),
None => false,
}
},
HTMLElementTypeId::HTMLImageElement => {
match elem.get_attribute(&ns!(""), &atom!("name")) {
Some(ref attr) => {
if attr.r().value().atom() == Some(name) {
true
} else {
match elem.get_attribute(&ns!(""), &atom!("id")) {
Some(ref attr) => attr.r().value().atom() == Some(name),
None => false,
}
}
},
None => false,
}
},
// TODO: Handle <embed>, <iframe> and <object>.
_ => false,
}
}
let name = Atom::from_slice(&name);
let root = NodeCast::from_ref(self);
{
// Step 1.
let mut elements = root.traverse_preorder().filter(|node| {
filter_by_name(&name, node.r())
}).peekable();
if let Some(first) = elements.next() {
if elements.is_empty() {
*found = true;
// TODO: Step 2.
// Step 3.
return first.r().reflector().get_jsobject().get()
}
} else {
*found = false;
return ptr::null_mut();
}
}
// Step 4.
*found = true;
let window = self.window();
let filter = NamedElementFilter { name: name };
let collection = HTMLCollection::create(window.r(), root, box filter);
collection.r().reflector().get_jsobject().get()
}
global_event_handlers!();
event_handler!(readystatechange, GetOnreadystatechange, SetOnreadystatechange);
}
fn is_scheme_host_port_tuple(url: &Url) -> bool {
url.host().is_some() && url.port_or_default().is_some()
}
pub enum DocumentProgressTask {
DOMContentLoaded,
Load,
}
pub struct DocumentProgressHandler {
addr: Trusted<Document>,
task: DocumentProgressTask,
}
impl DocumentProgressHandler {
pub fn new(addr: Trusted<Document>, task: DocumentProgressTask) -> DocumentProgressHandler {
DocumentProgressHandler {
addr: addr,
task: task,
}
}
fn dispatch_dom_content_loaded(&self) {
let document = self.addr.root();
let window = document.r().window();
let event = Event::new(GlobalRef::Window(window.r()), "DOMContentLoaded".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
let doctarget = EventTargetCast::from_ref(document.r());
let _ = doctarget.DispatchEvent(event.r());
window.r().reflow(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery, ReflowReason::DOMContentLoaded);
}
fn set_ready_state_complete(&self) {
let document = self.addr.root();
document.r().set_ready_state(DocumentReadyState::Complete);
}
fn dispatch_load(&self) {
let document = self.addr.root();
let window = document.r().window();
let event = Event::new(GlobalRef::Window(window.r()), "load".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
let wintarget = EventTargetCast::from_ref(window.r());
let doctarget = EventTargetCast::from_ref(document.r());
event.r().set_trusted(true);
let _ = wintarget.dispatch_event_with_target(doctarget, event.r());
let window_ref = window.r();
let browsing_context = window_ref.browsing_context();
let browsing_context = browsing_context.as_ref().unwrap();
browsing_context.frame_element().map(|frame_element| {
let frame_window = window_from_node(frame_element.r());
let event = Event::new(GlobalRef::Window(frame_window.r()), "load".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
let target = EventTargetCast::from_ref(frame_element.r());
event.r().fire(target);
});
// https://developer.mozilla.org/en-US/docs/Web/Events/mozbrowserloadend
document.r().trigger_mozbrowser_event(MozBrowserEvent::LoadEnd);
window_ref.reflow(ReflowGoal::ForDisplay,
ReflowQueryType::NoQuery,
ReflowReason::DocumentLoaded);
}
}
impl Runnable for DocumentProgressHandler {
fn handler(self: Box<DocumentProgressHandler>) {
let document = self.addr.root();
let window = document.r().window();
if window.r().is_alive() {
match self.task {
DocumentProgressTask::DOMContentLoaded => {
self.dispatch_dom_content_loaded();
}
DocumentProgressTask::Load => {
self.set_ready_state_complete();
self.dispatch_load();
}
}
}
}
}<|fim▁end|> | self.quirks_mode.get() |
<|file_name|>overlay.js<|end_file_name|><|fim▁begin|>define(['view',
'class'],
function(View, clazz) {
function Overlay(el, options) {
options = options || {};
Overlay.super_.call(this, el, options);
this.closable = options.closable;
this._autoRemove = options.autoRemove !== undefined ? options.autoRemove : true;
var self = this;
if (this.closable) {
this.el.on('click', function() {
self.hide();
return false;
});
}
}
clazz.inherits(Overlay, View);
Overlay.prototype.show = function() {
this.emit('show');
this.el.appendTo(document.body);
this.el.removeClass('hide');
return this;
}
Overlay.prototype.hide = function() {
this.emit('hide');
this.el.addClass('hide');
if (this._autoRemove) {
var self = this;
setTimeout(function() {
self.remove();<|fim▁hole|> }
return Overlay;
});<|fim▁end|> | self.dispose();
}, 10);
}
return this; |
<|file_name|>issue-3563-3.rs<|end_file_name|><|fim▁begin|>// run-pass
#![allow(unused_imports)]
#![allow(non_snake_case)]
// ASCII art shape renderer. Demonstrates traits, impls, operator overloading,
// non-copyable struct, unit testing. To run execute: rustc --test shapes.rs &&
// ./shapes
// Rust's std library is tightly bound to the language itself so it is
// automatically linked in. However the extra library is designed to be
// optional (for code that must run on constrained environments like embedded
// devices or special environments like kernel code) so it must be explicitly
// linked in.
// Extern mod controls linkage. Use controls the visibility of names to modules
// that are already linked in. Using WriterUtil allows us to use the write_line
// method.
use std::fmt;
use std::iter::repeat;
use std::slice;<|fim▁hole|> x: isize,
y: isize,
}
// Represents an offset on a canvas. (This has the same structure as a Point.
// but different semantics).
#[derive(Copy, Clone)]
struct Size {
width: isize,
height: isize,
}
#[derive(Copy, Clone)]
struct Rect {
top_left: Point,
size: Size,
}
// Contains the information needed to do shape rendering via ASCII art.
struct AsciiArt {
width: usize,
height: usize,
fill: char,
lines: Vec<Vec<char> > ,
// This struct can be quite large so we'll disable copying: developers need
// to either pass these structs around via references or move them.
}
impl Drop for AsciiArt {
fn drop(&mut self) {}
}
// It's common to define a constructor sort of function to create struct instances.
// If there is a canonical constructor it is typically named the same as the type.
// Other constructor sort of functions are typically named from_foo, from_bar, etc.
fn AsciiArt(width: usize, height: usize, fill: char) -> AsciiArt {
// Build a vector of vectors containing blank characters for each position in
// our canvas.
let lines = vec![vec!['.'; width]; height];
// Rust code often returns values by omitting the trailing semi-colon
// instead of using an explicit return statement.
AsciiArt {width: width, height: height, fill: fill, lines: lines}
}
// Methods particular to the AsciiArt struct.
impl AsciiArt {
fn add_pt(&mut self, x: isize, y: isize) {
if x >= 0 && x < self.width as isize {
if y >= 0 && y < self.height as isize {
// Note that numeric types don't implicitly convert to each other.
let v = y as usize;
let h = x as usize;
// Vector subscripting will normally copy the element, but &v[i]
// will return a reference which is what we need because the
// element is:
// 1) potentially large
// 2) needs to be modified
let row = &mut self.lines[v];
row[h] = self.fill;
}
}
}
}
// Allows AsciiArt to be converted to a string using the libcore ToString trait.
// Note that the %s fmt! specifier will not call this automatically.
impl fmt::Display for AsciiArt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Convert each line into a string.
let lines = self.lines.iter()
.map(|line| line.iter().cloned().collect())
.collect::<Vec<String>>();
// Concatenate the lines together using a new-line.
write!(f, "{}", lines.join("\n"))
}
}
// This is similar to an interface in other languages: it defines a protocol which
// developers can implement for arbitrary concrete types.
trait Canvas {
fn add_point(&mut self, shape: Point);
fn add_rect(&mut self, shape: Rect);
// Unlike interfaces traits support default implementations.
// Got an ICE as soon as I added this method.
fn add_points(&mut self, shapes: &[Point]) {
for pt in shapes {self.add_point(*pt)};
}
}
// Here we provide an implementation of the Canvas methods for AsciiArt.
// Other implementations could also be provided (e.g., for PDF or Apple's Quartz)
// and code can use them polymorphically via the Canvas trait.
impl Canvas for AsciiArt {
fn add_point(&mut self, shape: Point) {
self.add_pt(shape.x, shape.y);
}
fn add_rect(&mut self, shape: Rect) {
// Add the top and bottom lines.
for x in shape.top_left.x..shape.top_left.x + shape.size.width {
self.add_pt(x, shape.top_left.y);
self.add_pt(x, shape.top_left.y + shape.size.height - 1);
}
// Add the left and right lines.
for y in shape.top_left.y..shape.top_left.y + shape.size.height {
self.add_pt(shape.top_left.x, y);
self.add_pt(shape.top_left.x + shape.size.width - 1, y);
}
}
}
// Rust's unit testing framework is currently a bit under-developed so we'll use
// this little helper.
pub fn check_strs(actual: &str, expected: &str) -> bool {
if actual != expected {
println!("Found:\n{}\nbut expected\n{}", actual, expected);
return false;
}
return true;
}
fn test_ascii_art_ctor() {
let art = AsciiArt(3, 3, '*');
assert!(check_strs(&art.to_string(), "...\n...\n..."));
}
fn test_add_pt() {
let mut art = AsciiArt(3, 3, '*');
art.add_pt(0, 0);
art.add_pt(0, -10);
art.add_pt(1, 2);
assert!(check_strs(&art.to_string(), "*..\n...\n.*."));
}
fn test_shapes() {
let mut art = AsciiArt(4, 4, '*');
art.add_rect(Rect {top_left: Point {x: 0, y: 0}, size: Size {width: 4, height: 4}});
art.add_point(Point {x: 2, y: 2});
assert!(check_strs(&art.to_string(), "****\n*..*\n*.**\n****"));
}
pub fn main() {
test_ascii_art_ctor();
test_add_pt();
test_shapes();
}<|fim▁end|> |
// Represents a position on a canvas.
#[derive(Copy, Clone)]
struct Point { |
<|file_name|>heroe-list.component.js<|end_file_name|><|fim▁begin|>"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var router_1 = require('@angular/router');
var hero_service_1 = require('../../services/hero.service');
var HeroeList = (function () {
function HeroeList(router, heroService) {
this.router = router;
this.heroService = heroService;
this.title = "Tour of Heroes";
}
HeroeList.prototype.ngOnInit = function () {
this.getHeroes();
};
HeroeList.prototype.getHeroes = function () {
var _this = this;
this.heroService.getHeroes().then(function (heroes) { return _this.heroes = heroes; });
};
HeroeList.prototype.add = function (name) {
var _this = this;
name = name.trim();
if (!name) {
return;
}
this.heroService.create(name)
.then(function (hero) {
_this.heroes.push(hero);
_this.selectedHero = null;
});
};
HeroeList.prototype.delete = function (hero) {
var _this = this;
this.heroService
.delete(hero.id)
.then(function () {
_this.heroes = _this.heroes.filter(function (h) { return h !== hero; });
if (_this.selectedHero === hero) {
_this.selectedHero = null;
}
});
};
HeroeList.prototype.onSelect = function (hero) {
this.selectedHero = hero;
};
HeroeList.prototype.gotoDetail = function () {
this.router.navigate(['/detail', this.selectedHero.id]);
};
HeroeList = __decorate([
core_1.Component({
moduleId: module.id,
selector: 'heroe-list',
providers: [hero_service_1.HeroService],
templateUrl: 'heroe-list.html',
styleUrls: ['heroe-list.css']
}),
__metadata('design:paramtypes', [router_1.Router, hero_service_1.HeroService])
], HeroeList);
return HeroeList;
}());<|fim▁hole|>//# sourceMappingURL=heroe-list.component.js.map<|fim▁end|> | exports.HeroeList = HeroeList; |
<|file_name|>NewInstanceFormController.java<|end_file_name|><|fim▁begin|>/**
*============================================================================
* The Ohio State University Research Foundation, The University of Chicago -
* Argonne National Laboratory, Emory University, SemanticBits LLC,
* and Ekagra Software Technologies Ltd.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-workflow/LICENSE.txt for details.
*============================================================================
**/
package gov.nih.nci.cagrid.portal.portlet.workflow.mvc;
import gov.nih.nci.cagrid.portal.portlet.workflow.WorkflowExecutionService;
import gov.nih.nci.cagrid.portal.portlet.workflow.WorkflowRegistryService;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.SessionEprs;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.SubmitWorkflowCommand;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.WorkflowDescription;
import gov.nih.nci.cagrid.portal.portlet.workflow.domain.WorkflowSubmitted;
import gov.nih.nci.cagrid.portal.portlet.workflow.util.Utils;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.bind.PortletRequestUtils;
import org.springframework.web.portlet.mvc.SimpleFormController;
@Controller
@RequestMapping(params={"action=newInstance"})
@SuppressWarnings("deprecation")
public class NewInstanceFormController extends SimpleFormController {
protected final Log log = LogFactory.getLog(getClass());
@Autowired
private WorkflowExecutionService workflowService;
@Autowired
@Qualifier("MyExperiment")
private WorkflowRegistryService registry;
@Autowired
private SessionEprs eprs;
@Autowired
private Utils utilities;
/* @see org.springframework.web.portlet.mvc.SimpleFormController#processFormSubmission(javax.portlet.ActionRequest, javax.portlet.ActionResponse, java.lang.Object, org.springframework.validation.BindException) */
@Override
protected void processFormSubmission(ActionRequest request, ActionResponse response, Object command, BindException errors) throws Exception {
String id = PortletRequestUtils.getStringParameter(request, "id", "NaN");
log.debug("processFormSubmission. action: " + PortletRequestUtils.getStringParameter(request, "action", "NaN") + " | id - " + id);
SubmitWorkflowCommand cmd = (SubmitWorkflowCommand)command;
log.debug("Command Object: " + cmd.getTheWorkflow());
try {
WorkflowDescription selectedWorkflow = registry.getWorkflow(id);
log.info("Submitting the selected workflow.. #" + id);
String tempFilePath = saveWorkflowDefinition(selectedWorkflow);
EndpointReferenceType epr = workflowService.submitWorkflow(selectedWorkflow.getName(), tempFilePath, cmd.getInputValues());
UUID uuid = UUID.randomUUID();
log.debug("Will submit UUID : " + uuid.toString());
eprs.put(uuid.toString(), new WorkflowSubmitted(epr, selectedWorkflow, "Submitted"));
cmd.setResult("The Workflow was submitted successfully.");
log.info("The Workflow was submitted successfully.");
} catch(Throwable e) {
log.error("Error submitting workflow", e);
Throwable ex = e.getCause();
while(ex.getCause() !=null ) {
ex = ex.getCause();
}
cmd.setResult(e.getClass().getSimpleName() + " submitting workflow: " + e.getMessage());
}
}
/* @see org.springframework.web.portlet.mvc.SimpleFormController#renderFormSubmission(javax.portlet.RenderRequest, javax.portlet.RenderResponse, java.lang.Object, org.springframework.validation.BindException) */
@Override
protected ModelAndView renderFormSubmission(RenderRequest request, RenderResponse response, Object cmd, BindException errors) throws Exception {
log.debug("renderFormSubmission. action: " + PortletRequestUtils.getStringParameter(request, "action", "NaN"));
return new ModelAndView("json", "contents", ((SubmitWorkflowCommand)cmd).getResult());
}
/* @see org.springframework.web.portlet.mvc.SimpleFormController#showForm(javax.portlet.RenderRequest, javax.portlet.RenderResponse, org.springframework.validation.BindException) */
@Override
protected ModelAndView showForm(RenderRequest request, RenderResponse response, BindException errors) throws Exception {
String id = PortletRequestUtils.getStringParameter(request, "id", "NaN");
log.info("showForm. Action: " + PortletRequestUtils.getStringParameter(request, "action", "NaN") + " | id: " + id);
SubmitWorkflowCommand cmd = new SubmitWorkflowCommand();
cmd.setTheWorkflow(registry.getWorkflow(id));
return new ModelAndView("newInstance", "cmd", cmd);
}
/**
* Download the workflow definition to local filesystem
* @param wd Workflow Definition
* @return path of temporary file
* @throws IOException
* @throws HttpException
*/
private String saveWorkflowDefinition(WorkflowDescription wd) throws HttpException, IOException {
File tmpPath = new File( System.getProperty("java.io.tmpdir")+"/taverna" );
tmpPath.mkdirs();
String defPath = tmpPath.getAbsolutePath()+"/myexperiment_"+wd.getId()+"_v"+wd.getVersion()+".t2flow";
if(new File(defPath).exists()) { log.debug("Definition temporary file already exists so not downloading again."); return defPath; }
getUtilities().saveFile(defPath, getUtilities().download(wd.getContentURI()) );
return defPath;
}
<|fim▁hole|> public WorkflowExecutionService getWorkflowService() {return workflowService;}
public void setWorkflowService(WorkflowExecutionService workflowService) {this.workflowService = workflowService;}
public WorkflowRegistryService getRegistry() {return registry;}
public void setRegistry(WorkflowRegistryService registry) {this.registry = registry;}
public Utils getUtilities() {return utilities;}
public void setUtilities(Utils utilities) {this.utilities = utilities;}
}<|fim▁end|> | public SessionEprs getSessionEprs() {return eprs;}
public void setSessionEprs(SessionEprs sessionEprs) {this.eprs = sessionEprs;} |
<|file_name|>fake.go<|end_file_name|><|fim▁begin|>/*
Copyright 2022 The Knative 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,<|fim▁hole|>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 injection-gen. DO NOT EDIT.
package fake
import (
context "context"
factoryfiltered "knative.dev/operator/pkg/client/injection/informers/factory/filtered"
filtered "knative.dev/operator/pkg/client/injection/informers/operator/v1alpha1/knativeserving/filtered"
controller "knative.dev/pkg/controller"
injection "knative.dev/pkg/injection"
logging "knative.dev/pkg/logging"
)
var Get = filtered.Get
func init() {
injection.Fake.RegisterFilteredInformers(withInformer)
}
func withInformer(ctx context.Context) (context.Context, []controller.Informer) {
untyped := ctx.Value(factoryfiltered.LabelKey{})
if untyped == nil {
logging.FromContext(ctx).Panic(
"Unable to fetch labelkey from context.")
}
labelSelectors := untyped.([]string)
infs := []controller.Informer{}
for _, selector := range labelSelectors {
f := factoryfiltered.Get(ctx, selector)
inf := f.Operator().V1alpha1().KnativeServings()
ctx = context.WithValue(ctx, filtered.Key{Selector: selector}, inf)
infs = append(infs, inf.Informer())
}
return ctx, infs
}<|fim▁end|> | |
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>// Type definitions for wu.js 2.1
// Project: https://fitzgen.github.io/wu.js/
// Definitions by: phiresky <https://github.com/phiresky>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function wu<T>(iterable: Iterable<T>): wu.WuIterable<T>;
export = wu;
export as namespace wu;
declare namespace wu {
type Consumer<T> = (t: T) => void;
type Filter<T> = (t: T) => boolean;
// only static
function chain<T>(...iters: Array<Iterable<T>>): WuIterable<T>;
function count(start?: number, step?: number): WuIterable<number>;
function curryable(fun: (...x: any[]) => any, expected?: number): any;
function entries<T>(obj: { [i: string]: T }): WuIterable<[string, T]>;
function keys(obj: { [i: string]: any }): WuIterable<string>;
function values<T>(obj: { [i: string]: T }): WuIterable<T>;
function repeat<T>(obj: T, times?: number): WuIterable<T>;
// also copied to WuIterable
function asyncEach(fn: Consumer<any>, maxBlock?: number, timeout?: number): void;
function drop<T>(n: number, iter: Iterable<T>): WuIterable<T>;
function dropWhile<T>(fn: Filter<T>, iter: Iterable<T>): WuIterable<T>;
function cycle<T>(iter: Iterable<T>): Iterable<T>;
function chunk<T>(n: number, iter: Iterable<T>): WuIterable<T[]>;
function concatMap<T, U>(fn: (t: T) => Iterable<U>, iter: Iterable<T>): WuIterable<U>;
function enumerate<T>(iter: Iterable<T>): Iterable<[number, T]>;
function every<T>(fn: Filter<T>, iter: Iterable<T>): boolean;
function filter<T>(fn: Filter<T>, iter: Iterable<T>): WuIterable<T>;
function find<T>(fn: Filter<T>, iter: Iterable<T>): T | undefined;
function flatten(iter: Iterable<any>): WuIterable<any>;
function flatten(shallow: boolean, iter: Iterable<any>): WuIterable<any>;
function forEach<T>(fn: Consumer<T>, iter: Iterable<T>): void;
function has<T>(t: T, iter: Iterable<T>): boolean;
// invoke<T, U>(name:string, ...t:T[], iter: Iterable<(t:T)=>U>): WuIterable<U>;
const invoke: any;
function map<T, U>(fn: (t: T) => U, iter: Iterable<T>): WuIterable<U>;
// pluck<T>(attribute:string, iter: Iterable<{[attribute]: T}>): WuIterable<T>;
function pluck(attribute: string, iter: Iterable<any>): WuIterable<any>;
function reduce<T>(fn: (a: T, b: T) => T, iter: Iterable<T>): T;
function reduce<T>(fn: (a: T, b: T) => T, initial: T, iter: Iterable<T>): T;
function reduce<T, U>(fn: (a: U, b: T) => U, iter: Iterable<T>): U;
function reduce<T, U>(fn: (a: U, b: T) => U, initial: U, iter: Iterable<T>): U;
function reductions<T>(fn: (a: T, b: T) => T, iter: Iterable<T>): WuIterable<T>;
function reductions<T>(fn: (a: T, b: T) => T, initial: T, iter: Iterable<T>): WuIterable<T>;
function reductions<T, U>(fn: (a: U, b: T) => U, iter: Iterable<T>): WuIterable<U>;
function reductions<T, U>(fn: (a: U, b: T) => U, initial: U, iter: Iterable<T>): WuIterable<U>;
function reject<T>(fn: Filter<T>, iter: Iterable<T>): WuIterable<T>;
function slice<T>(iter: Iterable<T>): WuIterable<T>;
function slice<T>(start: number, iter: Iterable<T>): WuIterable<T>;
function slice<T>(start: number, stop: number, iter: Iterable<T>): WuIterable<T>;
function some<T>(fn: Filter<T>, iter: Iterable<T>): boolean;
function spreadMap<T>(fn: (...x: any[]) => T, iter: Iterable<any[]>): WuIterable<T>;
function take<T>(n: number, iter: Iterable<T>): WuIterable<T>;
function takeWhile<T>(fn: Filter<T>, iter: Iterable<T>): WuIterable<T>;
function tap<T>(fn: Consumer<T>, iter: Iterable<T>): WuIterable<T>;
function unique<T>(iter: Iterable<T>): WuIterable<T>;
function zip<T, U>(iter2: Iterable<T>, iter: Iterable<U>): WuIterable<[T, U]>;
function zipLongest<T, U>(iter2: Iterable<T>, iter: Iterable<U>): WuIterable<[T, U]>;
const zipWith: any;
const unzip: any;
function tee<T>(iter: Iterable<T>): Array<WuIterable<T>>;
function tee<T>(n: number, iter: Iterable<T>): Array<WuIterable<T>>;
interface WuIterable<T> extends IterableIterator<T> {
// generated from section "copied to WuIterable" above via
// sed -r 's/(, )?iter: Iterable<\w+>//' |
// sed -r 's/^(\s+\w+)<T>/\1/' |
// sed -r 's/^(\s+\w+)<T, /\1</'
asyncEach(fn: Consumer<any>, maxBlock?: number, timeout?: number): any;
drop(n: number): WuIterable<T>;
dropWhile(fn: Filter<T>): WuIterable<T>;
cycle(): Iterable<T>;
chunk(n: number): WuIterable<T[]>;
concatMap<U>(fn: (t: T) => Iterable<U>): WuIterable<U>;
enumerate(): Iterable<[number, T]>;
every(fn: Filter<T>): boolean;
filter(fn: Filter<T>): WuIterable<T>;
find(fn: Filter<T>): T | undefined;
flatten(shallow?: boolean): WuIterable<any>;
forEach(fn: Consumer<T>): void;
has(t: T): boolean;
// invoke<T, U>(name:string, ...t:T[], iter: Iterable<(t:T)=>U>): WuIterable<U>;
invoke: any;
map<U>(fn: (t: T) => U): WuIterable<U>;<|fim▁hole|> pluck(attribute: string): WuIterable<any>;
reduce(fn: (a: T, b: T) => T, initial?: T): T;
reduce<U>(fn: (a: U, b: T) => U, initial?: U): U;
reductions(fn: (a: T, b: T) => T, initial?: T): WuIterable<T>;
reductions<U>(fn: (a: U, b: T) => U, initial?: U): WuIterable<U>;
reject(fn: Filter<T>): WuIterable<T>;
slice(start?: number, stop?: number): WuIterable<T>;
some(fn: Filter<T>): boolean;
spreadMap(fn: (...x: any[]) => T, iter: Iterable<any[]>): WuIterable<T>;
take(n: number): WuIterable<T>;
takeWhile(fn: Filter<T>): WuIterable<T>;
tap(fn: Consumer<T>): WuIterable<T>;
unique(): WuIterable<T>;
// TODO: this makes no sense, where did the second entry come from?
// tslint:disable-next-line no-unnecessary-generics
zip<U>(iter2: Iterable<T>): WuIterable<[T, U]>;
// tslint:disable-next-line no-unnecessary-generics
zipLongest<U>(iter2: Iterable<T>): WuIterable<[T, U]>;
zipWith: any;
unzip: any;
tee(n?: number): Array<WuIterable<T>>;
}
}<|fim▁end|> | // pluck<T>(attribute:string, iter: Iterable<{[attribute]: T}>): WuIterable<T>; |
<|file_name|>deploymentconfig.go<|end_file_name|><|fim▁begin|>package create
import (
"fmt"
"io"
"github.com/spf13/cobra"
kapi "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/meta"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/runtime"
"github.com/openshift/origin/pkg/client"
"github.com/openshift/origin/pkg/cmd/util/clientcmd"
deployapi "github.com/openshift/origin/pkg/deploy/api"
)
const (
DeploymentConfigRecommendedName = "deploymentconfig"
deploymentConfigLong = `
Create a deployment config that uses a given image.
Deployment configs define the template for a pod and manages deploying new images or configuration changes.`
deploymentConfigExample = ` # Create an nginx deployment config named my-nginx
%[1]s my-nginx --image=nginx`
)
type CreateDeploymentConfigOptions struct {
DC *deployapi.DeploymentConfig
Client client.DeploymentConfigsNamespacer
Mapper meta.RESTMapper
OutputFormat string
Out io.Writer
Printer ObjectPrinter
}
// NewCmdCreateServiceAccount is a macro command to create a new service account
func NewCmdCreateDeploymentConfig(name, fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
o := &CreateDeploymentConfigOptions{Out: out}
cmd := &cobra.Command{
Use: name + " NAME --image=IMAGE -- [COMMAND] [args...]",
Short: "Create deployment config with default options that uses a given image.",
Long: deploymentConfigLong,
Example: fmt.Sprintf(deploymentConfigExample, fullName),
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(cmd, f, args))
cmdutil.CheckErr(o.Validate())
cmdutil.CheckErr(o.Run())
},
Aliases: []string{"dc"},
}
cmd.Flags().String("image", "", "The image for the container to run.")
cmd.MarkFlagRequired("image")
cmdutil.AddOutputFlagsForMutation(cmd)
return cmd
}
func (o *CreateDeploymentConfigOptions) Complete(cmd *cobra.Command, f *clientcmd.Factory, args []string) error {
argsLenAtDash := cmd.ArgsLenAtDash()
switch {
case (argsLenAtDash == -1 && len(args) != 1),
(argsLenAtDash == 0),
(argsLenAtDash > 1):
return fmt.Errorf("NAME is required: %v", args)
}
labels := map[string]string{"deployment-config.name": args[0]}
o.DC = &deployapi.DeploymentConfig{
ObjectMeta: kapi.ObjectMeta{Name: args[0]},
Spec: deployapi.DeploymentConfigSpec{
Selector: labels,
Replicas: 1,
Template: &kapi.PodTemplateSpec{
ObjectMeta: kapi.ObjectMeta{Labels: labels},
Spec: kapi.PodSpec{
Containers: []kapi.Container{
{
Name: "default-container",
Image: cmdutil.GetFlagString(cmd, "image"),
Args: args[1:],
},
},
},
},
},
}
var err error
o.DC.Namespace, _, err = f.DefaultNamespace()
if err != nil {
return err
}
o.Client, _, err = f.Clients()
if err != nil {
return err
}
o.Mapper, _ = f.Object(false)
o.OutputFormat = cmdutil.GetFlagString(cmd, "output")
o.Printer = func(obj runtime.Object, out io.Writer) error {
return f.PrintObject(cmd, o.Mapper, obj, out)
}
return nil
}
func (o *CreateDeploymentConfigOptions) Validate() error {
if o.DC == nil {
return fmt.Errorf("DC is required")
}
if o.Client == nil {
return fmt.Errorf("Client is required")
}
if o.Mapper == nil {
return fmt.Errorf("Mapper is required")
}<|fim▁hole|> return fmt.Errorf("Out is required")
}
if o.Printer == nil {
return fmt.Errorf("Printer is required")
}
return nil
}
func (o *CreateDeploymentConfigOptions) Run() error {
actualObj, err := o.Client.DeploymentConfigs(o.DC.Namespace).Create(o.DC)
if err != nil {
return err
}
if useShortOutput := o.OutputFormat == "name"; useShortOutput || len(o.OutputFormat) == 0 {
cmdutil.PrintSuccess(o.Mapper, useShortOutput, o.Out, "deploymentconfig", actualObj.Name, "created")
return nil
}
return o.Printer(actualObj, o.Out)
}<|fim▁end|> | if o.Out == nil { |
<|file_name|>defaults.js<|end_file_name|><|fim▁begin|>module.exports = {
'throttle': 10,
'hash': true,
'gzip': false,<|fim▁hole|> 'buildDir': 'build',
'prefix': ''
};<|fim▁end|> | 'baseDir': 'public', |
<|file_name|>gr_Painter.cpp<|end_file_name|><|fim▁begin|>/* AbiWord
* Copyright (C) 2003 Dom Lachowicz <[email protected]>
*
* 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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
<|fim▁hole|>#include "gr_Painter.h"
#include "gr_Graphics.h"
GR_Painter::GR_Painter (GR_Graphics * pGr, bool bDisableCarets)
: m_pGr (pGr),
m_bCaretsDisabled(bDisableCarets),
m_bDoubleBufferingToken(false),
m_bSuspendDrawingToken(false)
{
UT_ASSERT (m_pGr);
if (m_bCaretsDisabled)
m_pGr->disableAllCarets();
m_pGr->beginPaint ();
}
GR_Painter::~GR_Painter ()
{
endDoubleBuffering();
m_pGr->endPaint ();
if (m_bCaretsDisabled)
m_pGr->enableAllCarets();
}
void GR_Painter::drawLine(UT_sint32 x1, UT_sint32 y1, UT_sint32 x2, UT_sint32 y2)
{
m_pGr->drawLine (x1, y1, x2, y2);
}
#if XAP_DONTUSE_XOR
#else
void GR_Painter::xorLine(UT_sint32 x1, UT_sint32 y1, UT_sint32 x2, UT_sint32 y2)
{
m_pGr->xorLine (x1, y1, x2, y2);
}
void GR_Painter::xorRect(UT_sint32 x, UT_sint32 y, UT_sint32 w, UT_sint32 h)
{
m_pGr->xorRect (x, y, w, h);
}
void GR_Painter::xorRect(const UT_Rect& r)
{
m_pGr->xorRect (r);
}
#endif
void GR_Painter::invertRect(const UT_Rect* pRect)
{
m_pGr->invertRect (pRect);
}
void GR_Painter::fillRect(const UT_RGBColor& c,
UT_sint32 x,
UT_sint32 y,
UT_sint32 w,
UT_sint32 h)
{
m_pGr->fillRect (c, x, y, w, h);
}
void GR_Painter::fillRect(GR_Image *pImg, const UT_Rect &src, const UT_Rect & dest)
{
m_pGr->fillRect (pImg, src, dest);
}
void GR_Painter::clearArea(UT_sint32 x, UT_sint32 y, UT_sint32 w, UT_sint32 h)
{
m_pGr->clearArea (x, y, w, h);
}
void GR_Painter::drawImage(GR_Image* pImg, UT_sint32 xDest, UT_sint32 yDest)
{
m_pGr->drawImage (pImg, xDest, yDest);
}
void GR_Painter::fillRect(const UT_RGBColor& c, const UT_Rect &r)
{
m_pGr->fillRect (c, r);
}
void GR_Painter::polygon(UT_RGBColor& c, UT_Point *pts, UT_uint32 nPoints)
{
m_pGr->polygon (c, pts, nPoints);
}
void GR_Painter::polyLine(UT_Point * pts, UT_uint32 nPoints)
{
m_pGr->polyLine(pts, nPoints);
}
void GR_Painter::drawGlyph(UT_uint32 glyph_idx, UT_sint32 xoff, UT_sint32 yoff)
{
m_pGr->drawGlyph (glyph_idx, xoff, yoff);
}
void GR_Painter::drawChars(const UT_UCSChar* pChars,
int iCharOffset,
int iLength,
UT_sint32 xoff,
UT_sint32 yoff,
int* pCharWidths)
{
m_pGr->drawChars (pChars, iCharOffset, iLength, xoff, yoff, pCharWidths);
}
void GR_Painter::drawCharsRelativeToBaseline(const UT_UCSChar* pChars,
int iCharOffset,
int iLength,
UT_sint32 xoff,
UT_sint32 yoff,
int* pCharWidths)
{
m_pGr->drawCharsRelativeToBaseline (pChars, iCharOffset, iLength, xoff, yoff, pCharWidths);
}
void GR_Painter::renderChars(GR_RenderInfo & ri)
{
m_pGr->renderChars(ri);
}
void GR_Painter::fillRect(GR_Graphics::GR_Color3D c, UT_Rect &r)
{
m_pGr->fillRect (c, r.left, r.top, r.width, r.height);
}
void GR_Painter::fillRect(GR_Graphics::GR_Color3D c,
UT_sint32 x,
UT_sint32 y,
UT_sint32 w,
UT_sint32 h)
{
m_pGr->fillRect (c, x, y, w, h);
}
GR_Image * GR_Painter::genImageFromRectangle(const UT_Rect & r)
{
return m_pGr->genImageFromRectangle(r);
}
void GR_Painter::beginDoubleBuffering()
{
m_bDoubleBufferingToken = m_pGr -> beginDoubleBuffering();
}
void GR_Painter::endDoubleBuffering()
{
m_pGr -> endDoubleBuffering(m_bDoubleBufferingToken);
m_bDoubleBufferingToken = false;
}
void GR_Painter::suspendDrawing()
{
m_bSuspendDrawingToken = m_pGr->suspendDrawing();
}
void GR_Painter::resumeDrawing()
{
m_pGr->resumeDrawing(m_bSuspendDrawingToken);
m_bSuspendDrawingToken = false;
}<|fim▁end|> | |
<|file_name|>jstz.js<|end_file_name|><|fim▁begin|>(function (root) {/*global exports, Intl*/
/**
* This script gives you the zone info key representing your device's time zone setting.
*
* @name jsTimezoneDetect
* @version 1.0.6
* @author Jon Nylander
* @license MIT License - https://bitbucket.org/pellepim/jstimezonedetect/src/default/LICENCE.txt
*
* For usage and examples, visit:
* http://pellepim.bitbucket.org/jstz/
*
* Copyright (c) Jon Nylander
*/
/**
* Namespace to hold all the code for timezone detection.
*/
var jstz = (function () {
'use strict';
var HEMISPHERE_SOUTH = 's',
consts = {
DAY: 86400000,
HOUR: 3600000,
MINUTE: 60000,
SECOND: 1000,
BASELINE_YEAR: 2014,
MAX_SCORE: 864000000, // 10 days
AMBIGUITIES: {
'America/Denver': ['America/Mazatlan'],
'Europe/London': ['Africa/Casablanca'],
'America/Chicago': ['America/Mexico_City'],
'America/Asuncion': ['America/Campo_Grande', 'America/Santiago'],
'America/Montevideo': ['America/Sao_Paulo', 'America/Santiago'],
// Europe/Minsk should not be in this list... but Windows.
'Asia/Beirut': ['Asia/Amman', 'Asia/Jerusalem', 'Europe/Helsinki', 'Asia/Damascus', 'Africa/Cairo', 'Asia/Gaza', 'Europe/Minsk'],
'Pacific/Auckland': ['Pacific/Fiji'],
'America/Los_Angeles': ['America/Santa_Isabel'],
'America/New_York': ['America/Havana'],
'America/Halifax': ['America/Goose_Bay'],
'America/Godthab': ['America/Miquelon'],
'Asia/Dubai': ['Asia/Yerevan'],
'Asia/Jakarta': ['Asia/Krasnoyarsk'],
'Asia/Shanghai': ['Asia/Irkutsk', 'Australia/Perth'],
'Australia/Sydney': ['Australia/Lord_Howe'],
'Asia/Tokyo': ['Asia/Yakutsk'],
'Asia/Dhaka': ['Asia/Omsk'],
// In the real world Yerevan is not ambigous for Baku... but Windows.
'Asia/Baku': ['Asia/Yerevan'],
'Australia/Brisbane': ['Asia/Vladivostok'],
'Pacific/Noumea': ['Asia/Vladivostok'],
'Pacific/Majuro': ['Asia/Kamchatka', 'Pacific/Fiji'],
'Pacific/Tongatapu': ['Pacific/Apia'],
'Asia/Baghdad': ['Europe/Minsk', 'Europe/Moscow'],
'Asia/Karachi': ['Asia/Yekaterinburg'],
'Africa/Johannesburg': ['Asia/Gaza', 'Africa/Cairo']
}
},
/**
* Gets the offset in minutes from UTC for a certain date.
* @param {Date} date
* @returns {Number}
*/
get_date_offset = function get_date_offset(date) {
var offset = -date.getTimezoneOffset();
return (offset !== null ? offset : 0);
},
/**
* This function does some basic calculations to create information about
* the user's timezone. It uses REFERENCE_YEAR as a solid year for which
* the script has been tested rather than depend on the year set by the
* client device.
*
* Returns a key that can be used to do lookups in jstz.olson.timezones.
* eg: "720,1,2".
*
* @returns {String}
*/
lookup_key = function lookup_key() {
var january_offset = get_date_offset(new Date(consts.BASELINE_YEAR, 0, 2)),
june_offset = get_date_offset(new Date(consts.BASELINE_YEAR, 5, 2)),
diff = january_offset - june_offset;
if (diff < 0) {
return january_offset + ",1";
} else if (diff > 0) {
return june_offset + ",1," + HEMISPHERE_SOUTH;
}
return january_offset + ",0";
},
/**
* Tries to get the time zone key directly from the operating system for those
* environments that support the ECMAScript Internationalization API.
*/
get_from_internationalization_api = function get_from_internationalization_api() {
var format, timezone;
if (typeof Intl === "undefined" || typeof Intl.DateTimeFormat === "undefined") {
return;
}
format = Intl.DateTimeFormat();
if (typeof format === "undefined" || typeof format.resolvedOptions === "undefined") {
return;
}
timezone = format.resolvedOptions().timeZone;
if (timezone && (timezone.indexOf("/") > -1 || timezone === 'UTC')) {
return timezone;
}
},
/**
* Starting point for getting all the DST rules for a specific year
* for the current timezone (as described by the client system).
*
* Returns an object with start and end attributes, or false if no
* DST rules were found for the year.
*
* @param year
* @returns {Object} || {Boolean}
*/
dst_dates = function dst_dates(year) {
var yearstart = new Date(year, 0, 1, 0, 0, 1, 0).getTime();
var yearend = new Date(year, 12, 31, 23, 59, 59).getTime();
var current = yearstart;
var offset = (new Date(current)).getTimezoneOffset();
var dst_start = null;
var dst_end = null;
while (current < yearend - 86400000) {
var dateToCheck = new Date(current);
var dateToCheckOffset = dateToCheck.getTimezoneOffset();
if (dateToCheckOffset !== offset) {
if (dateToCheckOffset < offset) {
dst_start = dateToCheck;
}
if (dateToCheckOffset > offset) {
dst_end = dateToCheck;
}
offset = dateToCheckOffset;
}
current += 86400000;
}
if (dst_start && dst_end) {
return {
s: find_dst_fold(dst_start).getTime(),
e: find_dst_fold(dst_end).getTime()
};
}
return false;
},
/**
* Probably completely unnecessary function that recursively finds the
* exact (to the second) time when a DST rule was changed.
*
* @param a_date - The candidate Date.
* @param padding - integer specifying the padding to allow around the candidate
* date for finding the fold.
* @param iterator - integer specifying how many milliseconds to iterate while
* searching for the fold.
*
* @returns {Date}
*/
find_dst_fold = function find_dst_fold(a_date, padding, iterator) {
if (typeof padding === 'undefined') {
padding = consts.DAY;
iterator = consts.HOUR;
}
var date_start = new Date(a_date.getTime() - padding).getTime();
var date_end = a_date.getTime() + padding;
var offset = new Date(date_start).getTimezoneOffset();
var current = date_start;
var dst_change = null;
while (current < date_end - iterator) {
var dateToCheck = new Date(current);
var dateToCheckOffset = dateToCheck.getTimezoneOffset();
if (dateToCheckOffset !== offset) {
dst_change = dateToCheck;
break;
}
current += iterator;
}
if (padding === consts.DAY) {
return find_dst_fold(dst_change, consts.HOUR, consts.MINUTE);
}
if (padding === consts.HOUR) {
return find_dst_fold(dst_change, consts.MINUTE, consts.SECOND);
}
return dst_change;
},
windows7_adaptations = function windows7_adaptions(rule_list, preliminary_timezone, score, sample) {
if (score !== 'N/A') {
return score;
}
if (preliminary_timezone === 'Asia/Beirut') {
if (sample.name === 'Africa/Cairo') {
if (rule_list[6].s === 1398376800000 && rule_list[6].e === 1411678800000) {
return 0;
}
}
if (sample.name === 'Asia/Jerusalem') {
if (rule_list[6].s === 1395964800000 && rule_list[6].e === 1411858800000) {
return 0;
}
}
} else if (preliminary_timezone === 'America/Santiago') {
if (sample.name === 'America/Asuncion') {
if (rule_list[6].s === 1412481600000 && rule_list[6].e === 1397358000000) {
return 0;
}
}
if (sample.name === 'America/Campo_Grande') {
if (rule_list[6].s === 1413691200000 && rule_list[6].e === 1392519600000) {
return 0;
}
}
} else if (preliminary_timezone === 'America/Montevideo') {
if (sample.name === 'America/Sao_Paulo') {
if (rule_list[6].s === 1413687600000 && rule_list[6].e === 1392516000000) {
return 0;
}
}
} else if (preliminary_timezone === 'Pacific/Auckland') {
if (sample.name === 'Pacific/Fiji') {
if (rule_list[6].s === 1414245600000 && rule_list[6].e === 1396101600000) {
return 0;
}
}
}
return score;
},
/**
* Takes the DST rules for the current timezone, and proceeds to find matches
* in the jstz.olson.dst_rules.zones array.
*
* Compares samples to the current timezone on a scoring basis.
*
* Candidates are ruled immediately if either the candidate or the current zone
* has a DST rule where the other does not.
*
* Candidates are ruled out immediately if the current zone has a rule that is
* outside the DST scope of the candidate.
*
* Candidates are included for scoring if the current zones rules fall within the
* span of the samples rules.
*
* Low score is best, the score is calculated by summing up the differences in DST
* rules and if the consts.MAX_SCORE is overreached the candidate is ruled out.
*
* Yah follow? :)
*
* @param rule_list
* @param preliminary_timezone
* @returns {*}
*/
best_dst_match = function best_dst_match(rule_list, preliminary_timezone) {
var score_sample = function score_sample(sample) {
var score = 0;
for (var j = 0; j < rule_list.length; j++) {
// Both sample and current time zone report DST during the year.
if (!!sample.rules[j] && !!rule_list[j]) {
// The current time zone's DST rules are inside the sample's. Include.
if (rule_list[j].s >= sample.rules[j].s && rule_list[j].e <= sample.rules[j].e) {
score = 0;
score += Math.abs(rule_list[j].s - sample.rules[j].s);
score += Math.abs(sample.rules[j].e - rule_list[j].e);
// The current time zone's DST rules are outside the sample's. Discard.
} else {
score = 'N/A';
break;
}
// The max score has been reached. Discard.
if (score > consts.MAX_SCORE) {
score = 'N/A';
break;
}
}
}
score = windows7_adaptations(rule_list, preliminary_timezone, score, sample);
return score;
};
var scoreboard = {};
var dst_zones = jstz.olson.dst_rules.zones;
var dst_zones_length = dst_zones.length;
var ambiguities = consts.AMBIGUITIES[preliminary_timezone];
for (var i = 0; i < dst_zones_length; i++) {
var sample = dst_zones[i];
var score = score_sample(dst_zones[i]);
if (score !== 'N/A') {
scoreboard[sample.name] = score;
}
}
for (var tz in scoreboard) {
if (scoreboard.hasOwnProperty(tz)) {
for (var j = 0; j < ambiguities.length; j++) {
if (ambiguities[j] === tz) {
return tz;
}
}
}
}
return preliminary_timezone;
},
/**
* Takes the preliminary_timezone as detected by lookup_key().
*
* Builds up the current timezones DST rules for the years defined
* in the jstz.olson.dst_rules.years array.
*
* If there are no DST occurences for those years, immediately returns
* the preliminary timezone. Otherwise proceeds and tries to solve
* ambiguities.
*
* @param preliminary_timezone<|fim▁hole|> get_by_dst = function get_by_dst(preliminary_timezone) {
var get_rules = function get_rules() {
var rule_list = [];
for (var i = 0; i < jstz.olson.dst_rules.years.length; i++) {
var year_rules = dst_dates(jstz.olson.dst_rules.years[i]);
rule_list.push(year_rules);
}
return rule_list;
};
var check_has_dst = function check_has_dst(rules) {
for (var i = 0; i < rules.length; i++) {
if (rules[i] !== false) {
return true;
}
}
return false;
};
var rules = get_rules();
var has_dst = check_has_dst(rules);
if (has_dst) {
return best_dst_match(rules, preliminary_timezone);
}
return preliminary_timezone;
},
/**
* Uses get_timezone_info() to formulate a key to use in the olson.timezones dictionary.
*
* Returns an object with one function ".name()"
*
* @returns Object
*/
determine = function determine() {
var preliminary_tz = get_from_internationalization_api();
if (!preliminary_tz) {
preliminary_tz = jstz.olson.timezones[lookup_key()];
if (typeof consts.AMBIGUITIES[preliminary_tz] !== 'undefined') {
preliminary_tz = get_by_dst(preliminary_tz);
}
}
return {
name: function () {
return preliminary_tz;
}
};
};
return {
determine: determine
};
}());
jstz.olson = jstz.olson || {};
/**
* The keys in this dictionary are comma separated as such:
*
* First the offset compared to UTC time in minutes.
*
* Then a flag which is 0 if the timezone does not take daylight savings into account and 1 if it
* does.
*
* Thirdly an optional 's' signifies that the timezone is in the southern hemisphere,
* only interesting for timezones with DST.
*
* The mapped arrays is used for constructing the jstz.TimeZone object from within
* jstz.determine();
*/
jstz.olson.timezones = {
'-720,0': 'Etc/GMT+12',
'-660,0': 'Pacific/Pago_Pago',
'-660,1,s': 'Pacific/Apia', // Why? Because windows... cry!
'-600,1': 'America/Adak',
'-600,0': 'Pacific/Honolulu',
'-570,0': 'Pacific/Marquesas',
'-540,0': 'Pacific/Gambier',
'-540,1': 'America/Anchorage',
'-480,1': 'America/Los_Angeles',
'-480,0': 'Pacific/Pitcairn',
'-420,0': 'America/Phoenix',
'-420,1': 'America/Denver',
'-360,0': 'America/Guatemala',
'-360,1': 'America/Chicago',
'-360,1,s': 'Pacific/Easter',
'-300,0': 'America/Bogota',
'-300,1': 'America/New_York',
'-270,0': 'America/Caracas',
'-240,1': 'America/Halifax',
'-240,0': 'America/Santo_Domingo',
'-240,1,s': 'America/Asuncion',
'-210,1': 'America/St_Johns',
'-180,1': 'America/Godthab',
'-180,0': 'America/Argentina/Buenos_Aires',
'-180,1,s': 'America/Montevideo',
'-120,0': 'America/Noronha',
'-120,1': 'America/Noronha',
'-60,1': 'Atlantic/Azores',
'-60,0': 'Atlantic/Cape_Verde',
'0,0': 'UTC',
'0,1': 'Europe/London',
'60,1': 'Europe/Berlin',
'60,0': 'Africa/Lagos',
'60,1,s': 'Africa/Windhoek',
'120,1': 'Asia/Beirut',
'120,0': 'Africa/Johannesburg',
'180,0': 'Asia/Baghdad',
'180,1': 'Europe/Moscow',
'210,1': 'Asia/Tehran',
'240,0': 'Asia/Dubai',
'240,1': 'Asia/Baku',
'270,0': 'Asia/Kabul',
'300,1': 'Asia/Yekaterinburg',
'300,0': 'Asia/Karachi',
'330,0': 'Asia/Kolkata',
'345,0': 'Asia/Kathmandu',
'360,0': 'Asia/Dhaka',
'360,1': 'Asia/Omsk',
'390,0': 'Asia/Rangoon',
'420,1': 'Asia/Krasnoyarsk',
'420,0': 'Asia/Jakarta',
'480,0': 'Asia/Shanghai',
'480,1': 'Asia/Irkutsk',
'525,0': 'Australia/Eucla',
'525,1,s': 'Australia/Eucla',
'540,1': 'Asia/Yakutsk',
'540,0': 'Asia/Tokyo',
'570,0': 'Australia/Darwin',
'570,1,s': 'Australia/Adelaide',
'600,0': 'Australia/Brisbane',
'600,1': 'Asia/Vladivostok',
'600,1,s': 'Australia/Sydney',
'630,1,s': 'Australia/Lord_Howe',
'660,1': 'Asia/Kamchatka',
'660,0': 'Pacific/Noumea',
'690,0': 'Pacific/Norfolk',
'720,1,s': 'Pacific/Auckland',
'720,0': 'Pacific/Majuro',
'765,1,s': 'Pacific/Chatham',
'780,0': 'Pacific/Tongatapu',
'780,1,s': 'Pacific/Apia',
'840,0': 'Pacific/Kiritimati'
};
/* Build time: 2015-11-02 13:01:00Z Build by invoking python utilities/dst.py generate */
jstz.olson.dst_rules = {
"years": [
2008,
2009,
2010,
2011,
2012,
2013,
2014
],
"zones": [
{
"name": "Africa/Cairo",
"rules": [
{
"e": 1219957200000,
"s": 1209074400000
},
{
"e": 1250802000000,
"s": 1240524000000
},
{
"e": 1285880400000,
"s": 1284069600000
},
false,
false,
false,
{
"e": 1411678800000,
"s": 1406844000000
}
]
},
{
"name": "Africa/Casablanca",
"rules": [
{
"e": 1220223600000,
"s": 1212278400000
},
{
"e": 1250809200000,
"s": 1243814400000
},
{
"e": 1281222000000,
"s": 1272758400000
},
{
"e": 1312066800000,
"s": 1301788800000
},
{
"e": 1348970400000,
"s": 1345428000000
},
{
"e": 1382839200000,
"s": 1376100000000
},
{
"e": 1414288800000,
"s": 1406944800000
}
]
},
{
"name": "America/Asuncion",
"rules": [
{
"e": 1205031600000,
"s": 1224388800000
},
{
"e": 1236481200000,
"s": 1255838400000
},
{
"e": 1270954800000,
"s": 1286078400000
},
{
"e": 1302404400000,
"s": 1317528000000
},
{
"e": 1333854000000,
"s": 1349582400000
},
{
"e": 1364094000000,
"s": 1381032000000
},
{
"e": 1395543600000,
"s": 1412481600000
}
]
},
{
"name": "America/Campo_Grande",
"rules": [
{
"e": 1203217200000,
"s": 1224388800000
},
{
"e": 1234666800000,
"s": 1255838400000
},
{
"e": 1266721200000,
"s": 1287288000000
},
{
"e": 1298170800000,
"s": 1318737600000
},
{
"e": 1330225200000,
"s": 1350792000000
},
{
"e": 1361070000000,
"s": 1382241600000
},
{
"e": 1392519600000,
"s": 1413691200000
}
]
},
{
"name": "America/Goose_Bay",
"rules": [
{
"e": 1225594860000,
"s": 1205035260000
},
{
"e": 1257044460000,
"s": 1236484860000
},
{
"e": 1289098860000,
"s": 1268539260000
},
{
"e": 1320555600000,
"s": 1299988860000
},
{
"e": 1352005200000,
"s": 1331445600000
},
{
"e": 1383454800000,
"s": 1362895200000
},
{
"e": 1414904400000,
"s": 1394344800000
}
]
},
{
"name": "America/Havana",
"rules": [
{
"e": 1224997200000,
"s": 1205643600000
},
{
"e": 1256446800000,
"s": 1236488400000
},
{
"e": 1288501200000,
"s": 1268542800000
},
{
"e": 1321160400000,
"s": 1300597200000
},
{
"e": 1352005200000,
"s": 1333256400000
},
{
"e": 1383454800000,
"s": 1362891600000
},
{
"e": 1414904400000,
"s": 1394341200000
}
]
},
{
"name": "America/Mazatlan",
"rules": [
{
"e": 1225008000000,
"s": 1207472400000
},
{
"e": 1256457600000,
"s": 1238922000000
},
{
"e": 1288512000000,
"s": 1270371600000
},
{
"e": 1319961600000,
"s": 1301821200000
},
{
"e": 1351411200000,
"s": 1333270800000
},
{
"e": 1382860800000,
"s": 1365325200000
},
{
"e": 1414310400000,
"s": 1396774800000
}
]
},
{
"name": "America/Mexico_City",
"rules": [
{
"e": 1225004400000,
"s": 1207468800000
},
{
"e": 1256454000000,
"s": 1238918400000
},
{
"e": 1288508400000,
"s": 1270368000000
},
{
"e": 1319958000000,
"s": 1301817600000
},
{
"e": 1351407600000,
"s": 1333267200000
},
{
"e": 1382857200000,
"s": 1365321600000
},
{
"e": 1414306800000,
"s": 1396771200000
}
]
},
{
"name": "America/Miquelon",
"rules": [
{
"e": 1225598400000,
"s": 1205038800000
},
{
"e": 1257048000000,
"s": 1236488400000
},
{
"e": 1289102400000,
"s": 1268542800000
},
{
"e": 1320552000000,
"s": 1299992400000
},
{
"e": 1352001600000,
"s": 1331442000000
},
{
"e": 1383451200000,
"s": 1362891600000
},
{
"e": 1414900800000,
"s": 1394341200000
}
]
},
{
"name": "America/Santa_Isabel",
"rules": [
{
"e": 1225011600000,
"s": 1207476000000
},
{
"e": 1256461200000,
"s": 1238925600000
},
{
"e": 1288515600000,
"s": 1270375200000
},
{
"e": 1319965200000,
"s": 1301824800000
},
{
"e": 1351414800000,
"s": 1333274400000
},
{
"e": 1382864400000,
"s": 1365328800000
},
{
"e": 1414314000000,
"s": 1396778400000
}
]
},
{
"name": "America/Santiago",
"rules": [
{
"e": 1206846000000,
"s": 1223784000000
},
{
"e": 1237086000000,
"s": 1255233600000
},
{
"e": 1270350000000,
"s": 1286683200000
},
{
"e": 1304823600000,
"s": 1313899200000
},
{
"e": 1335668400000,
"s": 1346558400000
},
{
"e": 1367118000000,
"s": 1378612800000
},
{
"e": 1398567600000,
"s": 1410062400000
}
]
},
{
"name": "America/Sao_Paulo",
"rules": [
{
"e": 1203213600000,
"s": 1224385200000
},
{
"e": 1234663200000,
"s": 1255834800000
},
{
"e": 1266717600000,
"s": 1287284400000
},
{
"e": 1298167200000,
"s": 1318734000000
},
{
"e": 1330221600000,
"s": 1350788400000
},
{
"e": 1361066400000,
"s": 1382238000000
},
{
"e": 1392516000000,
"s": 1413687600000
}
]
},
{
"name": "Asia/Amman",
"rules": [
{
"e": 1225404000000,
"s": 1206655200000
},
{
"e": 1256853600000,
"s": 1238104800000
},
{
"e": 1288303200000,
"s": 1269554400000
},
{
"e": 1319752800000,
"s": 1301608800000
},
false,
false,
{
"e": 1414706400000,
"s": 1395957600000
}
]
},
{
"name": "Asia/Damascus",
"rules": [
{
"e": 1225486800000,
"s": 1207260000000
},
{
"e": 1256850000000,
"s": 1238104800000
},
{
"e": 1288299600000,
"s": 1270159200000
},
{
"e": 1319749200000,
"s": 1301608800000
},
{
"e": 1351198800000,
"s": 1333058400000
},
{
"e": 1382648400000,
"s": 1364508000000
},
{
"e": 1414702800000,
"s": 1395957600000
}
]
},
{
"name": "Asia/Dubai",
"rules": [
false,
false,
false,
false,
false,
false,
false
]
},
{
"name": "Asia/Gaza",
"rules": [
{
"e": 1219957200000,
"s": 1206655200000
},
{
"e": 1252015200000,
"s": 1238104800000
},
{
"e": 1281474000000,
"s": 1269640860000
},
{
"e": 1312146000000,
"s": 1301608860000
},
{
"e": 1348178400000,
"s": 1333058400000
},
{
"e": 1380229200000,
"s": 1364508000000
},
{
"e": 1414098000000,
"s": 1395957600000
}
]
},
{
"name": "Asia/Irkutsk",
"rules": [
{
"e": 1224957600000,
"s": 1206813600000
},
{
"e": 1256407200000,
"s": 1238263200000
},
{
"e": 1288461600000,
"s": 1269712800000
},
false,
false,
false,
false
]
},
{
"name": "Asia/Jerusalem",
"rules": [
{
"e": 1223161200000,
"s": 1206662400000
},
{
"e": 1254006000000,
"s": 1238112000000
},
{
"e": 1284246000000,
"s": 1269561600000
},
{
"e": 1317510000000,
"s": 1301616000000
},
{
"e": 1348354800000,
"s": 1333065600000
},
{
"e": 1382828400000,
"s": 1364515200000
},
{
"e": 1414278000000,
"s": 1395964800000
}
]
},
{
"name": "Asia/Kamchatka",
"rules": [
{
"e": 1224943200000,
"s": 1206799200000
},
{
"e": 1256392800000,
"s": 1238248800000
},
{
"e": 1288450800000,
"s": 1269698400000
},
false,
false,
false,
false
]
},
{
"name": "Asia/Krasnoyarsk",
"rules": [
{
"e": 1224961200000,
"s": 1206817200000
},
{
"e": 1256410800000,
"s": 1238266800000
},
{
"e": 1288465200000,
"s": 1269716400000
},
false,
false,
false,
false
]
},
{
"name": "Asia/Omsk",
"rules": [
{
"e": 1224964800000,
"s": 1206820800000
},
{
"e": 1256414400000,
"s": 1238270400000
},
{
"e": 1288468800000,
"s": 1269720000000
},
false,
false,
false,
false
]
},
{
"name": "Asia/Vladivostok",
"rules": [
{
"e": 1224950400000,
"s": 1206806400000
},
{
"e": 1256400000000,
"s": 1238256000000
},
{
"e": 1288454400000,
"s": 1269705600000
},
false,
false,
false,
false
]
},
{
"name": "Asia/Yakutsk",
"rules": [
{
"e": 1224954000000,
"s": 1206810000000
},
{
"e": 1256403600000,
"s": 1238259600000
},
{
"e": 1288458000000,
"s": 1269709200000
},
false,
false,
false,
false
]
},
{
"name": "Asia/Yekaterinburg",
"rules": [
{
"e": 1224968400000,
"s": 1206824400000
},
{
"e": 1256418000000,
"s": 1238274000000
},
{
"e": 1288472400000,
"s": 1269723600000
},
false,
false,
false,
false
]
},
{
"name": "Asia/Yerevan",
"rules": [
{
"e": 1224972000000,
"s": 1206828000000
},
{
"e": 1256421600000,
"s": 1238277600000
},
{
"e": 1288476000000,
"s": 1269727200000
},
{
"e": 1319925600000,
"s": 1301176800000
},
false,
false,
false
]
},
{
"name": "Australia/Lord_Howe",
"rules": [
{
"e": 1207407600000,
"s": 1223134200000
},
{
"e": 1238857200000,
"s": 1254583800000
},
{
"e": 1270306800000,
"s": 1286033400000
},
{
"e": 1301756400000,
"s": 1317483000000
},
{
"e": 1333206000000,
"s": 1349537400000
},
{
"e": 1365260400000,
"s": 1380987000000
},
{
"e": 1396710000000,
"s": 1412436600000
}
]
},
{
"name": "Australia/Perth",
"rules": [
{
"e": 1206813600000,
"s": 1224957600000
},
false,
false,
false,
false,
false,
false
]
},
{
"name": "Europe/Helsinki",
"rules": [
{
"e": 1224982800000,
"s": 1206838800000
},
{
"e": 1256432400000,
"s": 1238288400000
},
{
"e": 1288486800000,
"s": 1269738000000
},
{
"e": 1319936400000,
"s": 1301187600000
},
{
"e": 1351386000000,
"s": 1332637200000
},
{
"e": 1382835600000,
"s": 1364691600000
},
{
"e": 1414285200000,
"s": 1396141200000
}
]
},
{
"name": "Europe/Minsk",
"rules": [
{
"e": 1224979200000,
"s": 1206835200000
},
{
"e": 1256428800000,
"s": 1238284800000
},
{
"e": 1288483200000,
"s": 1269734400000
},
false,
false,
false,
false
]
},
{
"name": "Europe/Moscow",
"rules": [
{
"e": 1224975600000,
"s": 1206831600000
},
{
"e": 1256425200000,
"s": 1238281200000
},
{
"e": 1288479600000,
"s": 1269730800000
},
false,
false,
false,
false
]
},
{
"name": "Pacific/Apia",
"rules": [
false,
false,
false,
{
"e": 1301752800000,
"s": 1316872800000
},
{
"e": 1333202400000,
"s": 1348927200000
},
{
"e": 1365256800000,
"s": 1380376800000
},
{
"e": 1396706400000,
"s": 1411826400000
}
]
},
{
"name": "Pacific/Fiji",
"rules": [
false,
false,
{
"e": 1269698400000,
"s": 1287842400000
},
{
"e": 1327154400000,
"s": 1319292000000
},
{
"e": 1358604000000,
"s": 1350741600000
},
{
"e": 1390050000000,
"s": 1382796000000
},
{
"e": 1421503200000,
"s": 1414850400000
}
]
},
{
"name": "Europe/London",
"rules": [
{
"e": 1224982800000,
"s": 1206838800000
},
{
"e": 1256432400000,
"s": 1238288400000
},
{
"e": 1288486800000,
"s": 1269738000000
},
{
"e": 1319936400000,
"s": 1301187600000
},
{
"e": 1351386000000,
"s": 1332637200000
},
{
"e": 1382835600000,
"s": 1364691600000
},
{
"e": 1414285200000,
"s": 1396141200000
}
]
}
]
};
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = jstz;
} else if ((typeof define !== 'undefined' && define !== null) && (define.amd != null)) {
define([], function() {
return jstz;
});
} else {
if (typeof root === 'undefined') {
window.jstz = jstz;
} else {
root.jstz = jstz;
}
}
}());<|fim▁end|> | * @returns {String} timezone_name
*/ |
<|file_name|>CreateCrawlerRequest.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 com.amazonaws.services.glue.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/CreateCrawler" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateCrawlerRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* Name of the new crawler.
* </p>
*/
private String name;
/**
* <p>
* The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler to access customer resources.
* </p>
*/
private String role;
/**
* <p>
* The Glue database where results are written, such as:
* <code>arn:aws:daylight:us-east-1::database/sometable/*</code>.
* </p>
*/
private String databaseName;
/**
* <p>
* A description of the new crawler.
* </p>
*/
private String description;
/**
* <p>
* A list of collection of targets to crawl.
* </p>
*/
private CrawlerTargets targets;
/**
* <p>
* A <code>cron</code> expression used to specify the schedule (see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html">Time-Based Schedules for
* Jobs and Crawlers</a>. For example, to run something every day at 12:15 UTC, you would specify:
* <code>cron(15 12 * * ? *)</code>.
* </p>
*/
private String schedule;
/**
* <p>
* A list of custom classifiers that the user has registered. By default, all built-in classifiers are included in a
* crawl, but these custom classifiers always override the default classifiers for a given classification.
* </p>
*/
private java.util.List<String> classifiers;
/**
* <p>
* The table prefix used for catalog tables that are created.
* </p>
*/
private String tablePrefix;
/**
* <p>
* The policy for the crawler's update and deletion behavior.
* </p>
*/
private SchemaChangePolicy schemaChangePolicy;
/**
* <p>
* A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were added since
* the last crawler run.
* </p>
*/
private RecrawlPolicy recrawlPolicy;
/**
* <p>
* Specifies data lineage configuration settings for the crawler.
* </p>
*/
private LineageConfiguration lineageConfiguration;
private LakeFormationConfiguration lakeFormationConfiguration;
/**
* <p>
* Crawler configuration information. This versioned JSON string allows users to specify aspects of a crawler's
* behavior. For more information, see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html">Configuring a Crawler</a>.
* </p>
*/
private String configuration;
/**
* <p>
* The name of the <code>SecurityConfiguration</code> structure to be used by this crawler.
* </p>
*/
private String crawlerSecurityConfiguration;
/**
* <p>
* The tags to use with this crawler request. You may use tags to limit access to the crawler. For more information
* about tags in Glue, see <a href="https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">Amazon Web
* Services Tags in Glue</a> in the developer guide.
* </p>
*/
private java.util.Map<String, String> tags;
/**
* <p>
* Name of the new crawler.
* </p>
*
* @param name
* Name of the new crawler.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* Name of the new crawler.
* </p>
*
* @return Name of the new crawler.
*/
public String getName() {
return this.name;
}
/**
* <p>
* Name of the new crawler.
* </p>
*
* @param name
* Name of the new crawler.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler to access customer resources.
* </p>
*
* @param role
* The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler to access customer
* resources.
*/
public void setRole(String role) {
this.role = role;
}
/**
* <p>
* The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler to access customer resources.
* </p>
*
* @return The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler to access customer
* resources.
*/
public String getRole() {
return this.role;
}
/**
* <p>
* The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler to access customer resources.
* </p>
*
* @param role
* The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler to access customer
* resources.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withRole(String role) {
setRole(role);
return this;
}
/**
* <p>
* The Glue database where results are written, such as:
* <code>arn:aws:daylight:us-east-1::database/sometable/*</code>.
* </p>
*
* @param databaseName
* The Glue database where results are written, such as:
* <code>arn:aws:daylight:us-east-1::database/sometable/*</code>.
*/
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
/**
* <p>
* The Glue database where results are written, such as:
* <code>arn:aws:daylight:us-east-1::database/sometable/*</code>.
* </p>
*
* @return The Glue database where results are written, such as:
* <code>arn:aws:daylight:us-east-1::database/sometable/*</code>.
*/
public String getDatabaseName() {
return this.databaseName;
}
/**
* <p>
* The Glue database where results are written, such as:
* <code>arn:aws:daylight:us-east-1::database/sometable/*</code>.
* </p>
*
* @param databaseName
* The Glue database where results are written, such as:
* <code>arn:aws:daylight:us-east-1::database/sometable/*</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withDatabaseName(String databaseName) {
setDatabaseName(databaseName);
return this;
}
/**
* <p>
* A description of the new crawler.
* </p>
*
* @param description
* A description of the new crawler.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* A description of the new crawler.
* </p>
*
* @return A description of the new crawler.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* A description of the new crawler.
* </p>
*
* @param description
* A description of the new crawler.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* A list of collection of targets to crawl.
* </p>
*
* @param targets
* A list of collection of targets to crawl.
*/
public void setTargets(CrawlerTargets targets) {
this.targets = targets;
}
/**
* <p>
* A list of collection of targets to crawl.
* </p>
*
* @return A list of collection of targets to crawl.
*/
public CrawlerTargets getTargets() {
return this.targets;
}
/**
* <p>
* A list of collection of targets to crawl.
* </p>
*
* @param targets
* A list of collection of targets to crawl.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withTargets(CrawlerTargets targets) {
setTargets(targets);
return this;
}
/**
* <p>
* A <code>cron</code> expression used to specify the schedule (see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html">Time-Based Schedules for
* Jobs and Crawlers</a>. For example, to run something every day at 12:15 UTC, you would specify:
* <code>cron(15 12 * * ? *)</code>.
* </p>
*
* @param schedule
* A <code>cron</code> expression used to specify the schedule (see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html">Time-Based
* Schedules for Jobs and Crawlers</a>. For example, to run something every day at 12:15 UTC, you would
* specify: <code>cron(15 12 * * ? *)</code>.
*/
public void setSchedule(String schedule) {
this.schedule = schedule;
}
/**
* <p>
* A <code>cron</code> expression used to specify the schedule (see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html">Time-Based Schedules for
* Jobs and Crawlers</a>. For example, to run something every day at 12:15 UTC, you would specify:
* <code>cron(15 12 * * ? *)</code>.
* </p>
*
* @return A <code>cron</code> expression used to specify the schedule (see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html">Time-Based
* Schedules for Jobs and Crawlers</a>. For example, to run something every day at 12:15 UTC, you would
* specify: <code>cron(15 12 * * ? *)</code>.
*/
public String getSchedule() {
return this.schedule;
}
/**
* <p>
* A <code>cron</code> expression used to specify the schedule (see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html">Time-Based Schedules for
* Jobs and Crawlers</a>. For example, to run something every day at 12:15 UTC, you would specify:
* <code>cron(15 12 * * ? *)</code>.
* </p>
*
* @param schedule
* A <code>cron</code> expression used to specify the schedule (see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html">Time-Based
* Schedules for Jobs and Crawlers</a>. For example, to run something every day at 12:15 UTC, you would
* specify: <code>cron(15 12 * * ? *)</code>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withSchedule(String schedule) {
setSchedule(schedule);
return this;
}
/**
* <p>
* A list of custom classifiers that the user has registered. By default, all built-in classifiers are included in a
* crawl, but these custom classifiers always override the default classifiers for a given classification.
* </p>
*
* @return A list of custom classifiers that the user has registered. By default, all built-in classifiers are
* included in a crawl, but these custom classifiers always override the default classifiers for a given
* classification.
*/
public java.util.List<String> getClassifiers() {
return classifiers;
}
/**
* <p>
* A list of custom classifiers that the user has registered. By default, all built-in classifiers are included in a
* crawl, but these custom classifiers always override the default classifiers for a given classification.
* </p>
*
* @param classifiers
* A list of custom classifiers that the user has registered. By default, all built-in classifiers are
* included in a crawl, but these custom classifiers always override the default classifiers for a given
* classification.
*/
public void setClassifiers(java.util.Collection<String> classifiers) {
if (classifiers == null) {
this.classifiers = null;
return;
}
this.classifiers = new java.util.ArrayList<String>(classifiers);
}
/**
* <p>
* A list of custom classifiers that the user has registered. By default, all built-in classifiers are included in a
* crawl, but these custom classifiers always override the default classifiers for a given classification.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setClassifiers(java.util.Collection)} or {@link #withClassifiers(java.util.Collection)} if you want to
* override the existing values.
* </p>
*
* @param classifiers
* A list of custom classifiers that the user has registered. By default, all built-in classifiers are
* included in a crawl, but these custom classifiers always override the default classifiers for a given
* classification.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withClassifiers(String... classifiers) {
if (this.classifiers == null) {
setClassifiers(new java.util.ArrayList<String>(classifiers.length));
}
for (String ele : classifiers) {
this.classifiers.add(ele);
}
return this;
}
/**
* <p>
* A list of custom classifiers that the user has registered. By default, all built-in classifiers are included in a
* crawl, but these custom classifiers always override the default classifiers for a given classification.
* </p>
*
* @param classifiers
* A list of custom classifiers that the user has registered. By default, all built-in classifiers are
* included in a crawl, but these custom classifiers always override the default classifiers for a given
* classification.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withClassifiers(java.util.Collection<String> classifiers) {
setClassifiers(classifiers);
return this;
}
/**
* <p>
* The table prefix used for catalog tables that are created.
* </p>
*
* @param tablePrefix
* The table prefix used for catalog tables that are created.
*/
public void setTablePrefix(String tablePrefix) {
this.tablePrefix = tablePrefix;
}
/**
* <p>
* The table prefix used for catalog tables that are created.
* </p>
*
* @return The table prefix used for catalog tables that are created.
*/
public String getTablePrefix() {
return this.tablePrefix;
}
/**
* <p>
* The table prefix used for catalog tables that are created.
* </p>
*
* @param tablePrefix
* The table prefix used for catalog tables that are created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withTablePrefix(String tablePrefix) {
setTablePrefix(tablePrefix);
return this;
}
/**
* <p>
* The policy for the crawler's update and deletion behavior.
* </p>
*
* @param schemaChangePolicy
* The policy for the crawler's update and deletion behavior.
*/
public void setSchemaChangePolicy(SchemaChangePolicy schemaChangePolicy) {
this.schemaChangePolicy = schemaChangePolicy;
}
/**
* <p>
* The policy for the crawler's update and deletion behavior.
* </p>
*
* @return The policy for the crawler's update and deletion behavior.
*/
public SchemaChangePolicy getSchemaChangePolicy() {
return this.schemaChangePolicy;
}
/**
* <p>
* The policy for the crawler's update and deletion behavior.
* </p>
*
* @param schemaChangePolicy
* The policy for the crawler's update and deletion behavior.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withSchemaChangePolicy(SchemaChangePolicy schemaChangePolicy) {
setSchemaChangePolicy(schemaChangePolicy);
return this;
}
/**
* <p>
* A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were added since
* the last crawler run.
* </p>
*
* @param recrawlPolicy
* A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were
* added since the last crawler run.
*/
public void setRecrawlPolicy(RecrawlPolicy recrawlPolicy) {
this.recrawlPolicy = recrawlPolicy;
}
/**
* <p>
* A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were added since
* the last crawler run.
* </p>
*
* @return A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were
* added since the last crawler run.
*/
public RecrawlPolicy getRecrawlPolicy() {
return this.recrawlPolicy;
}
/**
* <p>
* A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were added since
* the last crawler run.
* </p>
*
* @param recrawlPolicy
* A policy that specifies whether to crawl the entire dataset again, or to crawl only folders that were
* added since the last crawler run.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withRecrawlPolicy(RecrawlPolicy recrawlPolicy) {
setRecrawlPolicy(recrawlPolicy);
return this;
}
/**
* <p>
* Specifies data lineage configuration settings for the crawler.
* </p>
*
* @param lineageConfiguration
* Specifies data lineage configuration settings for the crawler.
*/
public void setLineageConfiguration(LineageConfiguration lineageConfiguration) {
this.lineageConfiguration = lineageConfiguration;
}
/**
* <p>
* Specifies data lineage configuration settings for the crawler.
* </p>
*
* @return Specifies data lineage configuration settings for the crawler.
*/
public LineageConfiguration getLineageConfiguration() {
return this.lineageConfiguration;
}
/**
* <p>
* Specifies data lineage configuration settings for the crawler.
* </p>
*
* @param lineageConfiguration
* Specifies data lineage configuration settings for the crawler.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withLineageConfiguration(LineageConfiguration lineageConfiguration) {
setLineageConfiguration(lineageConfiguration);
return this;
}
/**
* @param lakeFormationConfiguration
*/
public void setLakeFormationConfiguration(LakeFormationConfiguration lakeFormationConfiguration) {
this.lakeFormationConfiguration = lakeFormationConfiguration;
}
/**
* @return
*/
public LakeFormationConfiguration getLakeFormationConfiguration() {
return this.lakeFormationConfiguration;
}
/**
* @param lakeFormationConfiguration
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withLakeFormationConfiguration(LakeFormationConfiguration lakeFormationConfiguration) {
setLakeFormationConfiguration(lakeFormationConfiguration);
return this;
}
/**
* <p>
* Crawler configuration information. This versioned JSON string allows users to specify aspects of a crawler's
* behavior. For more information, see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html">Configuring a Crawler</a>.
* </p>
*
* @param configuration
* Crawler configuration information. This versioned JSON string allows users to specify aspects of a
* crawler's behavior. For more information, see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html">Configuring a Crawler</a>.
*/
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
/**
* <p>
* Crawler configuration information. This versioned JSON string allows users to specify aspects of a crawler's
* behavior. For more information, see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html">Configuring a Crawler</a>.
* </p>
*
* @return Crawler configuration information. This versioned JSON string allows users to specify aspects of a
* crawler's behavior. For more information, see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html">Configuring a Crawler</a>.
*/
public String getConfiguration() {
return this.configuration;
}
/**
* <p>
* Crawler configuration information. This versioned JSON string allows users to specify aspects of a crawler's
* behavior. For more information, see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html">Configuring a Crawler</a>.
* </p>
*
* @param configuration
* Crawler configuration information. This versioned JSON string allows users to specify aspects of a
* crawler's behavior. For more information, see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/crawler-configuration.html">Configuring a Crawler</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withConfiguration(String configuration) {
setConfiguration(configuration);
return this;
}
/**
* <p>
* The name of the <code>SecurityConfiguration</code> structure to be used by this crawler.
* </p>
*
* @param crawlerSecurityConfiguration
* The name of the <code>SecurityConfiguration</code> structure to be used by this crawler.
*/
public void setCrawlerSecurityConfiguration(String crawlerSecurityConfiguration) {
this.crawlerSecurityConfiguration = crawlerSecurityConfiguration;
}
/**
* <p>
* The name of the <code>SecurityConfiguration</code> structure to be used by this crawler.
* </p>
*
* @return The name of the <code>SecurityConfiguration</code> structure to be used by this crawler.
*/
public String getCrawlerSecurityConfiguration() {
return this.crawlerSecurityConfiguration;
}
/**
* <p>
* The name of the <code>SecurityConfiguration</code> structure to be used by this crawler.
* </p>
*
* @param crawlerSecurityConfiguration
* The name of the <code>SecurityConfiguration</code> structure to be used by this crawler.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withCrawlerSecurityConfiguration(String crawlerSecurityConfiguration) {
setCrawlerSecurityConfiguration(crawlerSecurityConfiguration);
return this;
}
/**
* <p>
* The tags to use with this crawler request. You may use tags to limit access to the crawler. For more information
* about tags in Glue, see <a href="https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">Amazon Web
* Services Tags in Glue</a> in the developer guide.
* </p>
*
* @return The tags to use with this crawler request. You may use tags to limit access to the crawler. For more
* information about tags in Glue, see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">Amazon Web Services Tags in Glue</a>
* in the developer guide.
*/
public java.util.Map<String, String> getTags() {
return tags;
}
/**
* <p>
* The tags to use with this crawler request. You may use tags to limit access to the crawler. For more information
* about tags in Glue, see <a href="https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">Amazon Web
* Services Tags in Glue</a> in the developer guide.
* </p>
*
* @param tags
* The tags to use with this crawler request. You may use tags to limit access to the crawler. For more
* information about tags in Glue, see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">Amazon Web Services Tags in Glue</a>
* in the developer guide.
*/
public void setTags(java.util.Map<String, String> tags) {
this.tags = tags;
}
/**
* <p>
* The tags to use with this crawler request. You may use tags to limit access to the crawler. For more information
* about tags in Glue, see <a href="https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">Amazon Web
* Services Tags in Glue</a> in the developer guide.
* </p>
*
* @param tags
* The tags to use with this crawler request. You may use tags to limit access to the crawler. For more
* information about tags in Glue, see <a
* href="https://docs.aws.amazon.com/glue/latest/dg/monitor-tags.html">Amazon Web Services Tags in Glue</a>
* in the developer guide.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
}
/**
* Add a single Tags entry
*
* @see CreateCrawlerRequest#withTags
* @returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest addTagsEntry(String key, String value) {
if (null == this.tags) {
this.tags = new java.util.HashMap<String, String>();
}
if (this.tags.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.tags.put(key, value);
return this;
}
/**
* Removes all the entries added into Tags.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateCrawlerRequest clearTagsEntries() {
this.tags = null;
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getRole() != null)
sb.append("Role: ").append(getRole()).append(",");
if (getDatabaseName() != null)
sb.append("DatabaseName: ").append(getDatabaseName()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getTargets() != null)
sb.append("Targets: ").append(getTargets()).append(",");
if (getSchedule() != null)
sb.append("Schedule: ").append(getSchedule()).append(",");
if (getClassifiers() != null)
sb.append("Classifiers: ").append(getClassifiers()).append(",");
if (getTablePrefix() != null)
sb.append("TablePrefix: ").append(getTablePrefix()).append(",");
if (getSchemaChangePolicy() != null)
sb.append("SchemaChangePolicy: ").append(getSchemaChangePolicy()).append(",");
if (getRecrawlPolicy() != null)
sb.append("RecrawlPolicy: ").append(getRecrawlPolicy()).append(",");
if (getLineageConfiguration() != null)
sb.append("LineageConfiguration: ").append(getLineageConfiguration()).append(",");
if (getLakeFormationConfiguration() != null)
sb.append("LakeFormationConfiguration: ").append(getLakeFormationConfiguration()).append(",");
if (getConfiguration() != null)
sb.append("Configuration: ").append(getConfiguration()).append(",");
if (getCrawlerSecurityConfiguration() != null)
sb.append("CrawlerSecurityConfiguration: ").append(getCrawlerSecurityConfiguration()).append(",");
if (getTags() != null)
sb.append("Tags: ").append(getTags());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateCrawlerRequest == false)
return false;
CreateCrawlerRequest other = (CreateCrawlerRequest) obj;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getRole() == null ^ this.getRole() == null)
return false;
if (other.getRole() != null && other.getRole().equals(this.getRole()) == false)
return false;
if (other.getDatabaseName() == null ^ this.getDatabaseName() == null)
return false;
if (other.getDatabaseName() != null && other.getDatabaseName().equals(this.getDatabaseName()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getTargets() == null ^ this.getTargets() == null)
return false;
if (other.getTargets() != null && other.getTargets().equals(this.getTargets()) == false)
return false;
if (other.getSchedule() == null ^ this.getSchedule() == null)
return false;
if (other.getSchedule() != null && other.getSchedule().equals(this.getSchedule()) == false)
return false;
if (other.getClassifiers() == null ^ this.getClassifiers() == null)
return false;
if (other.getClassifiers() != null && other.getClassifiers().equals(this.getClassifiers()) == false)
return false;
if (other.getTablePrefix() == null ^ this.getTablePrefix() == null)
return false;
if (other.getTablePrefix() != null && other.getTablePrefix().equals(this.getTablePrefix()) == false)
return false;
if (other.getSchemaChangePolicy() == null ^ this.getSchemaChangePolicy() == null)
return false;
if (other.getSchemaChangePolicy() != null && other.getSchemaChangePolicy().equals(this.getSchemaChangePolicy()) == false)
return false;
if (other.getRecrawlPolicy() == null ^ this.getRecrawlPolicy() == null)
return false;
if (other.getRecrawlPolicy() != null && other.getRecrawlPolicy().equals(this.getRecrawlPolicy()) == false)
return false;
if (other.getLineageConfiguration() == null ^ this.getLineageConfiguration() == null)
return false;
if (other.getLineageConfiguration() != null && other.getLineageConfiguration().equals(this.getLineageConfiguration()) == false)
return false;
if (other.getLakeFormationConfiguration() == null ^ this.getLakeFormationConfiguration() == null)
return false;
if (other.getLakeFormationConfiguration() != null && other.getLakeFormationConfiguration().equals(this.getLakeFormationConfiguration()) == false)
return false;
if (other.getConfiguration() == null ^ this.getConfiguration() == null)
return false;
if (other.getConfiguration() != null && other.getConfiguration().equals(this.getConfiguration()) == false)
return false;
if (other.getCrawlerSecurityConfiguration() == null ^ this.getCrawlerSecurityConfiguration() == null)<|fim▁hole|> if (other.getCrawlerSecurityConfiguration() != null && other.getCrawlerSecurityConfiguration().equals(this.getCrawlerSecurityConfiguration()) == false)
return false;
if (other.getTags() == null ^ this.getTags() == null)
return false;
if (other.getTags() != null && other.getTags().equals(this.getTags()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getRole() == null) ? 0 : getRole().hashCode());
hashCode = prime * hashCode + ((getDatabaseName() == null) ? 0 : getDatabaseName().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getTargets() == null) ? 0 : getTargets().hashCode());
hashCode = prime * hashCode + ((getSchedule() == null) ? 0 : getSchedule().hashCode());
hashCode = prime * hashCode + ((getClassifiers() == null) ? 0 : getClassifiers().hashCode());
hashCode = prime * hashCode + ((getTablePrefix() == null) ? 0 : getTablePrefix().hashCode());
hashCode = prime * hashCode + ((getSchemaChangePolicy() == null) ? 0 : getSchemaChangePolicy().hashCode());
hashCode = prime * hashCode + ((getRecrawlPolicy() == null) ? 0 : getRecrawlPolicy().hashCode());
hashCode = prime * hashCode + ((getLineageConfiguration() == null) ? 0 : getLineageConfiguration().hashCode());
hashCode = prime * hashCode + ((getLakeFormationConfiguration() == null) ? 0 : getLakeFormationConfiguration().hashCode());
hashCode = prime * hashCode + ((getConfiguration() == null) ? 0 : getConfiguration().hashCode());
hashCode = prime * hashCode + ((getCrawlerSecurityConfiguration() == null) ? 0 : getCrawlerSecurityConfiguration().hashCode());
hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode());
return hashCode;
}
@Override
public CreateCrawlerRequest clone() {
return (CreateCrawlerRequest) super.clone();
}
}<|fim▁end|> | return false; |
<|file_name|>test_hessian.py<|end_file_name|><|fim▁begin|>"""
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 3 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.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
The development of this software was sponsored by NAG Ltd. (http://www.nag.co.uk)
and the EPSRC Centre For Doctoral Training in Industrially Focused Mathematical
Modelling (EP/L015803/1) at the University of Oxford. Please contact NAG for
alternative licensing.
"""
# Ensure compatibility with Python 2
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import unittest
from pybobyqa.hessian import Hessian
def array_compare(x, y, thresh=1e-14):
return np.max(np.abs(x - y)) < thresh
class TestBasicInit(unittest.TestCase):
def runTest(self):
n = 4
nvals = n*(n+1)//2
hess = Hessian(n)
self.assertEqual(hess.shape(), (nvals,), 'Wrong shape for initialisation')
self.assertEqual(hess.dim(), n, 'Wrong dimension')
self.assertEqual(len(hess), nvals, 'Wrong length')
self.assertTrue(np.all(hess.upper_triangular() == np.zeros((nvals,))), 'Wrong initialised values')
class TestInitFromVector(unittest.TestCase):
def runTest(self):
n = 5
nvals = n*(n+1)//2
x = np.arange(nvals, dtype=float)
hess = Hessian(n, vals=x)
self.assertEqual(hess.shape(), (nvals,), 'Wrong shape for initialisation')
self.assertEqual(hess.dim(), n, 'Wrong dimension')
self.assertEqual(len(hess), nvals, 'Wrong length')
self.assertTrue(np.all(hess.upper_triangular() == x), 'Wrong initialised values')
class TestInitFromMatrix(unittest.TestCase):
def runTest(self):
n = 3
nvals = n*(n+1)//2
A = np.arange(n**2, dtype=float).reshape((n,n))
hess = Hessian(n, vals=A+A.T) # force symmetric
self.assertEqual(hess.shape(), (nvals,), 'Wrong shape for initialisation')
self.assertEqual(hess.dim(), n, 'Wrong dimension')
self.assertEqual(len(hess), nvals, 'Wrong length')
self.assertTrue(np.all(hess.upper_triangular() == np.array([0.0, 4.0, 8.0, 8.0, 12.0, 16.0])),
'Wrong initialised values')
class TestToFull(unittest.TestCase):
def runTest(self):
n = 7
A = np.arange(n ** 2, dtype=float).reshape((n, n))
H = A + A.T # force symmetric
hess = Hessian(n, vals=H)
self.assertTrue(np.all(hess.as_full() == H), 'Wrong values')
class TestGetElementGood(unittest.TestCase):
def runTest(self):
n = 3
A = np.arange(n ** 2, dtype=float).reshape((n, n))
H = A + A.T # force symmetric
hess = Hessian(n, vals=H)
for i in range(n):
for j in range(n):
self.assertEqual(hess.get_element(i, j), H[i,j], 'Wrong value for (i,j)=(%g,%g): got %g, expecting %g'
% (i, j, hess.get_element(i, j), H[i,j]))
class TestGetElementBad(unittest.TestCase):
def runTest(self):
n = 4
A = np.arange(n ** 2, dtype=float).reshape((n, n))
H = A + A.T # force symmetric
hess = Hessian(n, vals=H)
# When testing for assertion errors, need lambda to stop assertion from actually happening
self.assertRaises(AssertionError, lambda: hess.get_element(-1, 0))
self.assertRaises(AssertionError, lambda: hess.get_element(-1, 0))
self.assertRaises(AssertionError, lambda: hess.get_element(-3, n-1))
self.assertRaises(AssertionError, lambda: hess.get_element(n, 0))
self.assertRaises(AssertionError, lambda: hess.get_element(n+3, 0))
self.assertRaises(AssertionError, lambda: hess.get_element(n+7, n-1))
self.assertRaises(AssertionError, lambda: hess.get_element(0, -1))
self.assertRaises(AssertionError, lambda: hess.get_element(0, -1))
self.assertRaises(AssertionError, lambda: hess.get_element(n-1, -3))
self.assertRaises(AssertionError, lambda: hess.get_element(0, n))
self.assertRaises(AssertionError, lambda: hess.get_element(0, n+3))
self.assertRaises(AssertionError, lambda: hess.get_element(n-1, n+7))
class TestSetElementGood(unittest.TestCase):
def runTest(self):
n = 3
A = np.arange(n ** 2, dtype=float).reshape((n, n))
H = A + A.T # force symmetric
hess = Hessian(n, vals=H)
H2 = np.sin(H)
for i in range(n):
for j in range(n):
hess.set_element(i, j, H2[i,j])
for i in range(n):
for j in range(n):
self.assertEqual(hess.get_element(i, j), H2[i, j], 'Wrong value for (i,j)=(%g,%g): got %g, expecting %g'
% (i, j, hess.get_element(i, j), H2[i, j]))
class TestSetElementBad(unittest.TestCase):
def runTest(self):
n = 5
A = np.arange(n ** 2, dtype=float).reshape((n, n))
H = A + A.T # force symmetric
hess = Hessian(n, vals=H)
# When testing for assertion errors, need lambda to stop assertion from actually happening
self.assertRaises(AssertionError, lambda: hess.set_element(-1, 0, 1.0))
self.assertRaises(AssertionError, lambda: hess.set_element(-1, 0, 2.0))
self.assertRaises(AssertionError, lambda: hess.set_element(-3, n - 1, 3.0))
self.assertRaises(AssertionError, lambda: hess.set_element(n, 0, 4.0))<|fim▁hole|> self.assertRaises(AssertionError, lambda: hess.set_element(0, -1, 7.0))
self.assertRaises(AssertionError, lambda: hess.set_element(n - 1, -3, -7.0))
self.assertRaises(AssertionError, lambda: hess.set_element(0, n, -76.3))
self.assertRaises(AssertionError, lambda: hess.set_element(0, n + 3, 2.8))
self.assertRaises(AssertionError, lambda: hess.set_element(n - 1, n + 7, -1.0))
class TestMultGood(unittest.TestCase):
def runTest(self):
n = 5
A = np.arange(n ** 2, dtype=float).reshape((n, n))
H = np.sin(A + A.T) # force symmetric
hess = Hessian(n, vals=H)
vec = np.exp(np.arange(n, dtype=float))
hs = np.dot(H, vec)
self.assertTrue(array_compare(hess*vec, hs, thresh=1e-12), 'Wrong values')
class TestMultBad(unittest.TestCase):
def runTest(self):
n = 5
A = np.arange(n ** 2, dtype=float).reshape((n, n))
H = A + A.T # force symmetric
hess = Hessian(n, vals=H)
# When testing for assertion errors, need lambda to stop assertion from actually happening
self.assertRaises(AssertionError, lambda: hess * 1.0)
self.assertRaises(AssertionError, lambda: hess * None)
self.assertRaises(AssertionError, lambda: hess * [float(i) for i in range(n)])
self.assertRaises(AssertionError, lambda: hess * np.arange(n-1, dtype=float))
self.assertRaises(AssertionError, lambda: hess * np.arange(n+1, dtype=float))
class TestNeg(unittest.TestCase):
def runTest(self):
n = 5
A = np.arange(n ** 2, dtype=float).reshape((n, n))
H = A + A.T # force symmetric
hess = Hessian(n, vals=H)
neghess = -hess
self.assertTrue(np.allclose(hess.upper_triangular(), -neghess.upper_triangular()), 'Wrong negative values')<|fim▁end|> | self.assertRaises(AssertionError, lambda: hess.set_element(n + 3, 0, -4.0))
self.assertRaises(AssertionError, lambda: hess.set_element(n + 7, n - 1, 5.0))
self.assertRaises(AssertionError, lambda: hess.set_element(0, -1, 6.0)) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>
class SocketIOBackend(BaseTaskRunnerBackend):
def __init__(self):
from . import sockets
def get_detail_template(self):
return 'task_runners/deployment_detail_socketio.html'<|fim▁end|> | from ..base import BaseTaskRunnerBackend
|
<|file_name|>transaction_dialog.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2012 thomasv@gitorious
#
# 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 3 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.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import datetime
import json
import PyQt4
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import PyQt4.QtCore as QtCore
from electrum_xvg import transaction
from electrum_xvg.bitcoin import base_encode
from electrum_xvg.i18n import _
from electrum_xvg.plugins import run_hook
from util import *
dialogs = [] # Otherwise python randomly garbage collects the dialogs...
def show_transaction(tx, parent, desc=None, prompt_if_unsaved=False):
d = TxDialog(tx, parent, desc, prompt_if_unsaved)
dialogs.append(d)
d.show()
class TxDialog(QDialog):
def __init__(self, tx, parent, desc, prompt_if_unsaved):
'''Transactions in the wallet will show their description.
Pass desc to give a description for txs not yet in the wallet.
'''
self.tx = tx
self.tx.deserialize()
self.parent = parent
self.wallet = parent.wallet
self.prompt_if_unsaved = prompt_if_unsaved
self.saved = False
self.broadcast = False
self.desc = desc
QDialog.__init__(self)
self.setMinimumWidth(600)
self.setWindowTitle(_("Transaction"))
vbox = QVBoxLayout()
self.setLayout(vbox)
vbox.addWidget(QLabel(_("Transaction ID:")))
self.tx_hash_e = ButtonsLineEdit()
qr_show = lambda: self.parent.show_qrcode(str(self.tx_hash_e.text()), 'Transaction ID')
self.tx_hash_e.addButton(":icons/qrcode.png", qr_show, _("Show as QR code"))
self.tx_hash_e.setReadOnly(True)
vbox.addWidget(self.tx_hash_e)
self.status_label = QLabel()
vbox.addWidget(self.status_label)
self.tx_desc = QLabel()
vbox.addWidget(self.tx_desc)
self.date_label = QLabel()
vbox.addWidget(self.date_label)
self.amount_label = QLabel()
vbox.addWidget(self.amount_label)
self.fee_label = QLabel()
vbox.addWidget(self.fee_label)
self.add_io(vbox)
vbox.addStretch(1)
self.sign_button = b = QPushButton(_("Sign"))
b.clicked.connect(self.sign)
self.broadcast_button = b = QPushButton(_("Broadcast"))
b.clicked.connect(self.do_broadcast)
self.save_button = b = QPushButton(_("Save"))
b.clicked.connect(self.save)
self.cancel_button = b = QPushButton(_("Close"))
b.clicked.connect(self.close)
b.setDefault(True)
self.qr_button = b = QPushButton()
b.setIcon(QIcon(":icons/qrcode.png"))
b.clicked.connect(self.show_qr)
self.copy_button = CopyButton(lambda: str(self.tx), self.parent.app)
# Action buttons
self.buttons = [self.sign_button, self.broadcast_button, self.cancel_button]
# Transaction sharing buttons
self.sharing_buttons = [self.copy_button, self.qr_button, self.save_button]
run_hook('transaction_dialog', self)
hbox = QHBoxLayout()
hbox.addLayout(Buttons(*self.sharing_buttons))
hbox.addStretch(1)
hbox.addLayout(Buttons(*self.buttons))
vbox.addLayout(hbox)
self.update()
def do_broadcast(self):
self.parent.broadcast_transaction(self.tx, self.desc, parent=self)
self.broadcast = True
self.update()
def closeEvent(self, event):
if (self.prompt_if_unsaved and not self.saved and not self.broadcast
and QMessageBox.question(
self, _('Warning'),
_('This transaction is not saved. Close anyway?'),
QMessageBox.Yes | QMessageBox.No) == QMessageBox.No):
event.ignore()
else:
event.accept()
dialogs.remove(self)
def show_qr(self):
text = self.tx.raw.decode('hex')
text = base_encode(text, base=43)
try:
self.parent.show_qrcode(text, 'Transaction')
except Exception as e:
self.show_message(str(e))
def sign(self):
def sign_done(success):
self.sign_button.setDisabled(False)
self.prompt_if_unsaved = True
self.saved = False
self.update()
self.sign_button.setDisabled(True)
cancelled, ret = self.parent.sign_tx(self.tx, sign_done, parent=self)
if cancelled:
self.sign_button.setDisabled(False)
def save(self):
name = 'signed_%s.txn' % (self.tx.hash()[0:8]) if self.tx.is_complete() else 'unsigned.txn'
fileName = self.parent.getSaveFileName(_("Select where to save your signed transaction"), name, "*.txn")
if fileName:
with open(fileName, "w+") as f:
f.write(json.dumps(self.tx.as_dict(), indent=4) + '\n')
self.show_message(_("Transaction saved successfully"))
self.saved = True
def update(self):
is_relevant, is_mine, v, fee = self.wallet.get_wallet_delta(self.tx)
tx_hash = self.tx.hash()
desc = self.desc
time_str = None
self.broadcast_button.hide()
if self.tx.is_complete():
status = _("Signed")
if tx_hash in self.wallet.transactions.keys():
desc, is_default = self.wallet.get_label(tx_hash)
conf, timestamp = self.wallet.get_confirmations(tx_hash)
if timestamp:
time_str = datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:-3]
else:
time_str = _('Pending')
status = _("%d confirmations")%conf
else:
self.broadcast_button.show()
# cannot broadcast when offline
if self.parent.network is None:
self.broadcast_button.setEnabled(False)
else:
s, r = self.tx.signature_count()
status = _("Unsigned") if s == 0 else _('Partially signed') + ' (%d/%d)'%(s,r)
tx_hash = _('Unknown');
if self.wallet.can_sign(self.tx):
self.sign_button.show()
else:
self.sign_button.hide()
self.tx_hash_e.setText(tx_hash)
if desc is None:
self.tx_desc.hide()
else:
self.tx_desc.setText(_("Description") + ': ' + desc)
self.tx_desc.show()
self.status_label.setText(_('Status:') + ' ' + status)
if time_str is not None:
self.date_label.setText(_("Date: %s")%time_str)
self.date_label.show()
else:
self.date_label.hide()
# if we are not synchronized, we cannot tell
if not self.wallet.up_to_date:
return
if is_relevant:
if is_mine:
if fee is not None:
self.amount_label.setText(_("Amount sent:")+' %s'% self.parent.format_amount(-v+fee) + ' ' + self.parent.base_unit())
self.fee_label.setText(_("Transaction fee")+': %s'% self.parent.format_amount(-fee) + ' ' + self.parent.base_unit())
else:
self.amount_label.setText(_("Amount sent:")+' %s'% self.parent.format_amount(-v) + ' ' + self.parent.base_unit())
self.fee_label.setText(_("Transaction fee")+': '+ _("unknown"))
else:
self.amount_label.setText(_("Amount received:")+' %s'% self.parent.format_amount(v) + ' ' + self.parent.base_unit())
else:
self.amount_label.setText(_("Transaction unrelated to your wallet"))
run_hook('transaction_dialog_update', self)
def add_io(self, vbox):
if self.tx.locktime > 0:
vbox.addWidget(QLabel("LockTime: %d\n" % self.tx.locktime))
vbox.addWidget(QLabel(_("Inputs")))
ext = QTextCharFormat()
rec = QTextCharFormat()
rec.setBackground(QBrush(QColor("lightgreen")))
rec.setToolTip(_("Wallet receive address"))
chg = QTextCharFormat()
chg.setBackground(QBrush(QColor("yellow")))
chg.setToolTip(_("Wallet change address"))<|fim▁hole|> def text_format(addr):
if self.wallet.is_mine(addr):
return chg if self.wallet.is_change(addr) else rec
return ext
i_text = QTextEdit()
i_text.setFont(QFont(MONOSPACE_FONT))
i_text.setReadOnly(True)
i_text.setMaximumHeight(100)
cursor = i_text.textCursor()
for x in self.tx.inputs:
if x.get('is_coinbase'):
cursor.insertText('coinbase')
else:
prevout_hash = x.get('prevout_hash')
prevout_n = x.get('prevout_n')
cursor.insertText(prevout_hash[0:8] + '...', ext)
cursor.insertText(prevout_hash[-8:] + ":%-4d " % prevout_n, ext)
addr = x.get('address')
if addr == "(pubkey)":
_addr = self.wallet.find_pay_to_pubkey_address(prevout_hash, prevout_n)
if _addr:
addr = _addr
if addr is None:
addr = _('unknown')
cursor.insertText(addr, text_format(addr))
cursor.insertBlock()
vbox.addWidget(i_text)
vbox.addWidget(QLabel(_("Outputs")))
o_text = QTextEdit()
o_text.setFont(QFont(MONOSPACE_FONT))
o_text.setReadOnly(True)
o_text.setMaximumHeight(100)
cursor = o_text.textCursor()
for addr, v in self.tx.get_outputs():
cursor.insertText(addr, text_format(addr))
if v is not None:
cursor.insertText('\t', ext)
cursor.insertText(self.parent.format_amount(v, whitespaces = True), ext)
cursor.insertBlock()
vbox.addWidget(o_text)
def show_message(self, msg):
QMessageBox.information(self, _('Message'), msg, _('OK'))<|fim▁end|> | |
<|file_name|>GoogleCloudDialogflowCxV3ListAgentsResponse.java<|end_file_name|><|fim▁begin|>/*
* 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 code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.dialogflow.v3.model;
/**
* The response message for Agents.ListAgents.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleCloudDialogflowCxV3ListAgentsResponse extends com.google.api.client.json.GenericJson {
/**
* The list of agents. There will be a maximum number of items returned based on the page_size
* field in the request.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudDialogflowCxV3Agent> agents;
static {
// hack to force ProGuard to consider GoogleCloudDialogflowCxV3Agent used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GoogleCloudDialogflowCxV3Agent.class);
}
/**
* Token to retrieve the next page of results, or empty if there are no more results in the list.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String nextPageToken;
/**
* The list of agents. There will be a maximum number of items returned based on the page_size
* field in the request.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudDialogflowCxV3Agent> getAgents() {
return agents;
}
/**
* The list of agents. There will be a maximum number of items returned based on the page_size
* field in the request.
* @param agents agents or {@code null} for none
*/
public GoogleCloudDialogflowCxV3ListAgentsResponse setAgents(java.util.List<GoogleCloudDialogflowCxV3Agent> agents) {
this.agents = agents;
return this;
}
/**
* Token to retrieve the next page of results, or empty if there are no more results in the list.
* @return value or {@code null} for none
*/
public java.lang.String getNextPageToken() {
return nextPageToken;
}
/**
* Token to retrieve the next page of results, or empty if there are no more results in the list.
* @param nextPageToken nextPageToken or {@code null} for none
*/
public GoogleCloudDialogflowCxV3ListAgentsResponse setNextPageToken(java.lang.String nextPageToken) {
this.nextPageToken = nextPageToken;
return this;
}
@Override
public GoogleCloudDialogflowCxV3ListAgentsResponse set(String fieldName, Object value) {
return (GoogleCloudDialogflowCxV3ListAgentsResponse) super.set(fieldName, value);
}
@Override
public GoogleCloudDialogflowCxV3ListAgentsResponse clone() {<|fim▁hole|>}<|fim▁end|> | return (GoogleCloudDialogflowCxV3ListAgentsResponse) super.clone();
}
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>use Val;
use std::fmt;
use std::ops::{Deref, DerefMut};
use html::{Html, CSS};
use meta::{Meta, SubMeta, Select};
use stash::{Location, Stash};
use tree::node::Node;
use tree::branch::Branch;
use tree::level::{Beginning, End, Relative};
/// A collection of elements of type T,
/// with metadata of type M.
///
/// This is the base type, that all the collection operations
/// are implemented over.
pub struct Collection<T, M>
where T: Val,
M: Meta<T>
{
/// The location on the stash that constitutes the root for this collection.
pub root: Location<T, M>,
/// The store for values of type Node<T, M>
pub stash: Stash<T, M>,
/// The branching factor, currently hard-coded to 2, which means on average
/// every fourth element will have weight > 0.
pub divisor: usize,
}
/// A view into a Collection, being able to act as a &mut T wrapper.
///
/// When this type dhrops, the collection will be re-balanced as neccesary.
pub struct MutContext<'a, T, M, R>
where T: 'a + Val,
M: 'a + Meta<T>,
R: Relative
{
/// The branch into the Collection, pointing at a value T
branch: Branch<T, M, R>,
/// A mutable reference to the root of the Collection this branch was
root: &'a mut Location<T, M>,
/// The stash of the parent Collection
stash: &'a mut Stash<T, M>,
/// The divisor from parent.
divisor: usize,
/// The weight of the element pointed at, pre-mutation.
weight: usize,
}
impl<'a, T, M, R> Deref for MutContext<'a, T, M, R>
where T: 'a + Val,
M: 'a + Meta<T>,
R: Relative
{
type Target = T;
fn deref(&self) -> &Self::Target {
self.branch.leaf(self.stash).expect("Invalid context")
}
}
impl<'a, T, M, R> DerefMut for MutContext<'a, T, M, R>
where T: 'a + Val,
M: 'a + Meta<T>,
R: Relative
{
fn deref_mut(&mut self) -> &mut Self::Target {
self.branch.leaf_mut(self.stash).expect("Invalid context")
}
}
impl<'a, T, M, R> Drop for MutContext<'a, T, M, R>
where T: 'a + Val,
M: 'a + Meta<T>,
R: Relative
{
fn drop(&mut self) {
let new_weight = self.branch
.leaf(self.stash)
.expect("Invalid context")
.weight();
self.branch.rebalance(self.weight / self.divisor,
new_weight / self.divisor,
self.stash);
*self.root = self.branch.root();
}
}
impl<T, M> Collection<T, M>
where T: Val,
M: Meta<T>
{
/// Returns a new, empty Collection.
pub fn new() -> Self {
let mut stash = Stash::new();
let root = stash.put(Node::new());
Collection {
root: root,
stash: stash,
divisor: 2,
}
}
/// Constructs a Collection given a root and a stash
pub fn new_from(root: Location<T, M>, stash: Stash<T, M>) -> Self {
Collection {
root: root,
stash: stash,
divisor: 2,
}
}
/// Produces a html representation of this Collection. For debug use only.
pub fn _html(&self) -> String
where T: fmt::Debug
{
format!("<style>{}</style>{}",
CSS,
self.root._html(self.stash.top()))
}
/// Clones the collection, mutating self
pub fn clone_mut(&mut self) -> Self {
let new_stash = self.stash.clone_mut(&mut self.root);
Collection {
stash: new_stash,
root: self.root,
divisor: self.divisor,
}
}
/// Returns a new, cloned collection that is the result of a union operation
/// given two Meta implementations `F` and `E`
///
/// `F` is used to select which T goes first in the union.
///
/// `E` is used to find overlapping common subtrees.
///
/// For Sets: `F: Max<T>`, `E: CheckSum<T>`, and for Maps:
/// `F: Key<T::Key>`, `E: KeySum<T>`.
///
/// When the equality testing succeeds, elements will be picked from
/// the Collection `b`.
pub fn union_using<F, E>(&mut self, b: &mut Self) -> Self
where F: Meta<T> + Select<T> + PartialEq + Ord,
E: Meta<T> + PartialEq,
M: SubMeta<F> + SubMeta<E>
{
let a = self.clone_mut();
let mut stash =
self.stash.merge(&mut self.root, &mut b.root, &mut b.stash);
<|fim▁hole|> // Branch into union, being constructed as we go
let mut branch_c: Option<Branch<_, _, End>> = None;
fn a_b<T, M, F, E>(from: &mut Branch<T, M, Beginning>,
into: &mut Option<Branch<T, M, End>>,
divisor: usize,
mut key: F,
stash: &mut Stash<T, M>)
where T: Val,
F: Meta<T> + Select<T> + PartialEq + Ord,
E: Meta<T> + PartialEq,
M: Meta<T> + SubMeta<F> + SubMeta<E>
{
from.find_full(&mut key, stash);
let left = from.left(stash);
*from = from.right(stash);
if into.is_some() {
*into = Some(into.as_ref()
.expect("is some")
.concat(&left.reverse(&stash),
divisor,
stash));
} else {
*into = Some(left)
}
}
loop {
let keys = (branch_a.leaf(&stash).map(|t| F::from_t(t)),
branch_b.leaf(&stash).map(|t| F::from_t(t)));
match keys {
(Some(a), Some(b)) => {
if a == b {
branch_a.skip_equal::<E>(&mut branch_b, &stash);
a_b::<_, _, F, E>(&mut branch_b,
&mut branch_c,
self.divisor,
a,
&mut stash);
branch_a = branch_a.right(&mut stash);
} else if a > b {
a_b::<_, _, F, E>(&mut branch_b,
&mut branch_c,
self.divisor,
a,
&mut stash);
} else {
a_b::<_, _, F, E>(&mut branch_a,
&mut branch_c,
self.divisor,
b,
&mut stash);
}
}
(None, Some(_)) => {
// concat full b
if branch_c.is_some() {
branch_c = Some(branch_c.as_ref()
.expect("is some")
.concat(&branch_b,
self.divisor,
&mut stash));
} else {
branch_c = Some(branch_b.reverse(&stash))
}
break;
}
(Some(_), None) => {
// concat full a
if branch_c.is_some() {
branch_c = Some(branch_c.as_ref()
.expect("is some")
.concat(&branch_a,
self.divisor,
&mut stash));
} else {
branch_c = Some(branch_a.reverse(&stash))
}
break;
}
(None, None) => break,
}
}
match branch_c {
None => Self::new(),
Some(branch) => {
Collection {
root: branch.root(),
stash: stash,
divisor: self.divisor,
}
}
}
}
/// Constructs a MutContext context, given a branch into the Collection.
pub fn mut_context<R: Relative>(&mut self,
branch: Branch<T, M, R>)
-> MutContext<T, M, R> {
MutContext {
weight: branch.leaf(&self.stash).expect("Invalid context").weight(),
branch: branch,
root: &mut self.root,
stash: &mut self.stash,
divisor: self.divisor,
}
}
}
#[macro_export]
macro_rules! collection {
($collection:ident<$t:ident>
{
$( $slot:ident: $submeta:ident<$subtype:ty>, )*
} where $($restraints:tt)*) => (
mod col {
use std::marker::PhantomData;
use std::borrow::Cow;
use Val;
use meta::{Meta, SubMeta};
use super::*;
#[derive(Clone)]
pub struct CollectionMeta<$t> where $t: Val, $($restraints)*
{
_t: PhantomData<$t>,
$(
$slot: $submeta<$subtype>,
)*
}
impl<$t> Meta<$t> for CollectionMeta<$t> where $t: Val, $($restraints)* {
fn from_t(t: &$t) -> Self {
CollectionMeta {
_t: PhantomData,
$(
$slot: $submeta::from_t(t),
)*
}
}
fn merge(&mut self, other: &Self, t: PhantomData<$t>) {
$(
self.$slot.merge(&other.$slot, t);
)*
}
}
macro_rules! as_ref {
($_submeta:ident, $_subtype:ty, $_slot:ident) => (
impl<'a, $t> SubMeta<$_submeta<$_subtype>>
for CollectionMeta<T> where $t: Val, $($restraints)*
{
fn submeta(&self) -> Cow<$_submeta<$_subtype>> {
Cow::Borrowed(&self.$_slot)
}
}
)
}
$(
as_ref!($submeta, $subtype, $slot);
)*
}
pub type $collection<T> = Collection<T, self::col::CollectionMeta<T>>;
)
}<|fim▁end|> | let mut branch_a: Branch<_, _, Beginning> = Branch::first(a.root,
&stash);
let mut branch_b: Branch<_, _, Beginning> = Branch::first(b.root,
&stash); |
<|file_name|>fn_args_layout-blockalways.rs<|end_file_name|><|fim▁begin|>// rustfmt-fn_args_layout: BlockAlways
fn foo() {
foo();
}
fn foo(a: Aaaaaaaaaaaaaa, b: Bbbbbbbbbbbbbb) {
foo();
}
fn bar(a: Aaaaaaaaaaaaaa, b: Bbbbbbbbbbbbbb, c: Cccccccccccccccccc, d: Dddddddddddddddd, e: Eeeeeeeeeeeeeee) {
bar();
}
fn foo(a: Aaaaaaaaaaaaaa, b: Bbbbbbbbbbbbbb) -> String {
foo();
}
fn bar(a: Aaaaaaaaaaaaaa, b: Bbbbbbbbbbbbbb, c: Cccccccccccccccccc, d: Dddddddddddddddd, e: Eeeeeeeeeeeeeee) -> String {<|fim▁hole|>}
trait Test {
fn foo(a: u8) {}
fn bar(a: u8) -> String {}
}<|fim▁end|> | bar(); |
<|file_name|>bitcoin_ar.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="ar" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About TransformersCoin</source>
<translation>عن البلاك كوين</translation>
</message>
<message>
<location line="+39"/>
<source><b>TransformersCoin</b> version</source>
<translation>جزء البلاك كوين</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The TransformersCoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>كتاب العنوان</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>أنقر على الماوس مرتين لتعديل العنوان</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>انشأ عنوان جديد</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>قم بنسخ العنوان المختار لحافظة النظام</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&عنوان جديد</translation>
</message>
<message>
<location line="-46"/>
<source>These are your TransformersCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>هذه هي عناوين البلاك كوين لاستقبال الدفعات. يمكن أن تعطي عنوان مختلف لكل مرسل من اجل أن تتابع من يرسل لك.</translation>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>انسخ العنوان</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>اظهار &رمز الاستجابة السريعة</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a TransformersCoin address</source>
<translation>التوقيع علي رسالة لاثبات بانك تملك عنوان البلاك كوين</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>وقع &الرسالة</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>خذف العنوان الحالي التي تم اختياره من القائمة</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified TransformersCoin address</source>
<translation>تحقق من الرسالة لتثبت بانه تم توقيعه بعنوان بلاك كوين محدد</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&تحقق الرسالة</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&أمسح</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>نسخ &التسمية</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>تعديل</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation>تصدير بيانات كتاب العناوين</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>خطا في التصدير</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>لا يمكن الكتابة الي الملف %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>وصف</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>عنوان</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(لا وصف)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>حوار كلمة المرور</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>ادخل كلمة المرور</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>عبارة مرور جديدة</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>ادخل الجملة السرية مرة أخرى</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>أدخل عبارة مرور جديدة إلى المحفظة. الرجاء استخدام عبارة مرور تتكون من10 حروف عشوائية على الاقل, أو أكثر من 7 كلمات </translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>تشفير المحفظة</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>هذه العملية تحتاج عبارة المرور محفظتك لفتحها</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>إفتح المحفظة</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>هذه العملية تحتاج عبارة المرور محفظتك فك تشفيرها</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>فك تشفير المحفظة</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>تغيير عبارة المرور</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>أدخل عبارة المرور القديمة والجديدة إلى المحفظة.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>تأكيد التشفير المحفظة</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>تخذير : اذا تم تشفير المحفظة وضيعت كلمة المرور, لن تستطيع الحصول علي البلاك كوين</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>هل انت متأكد من رغبتك في تشفير المحفظة؟</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>محفظة مشفرة</translation>
</message>
<message>
<location line="-58"/>
<source>TransformersCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>بلاك كوين</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>فشل تشفير المحفظة</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>شل تشفير المحفظة بسبب خطأ داخلي. لم يتم تشفير محفظتك.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>عبارتي المرور ليستا متطابقتان
</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>فشل فتح المحفظة</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>عبارة المرور التي تم إدخالها لفك شفرة المحفظة غير صحيحة.
</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>فشل فك التشفير المحفظة</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>كلمة مرور المحفظة تم تغييره بشكل ناجح</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+282"/>
<source>Sign &message...</source>
<translation>التوقيع و الرسائل</translation>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation>مزامنة مع شبكة ...</translation>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation>نظرة عامة</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>إظهار نظرة عامة على المحفظة</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>المعاملات</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>تصفح التاريخ المعاملات</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>&كتاب العنوان</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>تعديل قائمة العنوان المحفوظة</translation>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation>&استقبال البلاك كوين</translation>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation>اظهار قائمة العناوين التي تستقبل التعاملات</translation>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation>&ارسال البلاك كوين</translation>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>خروج</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>الخروج من التطبيق</translation>
</message>
<message>
<location line="+6"/>
<source>Show information about TransformersCoin</source>
<translation>اظهار المعلومات عن البلاك كوين</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>عن</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>اظهر المعلومات</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>خيارات ...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>تشفير المحفظة</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>حفظ ودعم المحفظة</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>تغيير كلمة المرور</translation>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation>&تصدير...</translation>
</message>
<message>
<location line="-64"/>
<source>Send coins to a TransformersCoin address</source>
<translation>ارسال البلاك كوين الي عنوان اخر</translation>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for TransformersCoin</source>
<translation>تعديل خيارات التكوين للبلاك كوين</translation>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation>ارسال البيانات الحالية الي ملف</translation>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation>تشفير او فك التشفير للمحفظة</translation>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>احفظ نسخة احتياطية للمحفظة في مكان آخر</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>تغيير عبارة المرور المستخدمة لتشفير المحفظة</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>تأكيد الرسالة</translation>
</message>
<message>
<location line="-202"/>
<source>TransformersCoin</source>
<translation>البلاك كوين</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>محفظة</translation>
</message>
<message>
<location line="+180"/>
<source>&About TransformersCoin</source>
<translation>عن البلاك كوين</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>اظهار/ اخفاء</translation>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation>فتح المحفظة</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>قفل المحفظة</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>قفل المحفظة</translation>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation>ملف</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>الاعدادات</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>مساعدة</translation>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation>شريط أدوات علامات التبويب</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>TransformersCoin client</source>
<translation>برنامج البلاك كوين</translation>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to TransformersCoin network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About TransformersCoin card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about TransformersCoin card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>محين</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>اللحاق بالركب ...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation>تأكيد رسوم المعاملة</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>المعاملات المرسلة</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>المعاملات واردة</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid TransformersCoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>المحفظة مشفرة و مفتوحة حاليا</translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>المحفظة مشفرة و مقفلة حاليا</translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation>النسخ الاحتياطي للمحفظة</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>بيانات المحفظة (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>فشل الدعم</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>خطا في محاولة حفظ بيانات الحفظة في مكان جديد</translation>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. TransformersCoin can no longer continue safely and will quit.</source>
<translation>خطا فادح! بلاك كوين لا يمكن أن يستمر جاري الاغلاق</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation>تحذير الشبكة</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>سيطرة الكوين</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>الكمية:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>المبلغ:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>اهمية:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>رسوم:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation>لا</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>بعد الرسوم:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>تغيير:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>المبلغ</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>عنوان</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>التاريخ</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>تأكيد</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation> انسخ عنوان</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation> انسخ التسمية</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>نسخ الكمية</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>نعم</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(لا وصف)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>عدل العنوان</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>العنوان</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>عنوان تلقي جديد</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>عنوان إرسال جديد</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>تعديل عنوان التلقي
</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>تعديل عنوان الارسال</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>هدا العنوان "%1" موجود مسبقا في دفتر العناوين</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid TransformersCoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation> يمكن فتح المحفظة.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>فشل توليد مفتاح جديد.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>TransformersCoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>خيارات ...</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>الرئيسي</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>ادفع &رسوم المعاملة</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation>حجز</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start TransformersCoin after logging in to the system.</source>
<translation>بد البلاك كوين تلقائي عند الدخول الي الجهاز</translation>
</message>
<message>
<location line="+3"/>
<source>&Start TransformersCoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&الشبكة</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the TransformersCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the TransformersCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>نافذه</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting TransformersCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show TransformersCoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>عرض العناوين في قائمة الصفقة</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>تم</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>الغاء</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>الافتراضي</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting TransformersCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>عنوان الوكيل توفيره غير صالح.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>نمودج</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the TransformersCoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>محفظة</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation>غير ناضجة</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation>الكامل:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation>اخر المعملات </translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>خارج المزامنه</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>اسم العميل</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation>غير معروف</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>نسخه العميل</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>المعلومات</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>الشبكه</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>عدد الاتصالات</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>الفتح</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the TransformersCoin-Qt help message to get a list with possible TransformersCoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>وقت البناء</translation>
</message>
<message>
<location line="-104"/>
<source>TransformersCoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>TransformersCoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the TransformersCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the TransformersCoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>إرسال Coins</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 TRANSF</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>إرسال إلى عدة مستلمين في وقت واحد</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>مسح الكل</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>الرصيد:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 TRANSF</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>تأكيد الإرسال</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a TransformersCoin address (e.g. TRANSF1xGeKnTkaAotEVgs2rnUfVsFv8LVSM)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>نسخ الكمية</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>تأكيد الإرسال Coins</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>المبلغ المدفوع يجب ان يكون اكبر من 0</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid TransformersCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(لا وصف)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>ادفع الى </translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>إدخال تسمية لهذا العنوان لإضافته إلى دفتر العناوين الخاص بك</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. TRANSF1xGeKnTkaAotEVgs2rnUfVsFv8LVSM)</source>
<translation>العنوان لارسال المعاملة الي (مثلا TRANSF1xGeKnTkaAotEVgs2rnUfVsFv8LVSM)</translation>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation>اختيار عنوان من كتاب العناوين</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>انسخ العنوان من لوحة المفاتيح</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>خذف هذا المستخدم</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a TransformersCoin address (e.g. TRANSF1xGeKnTkaAotEVgs2rnUfVsFv8LVSM)</source>
<translation>ادخال عنوان البلاك كوين (مثلا TRANSF1xGeKnTkaAotEVgs2rnUfVsFv8LVSM)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>التواقيع - التوقيع /تأكيد الرسالة</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&وقع الرسالة</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. TRANSF1xGeKnTkaAotEVgs2rnUfVsFv8LVSM)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>اختيار عنوان من كتاب العناوين</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>انسخ العنوان من لوحة المفاتيح</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this TransformersCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>مسح الكل</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. TRANSF1xGeKnTkaAotEVgs2rnUfVsFv8LVSM)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified TransformersCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a TransformersCoin address (e.g. TRANSF1xGeKnTkaAotEVgs2rnUfVsFv8LVSM)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter TransformersCoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>العنوان المدخل غير صالح</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>الرجاء التأكد من العنوان والمحاولة مرة اخرى</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>العنوان المدخل لا يشير الى مفتاح</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>المفتاح الخاص للعنوان المدخل غير موجود.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>فشل توقيع الرسالة.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>الرسالة موقعة.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>فشلت عملية التأكد من الرسالة.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>تم تأكيد الرسالة.</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>مفتوح حتى 1٪</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>1% غير متواجد</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>غير مؤكدة/1%</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>تأكيد %1</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>الحالة.</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>التاريخ</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>المصدر</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>تم اصداره.</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>من</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>الى</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>عنوانه</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>غير مقبولة</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>دين</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>رسوم التحويل</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>تعليق</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>رقم المعاملة</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 110 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>معاملة</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>المبلغ</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>صحيح</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>خاطئ</translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>لم يتم حتى الآن البث بنجاح</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>غير معروف</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>تفاصيل المعاملة</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>يبين هذا الجزء وصفا مفصلا لهده المعاملة</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>التاريخ</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>النوع</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>عنوان</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>المبلغ</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation>مفتوح حتى 1٪</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>تأكيد الإرسال Coins</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation>غير متصل</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>لم يتم تلقى هذه الكتلة (Block) من قبل أي العقد الأخرى وربما لن تكون مقبولة!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>ولدت ولكن لم تقبل</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>استقبل مع</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>استقبل من</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>أرسل إلى</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>دفع لنفسك</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>غير متوفر</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>حالة المعاملة. تحوم حول هذا الحقل لعرض عدد التأكيدات.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>التاريخ والوقت الذي تم فيه تلقي المعاملة.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>نوع المعاملات</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>عنوان وجهة المعاملة</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>المبلغ الذي أزيل أو أضيف الى الرصيد</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>الكل</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>اليوم</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>هدا الاسبوع</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>هدا الشهر</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>الشهر الماضي</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>هدا العام</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>نطاق</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>استقبل مع</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>أرسل إلى</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>إليك</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>اخرى</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>ادخل عنوان أووصف للبحث</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>الكمية الادني</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation> انسخ عنوان</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation> انسخ التسمية</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>نسخ الكمية</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>نسخ رقم المعاملة</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>عدل الوصف</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>اظهار تفاصيل المعاملة</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation>تصدير بيانات المعاملة</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>تأكيد</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>التاريخ</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>النوع</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>وصف</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>عنوان</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>المبلغ</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>العنوان</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>خطا في التصدير</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>لا يمكن الكتابة الي الملف %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>نطاق:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>الى</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation>ارسال....</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>TransformersCoin version</source>
<translation>جزع البلاك كوين</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>المستخدم</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or TransformersCoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>اعرض الأوامر</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>مساعدة في كتابة الاوامر</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>خيارات: </translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: TransformersCoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: TransformersCoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>حدد موقع مجلد المعلومات او data directory</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>ضع حجم كاش قاعدة البيانات بالميجابايت (الافتراضي: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>حدد عنوانك العام هنا</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation>تحذير صناعة المعاملة فشلت</translation>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation>خطا : المحفظة مقفلة, لا يمكن عمل المعاملة</translation>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation>استيراد بيانات ملف سلسلة الكتل</translation>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>استخدم التحقق من الشبكه</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>قبول الاتصالات من خارج</translation>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong TransformersCoin will not work properly.</source>
<translation>تحذير : تأكد من ساعة وتاريخ الكمبيوتر! اذا ساعة غير صحيحة بلاك كوين لن يعمل بشكل صحيح</translation>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>تحذير : خطا في قراءة wallet.dat! كل المفاتيح تم قرائتة بشكل صحيح لكن بيانات الصفقة او إدخالات كتاب العنوان غير صحيحة او غير موجودة</translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>تخذير :wallet.dat غير صالح تم حفظ البيانات. المحفظة الاصلية تم حفظه ك wallet.{timestamp}.bak %s في ; اذا حسابك او صفقاتك غير صحيح يجب عليك استعادة النسخ الاحتياطي</translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>محاولة استرجاع المفاتيح الخاصة من wallet.dat الغير صالح</translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>خيارات صناعة الكتل</translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>فشل في الاستماع على أي منفذ. استخدام الاستماع = 0 إذا كنت تريد هذا.</translation>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation>تحذير : مساحة القرص منخفض</translation>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>تحذير هذا الجزء قديم, التجديد مطلوب</translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat غير صالح لا يمكن الاسترجاع</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=TransformersCoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "TransformersCoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation>عند</translation>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>ارقاء المحفظة الي اخر نسخة</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>اعادة بحث سلسلة الكتلة لايجاد معالمات المحفظة</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation>كمية الكتل التي تريد ان تبحث عنه عند بداية البرنامج (التلقائي 2500, 0 = الكل)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>كمية تأكيد الكتل (0-6 التلقائي 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>نقل كتل من ملف blk000.dat خارجي</translation>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>رسالة المساعدة هذه</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. TransformersCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>TransformersCoin</source>
<translation>البلاك كوين</translation>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>تحميل العنوان</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation>خظا في تحميل blkindex.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>خطأ عند تنزيل wallet.dat: المحفظة تالفة</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of TransformersCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart TransformersCoin to complete</source>
<translation>المحفظة يجب أن يعاد كتابته : أعد البلاك كوين لتكتمل</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>خطأ عند تنزيل wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message><|fim▁hole|> <translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation>ارسال....</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>مبلغ خاطئ</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>حسابك لا يكفي</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. TransformersCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>تحميل المحفظه</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation> لا يمكن خفض المحفظة</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation> لا يمكن كتابة العنوان الافتراضي</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>إعادة مسح</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>انتهاء التحميل</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>خطأ</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS><|fim▁end|> | <message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source> |
<|file_name|>number.test.js<|end_file_name|><|fim▁begin|>const test = require('tape')
const nlp = require('../_lib')
test('number-tag:', function (t) {
let arr = [
['16.125', 'Cardinal'],
['+160.125', 'Cardinal'],
['-0.1', 'Cardinal'],
['.13', 'Cardinal'],
['(127.54)', 'Cardinal'],
['16.125th', 'Ordinal'],<|fim▁hole|> ['+160.125th', 'Ordinal'],
['-0.2nd', 'Ordinal'],
['(127.54th)', 'Ordinal'],
// ['(127.54)', 'Money'],
['-0.1%', 'Percent'],
['.1%', 'Percent'],
['+2,340.91%', 'Percent'],
['-2340%', 'Percent'],
['$-2340.01', 'Money'],
['-$2340', 'Money'],
['+$2340.01', 'Money'],
['$2340.01', 'Money'],
['£1,000,000', 'Money'],
['$19', 'Money'],
['($127.54)', 'Money'],
['2,000₽', 'Money'],
['2000₱', 'Money'],
['2000௹', 'Money'],
['₼2000', 'Money'],
['2.23₽', 'Money'],
['₺50', 'Money'],
['$47.5m', 'Money'],
['$47.5bn', 'Money'],
// ['1,000,000p', 'Cardinal'],
]
arr.forEach(function (a) {
let doc = nlp(a[0])
t.equal(doc.has('#' + a[1]), true, a[0] + ' is #' + a[1])
})
t.end()
})<|fim▁end|> | ['161,253th', 'Ordinal'], |
<|file_name|>gcreatedialog.cpp<|end_file_name|><|fim▁begin|>#include "src/gcreatedialog.h"
#include "ui_gcreatedialog.h"
GCreateDialog::GCreateDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::GCreateDialog)<|fim▁hole|>
ui->lineEdit_GName->setStyleSheet("QLineEdit#lineEdit_GName { border-radius: 2px; }");
}
GCreateDialog::~GCreateDialog()
{
delete ui;
}<|fim▁end|> | {
ui->setupUi(this); |
<|file_name|>SyncInfo.ts<|end_file_name|><|fim▁begin|>/* Generated code */
interface SyncInfo {
syncType?: 'FSync' | 'ISync';
syncToken?: string;
syncTime?: string;
<|fim▁hole|>
export default SyncInfo;<|fim▁end|> | olderRecordsExist?: boolean;
} |
<|file_name|>nightwatch.py<|end_file_name|><|fim▁begin|>import boto3
import logging
import argparse
import os
from botocore.exceptions import ClientError
from boto3.dynamodb.conditions import Key, Attr
import json
import decimal
import time
import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import contracts
from rest import IGParams, IGClient
import asyncio
import uuid
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
if o % 1 > 0:
return float(o)
else:
return int(o)
return super(DecimalEncoder, self).default(o)
class Utils(object):
def __init__(self):
pass
@staticmethod
def reliable(func):
def _decorator(self, *args, **kwargs):
tries = 0
result = func(self, *args, **kwargs)
if result is None:
while result is None and tries < 10:
tries += 1
time.sleep(2 ** tries)
result = func(self, *args, **kwargs)
return result
return _decorator
class CapsuleParams(object):
def __init__(self):
self.Region = ''
self.Instance = ''
self.Email = ''
self.Iam = ''
self.User = ''
self.Password = ''
self.Smtp = ''
class CapsuleController(object):
def __init__(self, params):
self.secDef = contracts.SecurityDefinition()
self.Email = params.Email
self.Iam = params.Iam
self.User = params.User
self.Password = params.Password
self.Smtp = params.Smtp
self.Logger = logging.getLogger()
self.Logger.setLevel(logging.INFO)
ec2 = boto3.resource('ec2', region_name=params.Region)
self.__Instance = ec2.Instance(params.Instance)
db = boto3.resource('dynamodb', region_name=params.Region)
self.__QuotesEod = db.Table('Quotes.EOD')
self.__Securities = db.Table('Securities')
self.__Orders = db.Table('Orders')
s3 = boto3.resource('s3')
debug = os.environ['DEBUG_FOLDER']
self.__debug = s3.Object(debug, 'vix_roll.txt')
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(threadName)s - %(message)s')
self.Logger.info('InstanceController Created. Region: %s Instance: %s' % (params.Region, params.Instance))
def AttemptsCount(self):
timestamp = int((datetime.datetime.now() - datetime.timedelta(hours=2)).timestamp()) * 1000
logs = boto3.client('logs')
log_group = '/aws/docker/Capsule'
data = logs.describe_log_streams(logGroupName=log_group, orderBy='LastEventTime', descending=True)
streams = filter(lambda x: x['creationTime'] > timestamp, data['logStreams'])
count = 0
for stream in streams:
lines = logs.get_log_events(logGroupName=log_group,
logStreamName=stream['logStreamName'])
for line in lines['events']:
if 'LogStream Created:' in line['message']:
count += 1
self.Logger.info('Capsule ran %s times in the last 2 hours' % count)
return count
def SendEmail(self, text):
msg = MIMEMultipart('alternative')
msg['Subject'] = 'NIGHTWATCH ALERT'
msg['From'] = self.Email
msg['To'] = self.Email
mime_text = MIMEText(text, 'html')
msg.attach(mime_text)
server = smtplib.SMTP(self.Smtp, 587, timeout=10)
server.set_debuglevel(10)
server.starttls()
server.ehlo()
server.login(self.User, self.Password)
server.sendmail(self.Email, self.Email, msg.as_string())
res = server.quit()
self.Logger.info(res)
def ValidateStrategy(self):
today = datetime.date.today().strftime("%Y%m%d")
fileObj = self.__debug.get()['Body']
ch = fileObj.read(1)
line = ''
while ch:
if ch.decode("utf-8") == '\n':
if today in line:
return True
line = ''
else:
line += ch.decode("utf-8")
ch = fileObj.read(1)
return False
@Utils.reliable
def SuspendTrading(self, symbol, broker):
try:
response = self.__Securities.update_item(
Key={
'Symbol': symbol,
'Broker': broker,
},
UpdateExpression="set #te = :te",
ExpressionAttributeNames={
'#te': 'TradingEnabled'
},
ExpressionAttributeValues={
':te': False
},
ReturnValues="UPDATED_NEW")
except ClientError as e:
self.Logger.error(e.response['Error']['Message'])
except Exception as e:
self.Logger.error(e)
else:
self.Logger.info('Security Updated')
self.Logger.info(json.dumps(response, indent=4, cls=DecimalEncoder))
return response
@Utils.reliable
def SendOrder(self, symbol, maturity, side, size, price, orderType, fillTime, dealId, broker, productType):
try:
order = {
"Side": side,
"Size": decimal.Decimal(str(size)),
"OrdType": orderType}
trade = {
"FillTime": fillTime,
"Side": side,
"FilledSize": decimal.Decimal(str(size)),
"Price": decimal.Decimal(str(price)),
"Broker": {"Name": broker, "RefType": "dealId", "Ref": dealId},
}
strategy = {
"Name": "SYSTEM",
"Reason": "STOP_TRIGGERED"
}
response = self.__Orders.update_item(
Key={
'OrderId': str(uuid.uuid4().hex),
'TransactionTime': str(time.time()),
},
UpdateExpression="set #st = :st, #s = :s, #m = :m, #p = :p, #b = :b, #o = :o, #t = :t, #str = :str",
ExpressionAttributeNames={
'#st': 'Status',
'#s': 'Symbol',
'#m': 'Maturity',
'#p': 'ProductType',
'#b': 'Broker',
'#o': 'Order',
'#t': 'Trade',
'#str': 'Strategy'
},
ExpressionAttributeValues={
':st': 'FILLED',
':s': symbol,
':m': maturity,
':p': productType,
':b': broker,
':o': order,
':t': trade,
':str': strategy
},
ReturnValues="UPDATED_NEW")
except ClientError as e:
self.Logger.error(e.response['Error']['Message'])
except Exception as e:
self.Logger.error(e)
else:
self.Logger.info('Order Created')
self.Logger.info(json.dumps(response, indent=4, cls=DecimalEncoder))
return response
def FindSystemStopOrders(self):
"""
Update Orders table if the stop order was executed by the broker
:return:
None
"""
params = IGParams()
params.Url = os.environ['IG_URL']
params.Key = os.environ['X_IG_API_KEY']
params.Identifier = os.environ['IDENTIFIER']
params.Password = os.environ['PASSWORD']
self.Logger.info('Checking if any stop order was triggered')
async def read():
async with IGClient(params, self.Logger) as client:
auth = await client.Login()
self.Logger.info('Auth: %s' % auth)
lastMonth = datetime.date.today() - datetime.timedelta(days=30)
activities = await client.GetActivities(lastMonth.strftime('%Y-%m-%d'), True)
self.Logger.info('activities: %s' % activities)
await client.Logout()
if activities is not None and 'activities' in activities and len(activities['activities']) > 0:
stopTriggered = [tran for tran in activities['activities']
if tran['channel'] == 'SYSTEM' and 'details' in tran]
if len(stopTriggered) == 0:
self.Logger.info('No stops were triggered')
return
filled = self.GetOrders('Status', 'FILLED')
self.Logger.info('All filled %s' % filled)
for tran in stopTriggered:
for action in tran['details']['actions']:
if action['actionType'] == 'POSITION_CLOSED':
self.Logger.info('affectedDealId: %s' % action['affectedDealId'])
already_done = [o for o in filled if 'Broker'in o['Trade'] and 'Ref'
in o['Trade']['Broker'] and o['Trade']['Broker']['Ref'] == tran['dealId']
and o['Strategy']['Name'] == 'SYSTEM']
if len(already_done) == 1:
self.Logger.info('Already filled this unaccounted stop %s' % tran['dealId'])
continue
found = [o for o in filled if 'Broker'in o['Trade'] and 'Ref' in o['Trade']['Broker']
and o['Trade']['Broker']['Ref'] == action['affectedDealId']]
if len(found) == 1:
f = found[0]
self.Logger.info('Unaccounted stop found %s' % found)
self.SuspendTrading(f['Symbol'], 'IG')
self.SendOrder(f['Symbol'], f['Maturity'], tran['details']['direction'],
tran['details']['size'], tran['details']['level'],
'STOP', tran['date'], tran['dealId'], 'IG', f['ProductType'])
self.SendEmail('STOP Order was triggered by IG. Trading in %s is suspended'
% f['Symbol'])
app_loop = asyncio.get_event_loop()
app_loop.run_until_complete(read())
def ValidateExecutor(self):
pending = self.GetOrders('Status', 'PENDING')
if pending is not None and len(pending) > 0:
self.SendEmail('There are %s PENDING Orders in Chaos' % len(pending))
failed = self.GetOrders('Status', 'FAILED')
if failed is not None and len(failed) > 0:
self.SendEmail('There are %s FAILED Orders in Chaos' % len(failed))
def EndOfDay(self):
allFound = True
for security in filter(lambda x: x['SubscriptionEnabled'], self.GetSecurities()):
today = datetime.date.today().strftime("%Y%m%d")
symbols = []
if security['ProductType'] == 'IND':
symbols = [security['Symbol']]
if security['ProductType'] == 'FUT':
symbols = self.secDef.get_futures(security['Symbol'], 2) # get two front months
for symbol in symbols:
found = self.GetQuotes(symbol, today)
if len(found) > 0:
self.Logger.info('Found Symbols: %s' % found)
else:
self.Logger.error('Failed to find data for %s' % symbol)
allFound &= len(found) > 0
if allFound:
self.Logger.info('All Found. Stopping EC2 Instance')
if self.IsInstanceRunning():
self.StopInstance()
if not self.ValidateStrategy():
self.SendEmail('The VIX Roll strategy left no TRACE file today')
else:
self.Logger.info('Not All Found. Will try again. Restarting EC2 Instance')
if self.IsInstanceRunning():
self.StopInstance()
if self.AttemptsCount() >= 3:
self.SendEmail('Capsule could not retrieve market data after %s attempts' % str(3))
return
self.StartInstance()
def IsInstanceRunning(self):
self.Logger.info('Instance Id: %s, State: %s' % (self.__Instance.instance_id, self.__Instance.state))
return self.__Instance.state['Name'] == 'running'
def StartInstance(self):
self.__Instance.start()
self.__Instance.wait_until_running()
self.Logger.info('Started instance: %s' % self.__Instance.instance_id)
def StopInstance(self):
self.__Instance.stop()
self.__Instance.wait_until_stopped()
self.Logger.info('Stopped instance: %s' % self.__Instance.instance_id)
@Utils.reliable
def GetOrders(self, key, value):
try:
self.Logger.info('Calling orders scan attr: %s, %s' % (key, value))
response = self.__Orders.scan(FilterExpression=Attr(key).eq(value))
except ClientError as e:
self.Logger.error(e.response['Error']['Message'])
return None
except Exception as e:
self.Logger.error(e)
return None
else:
if 'Items' in response:
return response['Items']
@Utils.reliable
def GetSecurities(self):
try:
self.Logger.info('Calling securities scan ...')
response = self.__Securities.scan(FilterExpression=Attr('SubscriptionEnabled').eq(True))
except ClientError as e:
self.Logger.error(e.response['Error']['Message'])
return None<|fim▁hole|> except Exception as e:
self.Logger.error(e)
return None
else:
if 'Items' in response:
return response['Items']
@Utils.reliable
def GetQuotes(self, symbol, date):
try:
self.Logger.info('Calling quotes query Date key: %s' % date)
response = self.__QuotesEod.query(
KeyConditionExpression=Key('Symbol').eq(symbol) & Key('Date').eq(date)
)
except ClientError as e:
self.Logger.error(e.response['Error']['Message'])
return None
except Exception as e:
self.Logger.error(e)
return None
else:
self.Logger.info(json.dumps(response, indent=4, cls=DecimalEncoder))
if 'Items' in response:
return response['Items']
def lambda_handler(event, context):
params = CapsuleParams()
params.Region = os.environ["NIGHT_WATCH_REGION"]
params.Instance = os.environ["NIGHT_WATCH_INSTANCE"]
params.Email = os.environ["NIGHT_WATCH_EMAIL"]
params.Iam = os.environ["NIGHT_WATCH_IAM"]
params.User = os.environ["NIGHT_WATCH_USER"]
params.Password = os.environ["NIGHT_WATCH_PASSWORD"]
params.Smtp = os.environ["NIGHT_WATCH_SMTP"]
controller = CapsuleController(params)
try:
controller.FindSystemStopOrders()
except Exception as e:
controller.Logger.error('FindSystemStopOrders: %s' % e)
controller.ValidateExecutor()
controller.EndOfDay()
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--region', help='AWS region', required=True)
parser.add_argument('--instance', help='EC2 instance', required=True)
parser.add_argument('--email', help='Email address', required=True)
parser.add_argument('--iam', help='IAM Role', required=True)
parser.add_argument('--user', help='SMTP User', required=True)
parser.add_argument('--password', help='SMTP Password', required=True)
parser.add_argument('--smtp', help='SMTP Address', required=True)
parser.add_argument('--debug', help='Debug Folder', required=True)
args = parser.parse_args()
os.environ["NIGHT_WATCH_REGION"] = args.region
os.environ["NIGHT_WATCH_INSTANCE"] = args.instance
os.environ["NIGHT_WATCH_EMAIL"] = args.email
os.environ["NIGHT_WATCH_IAM"] = args.iam
os.environ["NIGHT_WATCH_USER"] = args.user
os.environ["NIGHT_WATCH_PASSWORD"] = args.password
os.environ["NIGHT_WATCH_SMTP"] = args.smtp
os.environ["DEBUG_FOLDER"] = args.debug
event = ''
context = ''
lambda_handler(event, context)
if __name__ == "__main__":
main()<|fim▁end|> | |
<|file_name|>Packet.java<|end_file_name|><|fim▁begin|>/*
* Copyright (c) 2005 Dizan Vasquez.
*
* 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.
*/
package net.jenet;
import java.nio.ByteBuffer;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
/**
* Wraps information to be sent through JeNet.
* @author Dizan Vasquez
*/
public class Packet implements IBufferable {
/**
* Indicates that this packet is reliable
*/
public static final int FLAG_RELIABLE = 1;
/**
* Indicates that the packet should be processed no
* matter its order relative to other packets.
*/
public static final int FLAG_UNSEQUENCED = 2;
protected int referenceCount;
protected int flags;
protected ByteBuffer data;
protected int dataLength;
private Packet() {
super();
}
/**
* Creates a new Packet.
* The constructor allocates a new packet and allocates a
* buffer of <code>dataLength</code> bytes for it.
*
* @param dataLength
* The size in bytes of this packet.
* @param flags
* An byte inidicating the how to handle this packet.
*/
public Packet( int dataLength, int flags ) {
data = ByteBuffer.allocateDirect( dataLength );
this.dataLength = dataLength;
this.flags = flags;
}
/**
* Copies this packet's data into the given buffer.
* @param buffer
* Destination buffer
*/
public void toBuffer( ByteBuffer buffer ) {
data.flip();
for ( int i = 0; i < dataLength; i++ ) {
buffer.put( data.get() );
}
}
/**
* Copies part of this packet's data into the given buffer.
* @param buffer
* Destination buffer
* @param offset
* Initial position of the destination buffer
* @param length
* Total number of bytes to copy
*/
public void toBuffer( ByteBuffer buffer, int offset, int length ) {
int position = data.position();
int limit = data.limit();
data.flip();
data.position( offset );
for ( int i = 0; i < length; i++ ) {
buffer.put( data.get() );
}
data.position( position );
data.limit( limit );
}
/**
* Copies the given buffer into this packet's data.
* @ param buffer
* Buffer to copy from
*/
public void fromBuffer( ByteBuffer buffer ) {
data.clear();
for ( int i = 0; i < dataLength; i++ ) {
data.put( buffer.get() );
}
}
/**
* Copies part of the given buffer into this packet's data.
* @param buffer
* Buffer to copy from
* @param fragmentOffset
* Position of the first byte to copy<|fim▁hole|> */
public void fromBuffer( ByteBuffer buffer, int fragmentOffset, int length ) {
data.position( fragmentOffset );
for ( int i = 0; i < length; i++ ) {
data.put( buffer.get() );
}
data.position( dataLength );
data.limit( dataLength );
}
/**
* Returs size of this packet.
* @return Size in bytes of this packet
*/
public int byteSize() {
return dataLength;
}
/**
* Returns the data contained in this packet
* @return Returns the data.
*/
public ByteBuffer getData() {
return data;
}
/**
* Returns the size in bytes of this packet's data
* @return Returns the dataLength.
*/
public int getDataLength() {
return dataLength;
}
/**
* Returns this packet's flags.
* @return Returns the flags.
*/
public int getFlags() {
return flags;
}
/**
* @return Returns the referenceCount.
*/
int getReferenceCount() {
return referenceCount;
}
/**
* Sets the flags for this packet.
* The parameter is an or of the flags <code>FLAG_RELIABLE</code> and <code>FLAG_UNSEQUENCED</code>
* a value of zero indicates an unreliable, sequenced (last one is kept) packet.
* @param flags
* The flags to set.
*/
public void setFlags( int flags ) {
this.flags = flags;
}
/**
* @param referenceCount
* The referenceCount to set.
*/
void setReferenceCount( int referenceCount ) {
this.referenceCount = referenceCount;
}
public String toString() {
return ToStringBuilder.reflectionToString( this, ToStringStyle.MULTI_LINE_STYLE );
}
}<|fim▁end|> | * @param length
* Total number of bytes to copy |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.