prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>commandline.py<|end_file_name|><|fim▁begin|>from optparse import OptionParser
import os,sys
from oldowan.mitotype.matcher import HVRMatcher
from oldowan.mitotype.prevalidate import prevalidate_submission
def run_command():
"""Perform automated human mtDNA haplotype identification."""
# Set up the options parser
usage = "usage: %prog [options] sequence|filename"
parser = OptionParser(usage=usage)
parser.add_option('-f',
'--file',
action='store_true',
default=False,
help='load sequences from FASTA file',
dest='use_file')
parser.add_option('-c',
'--csv',
action='store_true',
dest='csv',
default=False,
help='output in comma-separated-value format')
parser.add_option('-n',
'--no-csv-header',
action='store_false',
dest='csv_header',
default=True,
help='output a csv header')
parser.add_option('-o',
'--out',
dest='outfile',
help='write results to FILE',
default=False,
metavar='FILE')
# Parse the options
(options, args) = parser.parse_args()
# At least one argument is always required.
# It will be either the sequence to be tested, or
# When the -f flag is used, the filename of the fasta file
# to be tested
if len(args) != 1:
if options.use_file:
print 'You must provide a filename!'
print "Type 'mitotype -h' for help."
else:
print 'You must provide a sequence to test'
print "Type 'mitotype -h' for help."
sys.exit(1)
# If we've made it this far we're probably going to have to do some
# actual work; initialize the matcher.
hvrm = HVRMatcher()
# Do the work, either:<|fim▁hole|> if os.path.exists(args[0]):
f = open(args[0], 'r')
working_text = f.read()
f.close()
else:
print 'ERROR: Could not find file: %s' % args[0]
sys.exit(1)
else:
working_text = args[0]
vi = prevalidate_submission(working_text)
if not vi.valid:
print 'ERROR: Could not validate input: %s' % vi.problem
results = hvrm.match(working_text, vi)
# If outfile option is used, make stdout point to that file
if options.outfile:
outf = open(options.outfile, 'w')
sys.stdout = outf
# If we're outputing to CSV, spit out a header
if options.csv and options.csv_header:
print 'Query Label,Query Defining Positions,Motif Label,Match Score,Motif Defining Positions,Source'
# Output the results
for r in results:
if options.csv:
for row in r.csv_rows():
print row
else:
print r
sys.stdout.flush()<|fim▁end|> | # (1) load the fasta file
# (2) use sequence passed on the command line
working_text = ''
if options.use_file: |
<|file_name|>async_job.py<|end_file_name|><|fim▁begin|>__author__ = 'en0'
from http import context
from uuid import uuid4
from redis import Redis
from gevent import spawn
from functools import wraps
class AsyncJob(object):
def __init__(self, target):
assert isinstance(context.db, Redis)
self._target = target
self._db = context.db
def __call__(self, fn):
wraps(fn)
def _wrapper(*args, **kwargs):
_args = fn(*args, **kwargs)
_job_id = str(uuid4())
_key = "jobs:{0}".format(_job_id)
_status_key = "jobs:{0}:status".format(_job_id)
_expire_time = 3600
self._db.set(_status_key, 202)
self._db.expire(_status_key, _expire_time)
def task():
# noinspection PyBroadException
try:
data = self._target(*_args)
except:
self._db.set(_status_key, 500)
else:<|fim▁hole|> self._db.expire(_status_key, _expire_time)
spawn(task)
return dict(job=_job_id)
return _wrapper<|fim▁end|> | self._db.set(_key, data)
self._db.set(_status_key, 200)
self._db.expire(_key, _expire_time) |
<|file_name|>version.py<|end_file_name|><|fim▁begin|># Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import __version__
from ansible.errors import AnsibleError
from distutils.version import LooseVersion
from operator import eq, ge, gt
from sys import version_info
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
version_requirement = '2.5.0.0'
version_tested_max = '2.7.5'
python3_required_version = '2.5.3'
if version_info[0] == 3 and not ge(LooseVersion(__version__), LooseVersion(python3_required_version)):
raise AnsibleError(('Ansible >= {} is required when using Python 3.\n'
'Either downgrade to Python 2 or update your Ansible version to {}.').format(python3_required_version, python3_required_version))
if not ge(LooseVersion(__version__), LooseVersion(version_requirement)):
raise AnsibleError(('Trellis no longer supports Ansible {}.\n'
'Please upgrade to Ansible {} or higher.').format(__version__, version_requirement))
elif gt(LooseVersion(__version__), LooseVersion(version_tested_max)):
display.warning(u'You Ansible version is {} but this version of Trellis has only been tested for '<|fim▁hole|> display.warning(u'You Ansible version is {}. Consider upgrading your Ansible version to avoid '
u'erroneous warnings such as `Removed restricted key from module data...`'.format(__version__))
# Import BaseVarsPlugin after Ansible version check.
# Otherwise import error for Ansible versions older than 2.4 would prevent display of version check message.
from ansible.plugins.vars import BaseVarsPlugin
class VarsModule(BaseVarsPlugin):
def get_vars(self, loader, path, entities, cache=True):
return {}<|fim▁end|> | u'compatability with Ansible {} -> {}. It is advisable to check for Trellis updates or '
u'downgrade your Ansible version.'.format(__version__, version_requirement, version_tested_max))
if eq(LooseVersion(__version__), LooseVersion('2.5.0')): |
<|file_name|>color_space_10_8.py<|end_file_name|><|fim▁begin|>"""
HLS and Color Threshold
-----------------------
You've now seen that various color thresholds can be applied to find the lane lines in images. Here we'll explore
this a bit further and look at a couple examples to see why a color space like HLS can be more robust.
"""
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def run():
"""
Run different HLS and its thresholds.
"""
image = mpimg.imread('test6.jpg')
# Converting original to gray
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# Threshold for original image
thresh = (180, 255)
binary = np.zeros_like(gray)
binary[(gray > thresh[0]) & (gray <= thresh[1])] = 1
red = image[:, :, 0]
green = image[:, :, 1]
blue = image[:, :, 2]
thresh_2 = (200, 255)
binary_2 = np.zeros_like(red)
binary_2[(red > thresh_2[0]) & (red <= thresh_2[1])] = 1
# Converting image to HLS
hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)
# Splitting HSL
hue = hls[:, :, 0]
lightness = hls[:, :, 1]
saturation = hls[:, :, 2]
# Threshold for saturation
thresh_3 = (90, 255)
binary_3 = np.zeros_like(saturation)
binary_3[(saturation > thresh_3[0]) & (saturation <= thresh_3[1])] = 1
# Threshold for Hue
thresh_4 = (15, 100)
binary_4 = np.zeros_like(hue)
binary_4[(hue > thresh_4[0]) & (hue <= thresh_4[1])] = 1
# -------------------- Figure -----------------------
f = plt.figure()
size_x, size_y = (4, 4)
f.add_subplot(size_x, size_y, 1)
plt.imshow(image)
plt.title("Original")
f.add_subplot(size_x, size_y, 2)
plt.imshow(gray, cmap='gray')
plt.title("Gray")
f.add_subplot(size_x, size_y, 3)
plt.imshow(binary, cmap='gray')<|fim▁hole|> plt.imshow(red, cmap='gray')
plt.title("Red")
f.add_subplot(size_x, size_y, 5)
plt.imshow(green, cmap='gray')
plt.title("Green")
f.add_subplot(size_x, size_y, 6)
plt.imshow(blue, cmap='gray')
plt.title("Blue")
f.add_subplot(size_x, size_y, 7)
plt.imshow(binary_2, cmap='gray')
plt.title("Threshold of Red color")
f.add_subplot(size_x, size_y, 8)
plt.imshow(hue, cmap='gray')
plt.title("Hue")
f.add_subplot(size_x, size_y, 9)
plt.imshow(lightness, cmap='gray')
plt.title("Lightness")
f.add_subplot(size_x, size_y, 10)
plt.imshow(saturation, cmap='gray')
plt.title("Saturation")
f.add_subplot(size_x, size_y, 11)
plt.imshow(binary_3, cmap='gray')
plt.title("Threshold of saturation")
f.add_subplot(size_x, size_y, 12)
plt.imshow(binary_4, cmap='gray')
plt.title("Threshold of hue")
plt.show()
if __name__ == '__main__':
run()<|fim▁end|> | plt.title("Threshold of ({}, {})".format(thresh[0], thresh[1]))
f.add_subplot(size_x, size_y, 4) |
<|file_name|>mock-ng2-localforage.service.spec.ts<|end_file_name|><|fim▁begin|>import { Injectable } from '@angular/core';
import { ReplaySubject, Subject } from 'rxjs/Rx';
@Injectable()
export class MockNg2LocalforageService {
item;
list;
constructor() {
this.onInit();
}
onInit() {
this.item = new Subject();
this.list = new ReplaySubject();
}
getItem(input) {
if (input === 'list-2') {
return this.list.asObservable();
}
return this.item.asObservable();
}
setItem(input) {
}
update(updateInput, list?: boolean) {
if (list) {
this.list.next(updateInput);<|fim▁hole|> }
}
}<|fim▁end|> | } else {
this.item.next(updateInput);
this.item.complete(); |
<|file_name|>OSLImageUI.py<|end_file_name|><|fim▁begin|>##########################################################################
#
# Copyright (c) 2013-2014, John Haddon. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import IECore
import Gaffer
import GafferUI
import GafferOSL
import imath
import functools
_channelNamesOptions = {
"RGB" : IECore.Color3fData( imath.Color3f( 1 ) ),
"RGBA" : IECore.Color4fData( imath.Color4f( 1 ) ),
"R" : IECore.FloatData( 1 ),
"G" : IECore.FloatData( 1 ),
"B" : IECore.FloatData( 1 ),
"A" : IECore.FloatData( 1 ),
"customChannel" : IECore.FloatData( 1 ),
"customLayer" : IECore.Color3fData( imath.Color3f( 1 ) ),
"customLayerRGBA" : IECore.Color4fData( imath.Color4f( 1 ) ),
"closure" : None,
}
##########################################################################
# _ChannelsFooter
##########################################################################
class _ChannelsFooter( GafferUI.PlugValueWidget ) :
def __init__( self, plug ) :
row = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal )
GafferUI.PlugValueWidget.__init__( self, row, plug )
with row :
GafferUI.Spacer( imath.V2i( GafferUI.PlugWidget.labelWidth(), 1 ) )
menuButton = GafferUI.MenuButton(
image = "plus.png",
hasFrame = False,
menu = GafferUI.Menu(
Gaffer.WeakMethod( self.__menuDefinition ),
title = "Add Input"
),
toolTip = "Add Input"
)
menuButton.setEnabled( not Gaffer.MetadataAlgo.readOnly( plug ) )
GafferUI.Spacer( imath.V2i( 1 ), imath.V2i( 999999, 1 ), parenting = { "expand" : True } )
def _updateFromPlug( self ) :
self.setEnabled( self._editable() )
def __menuDefinition( self ) :
result = IECore.MenuDefinition()
usedNames = set()<|fim▁hole|> # ( it's based on Switch::variesWithContext )
sourcePlug = p["name"].source()
variesWithContext = sourcePlug.direction() == Gaffer.Plug.Direction.Out and isinstance( ComputeNode, sourcePlug.node() )
if not variesWithContext:
usedNames.add( p["name"].getValue() )
# Use a fixed order for some standard options that we want to list in a specific order
sortedOptions = []
for label in ["RGB", "RGBA", "R", "G", "B", "A" ]:
sortedOptions.append( (label, _channelNamesOptions[label] ) )
for label, defaultData in sorted( _channelNamesOptions.items() ):
if not label in [ i[0] for i in sortedOptions ]:
sortedOptions.append( (label, defaultData) )
categories = { "Standard" : [], "Custom" : [], "Advanced" : [] }
for label, defaultData in sortedOptions:
if label == "closure":
categories["Advanced"].append( ( label, label, defaultData ) )
else:
bareLabel = label.replace( "RGBA", "" ).replace( "RGB", "" )
channelName = bareLabel
if label.startswith( "custom" ):
if channelName in usedNames:
suffix = 2
while True:
channelName = bareLabel + str( suffix )
if not channelName in usedNames:
break
suffix += 1
categories["Custom"].append( ( label, channelName, defaultData ) )
else:
if channelName in usedNames:
continue
categories["Standard"].append( ( label, channelName, defaultData ) )
for category in [ "Standard", "Custom", "Advanced" ]:
for ( menuLabel, channelName, defaultData ) in categories[category]:
result.append(
"/" + category + "/" + menuLabel,
{
"command" : functools.partial( Gaffer.WeakMethod( self.__addPlug ), channelName, defaultData ),
}
)
return result
def __addPlug( self, name, defaultData ) :
alphaValue = None
if isinstance( defaultData, IECore.Color4fData ):
alphaValue = Gaffer.FloatPlug( "value", Gaffer.Plug.Direction.In, defaultData.value.a )
defaultData = IECore.Color3fData( imath.Color3f( defaultData.value.r, defaultData.value.g, defaultData.value.b ) )
if defaultData == None:
plugName = "closure"
name = ""
valuePlug = GafferOSL.ClosurePlug( "value" )
else:
plugName = "channel"
valuePlug = Gaffer.PlugAlgo.createPlugFromData( "value", Gaffer.Plug.Direction.In, Gaffer.Plug.Flags.Default, defaultData )
with Gaffer.UndoScope( self.getPlug().ancestor( Gaffer.ScriptNode ) ) :
self.getPlug().addChild( Gaffer.NameValuePlug( name, valuePlug, True, plugName, Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic ) )
if alphaValue:
self.getPlug().addChild(
Gaffer.NameValuePlug( name + ".A" if name else "A", alphaValue, True, plugName, Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic )
)
def __channelLabelFromPlug( plug ):
if plug.typeId() == GafferOSL.ClosurePlug.staticTypeId():
return plug.parent().getName()
elif plug.typeId() == Gaffer.Color3fPlug.staticTypeId() and plug.parent()["name"].getValue() == "":
return "[RGB]"
else:
return plug.parent()["name"].getValue()
##########################################################################
# Metadata
##########################################################################
Gaffer.Metadata.registerNode(
GafferOSL.OSLImage,
"description",
"""
Executes OSL shaders to perform image processing. Use the shaders from
the OSL/ImageProcessing menu to read values from the input image and
then write values back to it.
""",
"plugAdderOptions", IECore.CompoundData( _channelNamesOptions ),
"layout:activator:defaultFormatActive", lambda node : not node["in"].getInput(),
plugs = {
"defaultFormat" : [
"description",
"""
The resolution and aspect ratio to output when there is no input image provided.
""",
"layout:activator", "defaultFormatActive",
],
"channels" : [
"description",
"""
Define image channels to output by adding child plugs and connecting
corresponding OSL shaders. You can drive RGB layers with a color,
or connect individual channels to a float.
If you want to add multiple channels at once, you can also add a closure plug,
which can accept a connection from an OSLCode with a combined output closure.
""",
"layout:customWidget:footer:widgetType", "GafferOSLUI.OSLImageUI._ChannelsFooter",
"layout:customWidget:footer:index", -1,
"nodule:type", "GafferUI::CompoundNodule",
"noduleLayout:section", "left",
"noduleLayout:spacing", 0.2,
"plugValueWidget:type", "GafferUI.LayoutPlugValueWidget",
# Add + button for showing and hiding parameters in the GraphEditor
"noduleLayout:customGadget:addButton:gadgetType", "GafferOSLUI.OSLImageUI.PlugAdder",
],
"channels.*" : [
# Although the parameters plug is positioned
# as we want above, we must also register
# appropriate values for each individual parameter,
# for the case where they get promoted to a box
# individually.
"noduleLayout:section", "left",
"nodule:type", "GafferUI::CompoundNodule",
"nameValuePlugPlugValueWidget:ignoreNamePlug", lambda plug : isinstance( plug["value"], GafferOSL.ClosurePlug ),
],
"channels.*.name" : [
"nodule:type", "",
"stringPlugValueWidget:placeholderText", lambda plug : "[RGB]" if isinstance( plug.parent()["value"], Gaffer.Color3fPlug ) else None,
],
"channels.*.enabled" : [
"nodule:type", "",
],
"channels.*.value" : [
# Although the parameters plug is positioned
# as we want above, we must also register
# appropriate values for each individual parameter,
# for the case where they get promoted to a box
# individually.
"noduleLayout:section", "left",
"nodule:type", "GafferUI::StandardNodule",
"noduleLayout:label", __channelLabelFromPlug,
"ui:visibleDimensions", lambda plug : 2 if hasattr( plug, "interpretation" ) and plug.interpretation() == IECore.GeometricData.Interpretation.UV else None,
],
}
)<|fim▁end|> | for p in self.getPlug().children():
# TODO - this method for checking if a plug variesWithContext should probably live in PlugAlgo |
<|file_name|>main.go<|end_file_name|><|fim▁begin|>// Copyright 2010 The Freetype-Go Authors. All rights reserved.
// Use of this source code is governed by your choice of either the
// FreeType License or the GNU General Public License version 2 (or
// any later version), both of which can be found in the LICENSE file.
// +build ignore
//
// This build tag means that "go install yougam/libraries/golang/freetype/..."
// doesn't install this example program. Use "go run main.go" to run it.
package main
import (
"bufio"
"fmt"
"image"
"image/draw"
"image/png"
"log"
"os"
"github.com/insionng/yougam/libraries/golang/freetype/raster"
"github.com/insionng/yougam/libraries/x/image/math/fixed"
)
func p(x, y int) fixed.Point26_6 {
return fixed.Point26_6{
X: fixed.Int26_6(x * 64),
Y: fixed.Int26_6(y * 64),
}
}
func main() {
// Draw a rounded corner that is one pixel wide.
r := raster.NewRasterizer(50, 50)
r.Start(p(5, 5))
r.Add1(p(5, 25))
r.Add2(p(5, 45), p(25, 45))
r.Add1(p(45, 45))
r.Add1(p(45, 44))
r.Add1(p(26, 44))
r.Add2(p(6, 44), p(6, 24))
r.Add1(p(6, 5))
r.Add1(p(5, 5))
// Rasterize that curve multiple times at different gammas.
const (
w = 600
h = 200
)
rgba := image.NewRGBA(image.Rect(0, 0, w, h))
draw.Draw(rgba, image.Rect(0, 0, w, h/2), image.Black, image.ZP, draw.Src)
draw.Draw(rgba, image.Rect(0, h/2, w, h), image.White, image.ZP, draw.Src)
mask := image.NewAlpha(image.Rect(0, 0, 50, 50))
painter := raster.NewAlphaSrcPainter(mask)
gammas := []float64{1.0 / 10.0, 1.0 / 3.0, 1.0 / 2.0, 2.0 / 3.0, 4.0 / 5.0, 1.0, 5.0 / 4.0, 3.0 / 2.0, 2.0, 3.0, 10.0}
for i, g := range gammas {
draw.Draw(mask, mask.Bounds(), image.Transparent, image.ZP, draw.Src)
r.Rasterize(raster.NewGammaCorrectionPainter(painter, g))
x, y := 50*i+25, 25
draw.DrawMask(rgba, image.Rect(x, y, x+50, y+50), image.White, image.ZP, mask, image.ZP, draw.Over)
y += 100
draw.DrawMask(rgba, image.Rect(x, y, x+50, y+50), image.Black, image.ZP, mask, image.ZP, draw.Over)
}
// Save that RGBA image to disk.
outFile, err := os.Create("out.png")
if err != nil {
log.Println(err)
os.Exit(1)
}
defer outFile.Close()
b := bufio.NewWriter(outFile)
err = png.Encode(b, rgba)<|fim▁hole|> if err != nil {
log.Println(err)
os.Exit(1)
}
err = b.Flush()
if err != nil {
log.Println(err)
os.Exit(1)
}
fmt.Println("Wrote out.png OK.")
}<|fim▁end|> | |
<|file_name|>pispi1.py<|end_file_name|><|fim▁begin|>import spi
from time import sleep<|fim▁hole|>a = spi.SPI(0,0)
print "PY: initisalising SPI mode ...\n"<|fim▁end|> | |
<|file_name|>let-else-if.rs<|end_file_name|><|fim▁begin|><|fim▁hole|> let Some(_) = Some(()) else if true {
//~^ ERROR conditional `else if` is not supported for `let...else`
return;
} else {
return;
};
}<|fim▁end|> | #![feature(let_else)]
fn main() { |
<|file_name|>utils.go<|end_file_name|><|fim▁begin|>package lineargo
/*
#include <stdlib.h>
*/
import "C"
import "unsafe"
func mapCDouble(in []float64) []C.double {
out := make([]C.double, len(in), len(in))<|fim▁hole|>}
func mapCInt(in []int) []C.int {
out := make([]C.int, len(in), len(in))
for i, val := range in {
out[i] = C.int(val)
}
return out
}
// convert C double pointer to float64 slice ...
func doubleToFloats(in *C.double, size int) []float64 {
defer C.free(unsafe.Pointer(in))
outD := (*[1 << 30]C.double)(unsafe.Pointer(in))[:size:size]
out := make([]float64, size, size)
for i := 0; i < size; i++ {
out[i] = float64(outD[i])
}
return out
}<|fim▁end|> | for i, val := range in {
out[i] = C.double(val)
}
return out |
<|file_name|>types.go<|end_file_name|><|fim▁begin|>// Copyright 2016-2019 Authors of Cilium
//
// 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 ctmap
import (
"bytes"
"fmt"
"unsafe"
"github.com/cilium/cilium/pkg/bpf"
"github.com/cilium/cilium/pkg/byteorder"
"github.com/cilium/cilium/pkg/tuple"
)
// mapType is a type of connection tracking map.
type mapType int
const (
// mapTypeIPv4TCPLocal and friends are map types which correspond to a
// combination of the following attributes:
// * IPv4 or IPv6;
// * TCP or non-TCP (shortened to Any)
// * Local (endpoint-specific) or global (endpoint-oblivious).
mapTypeIPv4TCPLocal mapType = iota
mapTypeIPv6TCPLocal
mapTypeIPv4TCPGlobal
mapTypeIPv6TCPGlobal
mapTypeIPv4AnyLocal
mapTypeIPv6AnyLocal
mapTypeIPv4AnyGlobal
mapTypeIPv6AnyGlobal
mapTypeMax
)
// String renders the map type into a user-readable string.
func (m mapType) String() string {
switch m {
case mapTypeIPv4TCPLocal:
return "Local IPv4 TCP CT map"
case mapTypeIPv6TCPLocal:
return "Local IPv6 TCP CT map"
case mapTypeIPv4TCPGlobal:
return "Global IPv4 TCP CT map"
case mapTypeIPv6TCPGlobal:
return "Global IPv6 TCP CT map"
case mapTypeIPv4AnyLocal:
return "Local IPv4 non-TCP CT map"
case mapTypeIPv6AnyLocal:
return "Local IPv6 non-TCP CT map"
case mapTypeIPv4AnyGlobal:
return "Global IPv4 non-TCP CT map"
case mapTypeIPv6AnyGlobal:
return "Global IPv6 non-TCP CT map"
}
return fmt.Sprintf("Unknown (%d)", int(m))
}
func (m mapType) isIPv4() bool {
switch m {
case mapTypeIPv4TCPLocal, mapTypeIPv4TCPGlobal, mapTypeIPv4AnyLocal, mapTypeIPv4AnyGlobal:
return true
}
return false
}
func (m mapType) isIPv6() bool {
switch m {
case mapTypeIPv6TCPLocal, mapTypeIPv6TCPGlobal, mapTypeIPv6AnyLocal, mapTypeIPv6AnyGlobal:
return true
}
return false
}
func (m mapType) isLocal() bool {
switch m {
case mapTypeIPv4TCPLocal, mapTypeIPv6TCPLocal, mapTypeIPv4AnyLocal, mapTypeIPv6AnyLocal:
return true
}
return false
}
func (m mapType) isGlobal() bool {
switch m {
case mapTypeIPv4TCPGlobal, mapTypeIPv6TCPGlobal, mapTypeIPv4AnyGlobal, mapTypeIPv6AnyGlobal:
return true
}
return false
}
func (m mapType) isTCP() bool {
switch m {
case mapTypeIPv4TCPLocal, mapTypeIPv6TCPLocal, mapTypeIPv4TCPGlobal, mapTypeIPv6TCPGlobal:
return true
}
return false
}
type CtKey interface {
bpf.MapKey
// ToNetwork converts fields to network byte order.
ToNetwork() CtKey
// ToHost converts fields to host byte order.
ToHost() CtKey
// Dump contents of key to buffer. Returns true if successful.
Dump(buffer *bytes.Buffer, reverse bool) bool
// GetFlags flags containing the direction of the CtKey.
GetFlags() uint8
GetTupleKey() tuple.TupleKey
}
// CtKey4 is needed to provide CtEntry type to Lookup values
// +k8s:deepcopy-gen=true
// +k8s:deepcopy-gen:interfaces=github.com/cilium/cilium/pkg/bpf.MapKey
type CtKey4 struct {
tuple.TupleKey4
}
// NewValue creates a new bpf.MapValue.
func (k *CtKey4) NewValue() bpf.MapValue { return &CtEntry{} }
// ToNetwork converts CtKey4 ports to network byte order.
func (k *CtKey4) ToNetwork() CtKey {
n := *k
n.SourcePort = byteorder.HostToNetwork(n.SourcePort).(uint16)
n.DestPort = byteorder.HostToNetwork(n.DestPort).(uint16)
return &n
}
// ToHost converts CtKey ports to host byte order.
func (k *CtKey4) ToHost() CtKey {
n := *k
n.SourcePort = byteorder.NetworkToHost(n.SourcePort).(uint16)
n.DestPort = byteorder.NetworkToHost(n.DestPort).(uint16)
return &n
}
// GetFlags returns the tuple's flags.
func (k *CtKey4) GetFlags() uint8 {
return k.Flags
}
func (k *CtKey4) String() string {
return fmt.Sprintf("%s:%d, %d, %d, %d", k.DestAddr, k.SourcePort, k.DestPort, k.NextHeader, k.Flags)
}
// GetKeyPtr returns the unsafe.Pointer for k.
func (k *CtKey4) GetKeyPtr() unsafe.Pointer { return unsafe.Pointer(k) }
// Dump writes the contents of key to buffer and returns true if the value for
// next header in the key is nonzero.
func (k *CtKey4) Dump(buffer *bytes.Buffer, reverse bool) bool {
var addrDest string
if k.NextHeader == 0 {
return false
}
// Addresses swapped, see issue #5848
if reverse {
addrDest = k.SourceAddr.IP().String()
} else {
addrDest = k.DestAddr.IP().String()
}
if k.Flags&TUPLE_F_IN != 0 {
buffer.WriteString(fmt.Sprintf("%s IN %s %d:%d ",
k.NextHeader.String(), addrDest, k.SourcePort,
k.DestPort),
)
} else {
buffer.WriteString(fmt.Sprintf("%s OUT %s %d:%d ",
k.NextHeader.String(), addrDest, k.DestPort,
k.SourcePort),
)
}
if k.Flags&TUPLE_F_RELATED != 0 {
buffer.WriteString("related ")
}
if k.Flags&TUPLE_F_SERVICE != 0 {
buffer.WriteString("service ")
}
return true
}
func (k *CtKey4) GetTupleKey() tuple.TupleKey {
return &k.TupleKey4
}
// CtKey4Global is needed to provide CtEntry type to Lookup values
// +k8s:deepcopy-gen=true
// +k8s:deepcopy-gen:interfaces=github.com/cilium/cilium/pkg/bpf.MapKey
type CtKey4Global struct {
tuple.TupleKey4Global
}
// NewValue creates a new bpf.MapValue.
func (k *CtKey4Global) NewValue() bpf.MapValue { return &CtEntry{} }
// ToNetwork converts ports to network byte order.
//<|fim▁hole|> return &CtKey4Global{
TupleKey4Global: *k.TupleKey4Global.ToNetwork().(*tuple.TupleKey4Global),
}
}
// ToHost converts ports to host byte order.
//
// This is necessary to prevent callers from implicitly converting
// the CtKey4Global type here into a local key type in the nested
// TupleKey4Global field.
func (k *CtKey4Global) ToHost() CtKey {
return &CtKey4Global{
TupleKey4Global: *k.TupleKey4Global.ToHost().(*tuple.TupleKey4Global),
}
}
// GetFlags returns the tuple's flags.
func (k *CtKey4Global) GetFlags() uint8 {
return k.Flags
}
func (k *CtKey4Global) String() string {
return fmt.Sprintf("%s:%d --> %s:%d, %d, %d", k.SourceAddr, k.SourcePort, k.DestAddr, k.DestPort, k.NextHeader, k.Flags)
}
// GetKeyPtr returns the unsafe.Pointer for k.
func (k *CtKey4Global) GetKeyPtr() unsafe.Pointer { return unsafe.Pointer(k) }
// Dump writes the contents of key to buffer and returns true if the
// value for next header in the key is nonzero.
func (k *CtKey4Global) Dump(buffer *bytes.Buffer, reverse bool) bool {
var addrSource, addrDest string
if k.NextHeader == 0 {
return false
}
// Addresses swapped, see issue #5848
if reverse {
addrSource = k.DestAddr.IP().String()
addrDest = k.SourceAddr.IP().String()
} else {
addrSource = k.SourceAddr.IP().String()
addrDest = k.DestAddr.IP().String()
}
if k.Flags&TUPLE_F_IN != 0 {
buffer.WriteString(fmt.Sprintf("%s IN %s:%d -> %s:%d ",
k.NextHeader.String(), addrSource, k.SourcePort,
addrDest, k.DestPort),
)
} else {
buffer.WriteString(fmt.Sprintf("%s OUT %s:%d -> %s:%d ",
k.NextHeader.String(), addrSource, k.SourcePort,
addrDest, k.DestPort),
)
}
if k.Flags&TUPLE_F_RELATED != 0 {
buffer.WriteString("related ")
}
if k.Flags&TUPLE_F_SERVICE != 0 {
buffer.WriteString("service ")
}
return true
}
func (k *CtKey4Global) GetTupleKey() tuple.TupleKey {
return &k.TupleKey4Global
}
// CtKey6 is needed to provide CtEntry type to Lookup values
// +k8s:deepcopy-gen=true
// +k8s:deepcopy-gen:interfaces=github.com/cilium/cilium/pkg/bpf.MapKey
type CtKey6 struct {
tuple.TupleKey6
}
// NewValue creates a new bpf.MapValue.
func (k *CtKey6) NewValue() bpf.MapValue { return &CtEntry{} }
// ToNetwork converts CtKey6 ports to network byte order.
func (k *CtKey6) ToNetwork() CtKey {
return &CtKey6{
TupleKey6: *k.TupleKey6.ToNetwork().(*tuple.TupleKey6),
}
}
// ToHost converts CtKey ports to host byte order.
func (k *CtKey6) ToHost() CtKey {
return &CtKey6{
TupleKey6: *k.TupleKey6.ToHost().(*tuple.TupleKey6),
}
}
// GetFlags returns the tuple's flags.
func (k *CtKey6) GetFlags() uint8 {
return k.Flags
}
func (k *CtKey6) String() string {
return fmt.Sprintf("[%s]:%d, %d, %d, %d", k.DestAddr, k.SourcePort, k.DestPort, k.NextHeader, k.Flags)
}
// GetKeyPtr returns the unsafe.Pointer for k.
func (k *CtKey6) GetKeyPtr() unsafe.Pointer { return unsafe.Pointer(k) }
// Dump writes the contents of key to buffer and returns true if the value for
// next header in the key is nonzero.
func (k *CtKey6) Dump(buffer *bytes.Buffer, reverse bool) bool {
var addrDest string
if k.NextHeader == 0 {
return false
}
// Addresses swapped, see issue #5848
if reverse {
addrDest = k.SourceAddr.IP().String()
} else {
addrDest = k.DestAddr.IP().String()
}
if k.Flags&TUPLE_F_IN != 0 {
buffer.WriteString(fmt.Sprintf("%s IN %s %d:%d ",
k.NextHeader.String(), addrDest, k.SourcePort,
k.DestPort),
)
} else {
buffer.WriteString(fmt.Sprintf("%s OUT %s %d:%d ",
k.NextHeader.String(), addrDest, k.DestPort,
k.SourcePort),
)
}
if k.Flags&TUPLE_F_RELATED != 0 {
buffer.WriteString("related ")
}
if k.Flags&TUPLE_F_SERVICE != 0 {
buffer.WriteString("service ")
}
return true
}
func (k *CtKey6) GetTupleKey() tuple.TupleKey {
return &k.TupleKey6
}
// CtKey6Global is needed to provide CtEntry type to Lookup values
// +k8s:deepcopy-gen=true
// +k8s:deepcopy-gen:interfaces=github.com/cilium/cilium/pkg/bpf.MapKey
type CtKey6Global struct {
tuple.TupleKey6Global
}
const SizeofCtKey6Global = int(unsafe.Sizeof(CtKey6Global{}))
// NewValue creates a new bpf.MapValue.
func (k *CtKey6Global) NewValue() bpf.MapValue { return &CtEntry{} }
// ToNetwork converts ports to network byte order.
//
// This is necessary to prevent callers from implicitly converting
// the CtKey6Global type here into a local key type in the nested
// TupleKey6Global field.
func (k *CtKey6Global) ToNetwork() CtKey {
return &CtKey6Global{
TupleKey6Global: *k.TupleKey6Global.ToNetwork().(*tuple.TupleKey6Global),
}
}
// ToHost converts ports to host byte order.
//
// This is necessary to prevent callers from implicitly converting
// the CtKey6Global type here into a local key type in the nested
// TupleKey6Global field.
func (k *CtKey6Global) ToHost() CtKey {
return &CtKey6Global{
TupleKey6Global: *k.TupleKey6Global.ToHost().(*tuple.TupleKey6Global),
}
}
// GetFlags returns the tuple's flags.
func (k *CtKey6Global) GetFlags() uint8 {
return k.Flags
}
func (k *CtKey6Global) String() string {
return fmt.Sprintf("[%s]:%d --> [%s]:%d, %d, %d", k.SourceAddr, k.SourcePort, k.DestAddr, k.DestPort, k.NextHeader, k.Flags)
}
// GetKeyPtr returns the unsafe.Pointer for k.
func (k *CtKey6Global) GetKeyPtr() unsafe.Pointer { return unsafe.Pointer(k) }
// Dump writes the contents of key to buffer and returns true if the
// value for next header in the key is nonzero.
func (k *CtKey6Global) Dump(buffer *bytes.Buffer, reverse bool) bool {
var addrSource, addrDest string
if k.NextHeader == 0 {
return false
}
// Addresses swapped, see issue #5848
if reverse {
addrSource = k.DestAddr.IP().String()
addrDest = k.SourceAddr.IP().String()
} else {
addrSource = k.SourceAddr.IP().String()
addrDest = k.DestAddr.IP().String()
}
if k.Flags&TUPLE_F_IN != 0 {
buffer.WriteString(fmt.Sprintf("%s IN %s:%d -> %s:%d ",
k.NextHeader.String(), addrSource, k.SourcePort,
addrDest, k.DestPort),
)
} else {
buffer.WriteString(fmt.Sprintf("%s OUT %s:%d -> %s:%d ",
k.NextHeader.String(), addrSource, k.SourcePort,
addrDest, k.DestPort),
)
}
if k.Flags&TUPLE_F_RELATED != 0 {
buffer.WriteString("related ")
}
if k.Flags&TUPLE_F_SERVICE != 0 {
buffer.WriteString("service ")
}
return true
}
func (k *CtKey6Global) GetTupleKey() tuple.TupleKey {
return &k.TupleKey6Global
}
// CtEntry represents an entry in the connection tracking table.
// +k8s:deepcopy-gen=true
// +k8s:deepcopy-gen:interfaces=github.com/cilium/cilium/pkg/bpf.MapValue
type CtEntry struct {
RxPackets uint64 `align:"rx_packets"`
RxBytes uint64 `align:"rx_bytes"`
TxPackets uint64 `align:"tx_packets"`
TxBytes uint64 `align:"tx_bytes"`
Lifetime uint32 `align:"lifetime"`
Flags uint16 `align:"rx_closing"`
// RevNAT is in network byte order
RevNAT uint16 `align:"rev_nat_index"`
IfIndex uint16 `align:"ifindex"`
TxFlagsSeen uint8 `align:"tx_flags_seen"`
RxFlagsSeen uint8 `align:"rx_flags_seen"`
SourceSecurityID uint32 `align:"src_sec_id"`
LastTxReport uint32 `align:"last_tx_report"`
LastRxReport uint32 `align:"last_rx_report"`
}
const SizeofCtEntry = int(unsafe.Sizeof(CtEntry{}))
// GetValuePtr returns the unsafe.Pointer for s.
func (c *CtEntry) GetValuePtr() unsafe.Pointer { return unsafe.Pointer(c) }
const (
RxClosing = 1 << iota
TxClosing
Nat64
LBLoopback
SeenNonSyn
NodePort
ProxyRedirect
DSR
MaxFlags
)
func (c *CtEntry) flagsString() string {
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("Flags=%#04x [ ", c.Flags))
if (c.Flags & RxClosing) != 0 {
buffer.WriteString("RxClosing ")
}
if (c.Flags & TxClosing) != 0 {
buffer.WriteString("TxClosing ")
}
if (c.Flags & Nat64) != 0 {
buffer.WriteString("Nat64 ")
}
if (c.Flags & LBLoopback) != 0 {
buffer.WriteString("LBLoopback ")
}
if (c.Flags & SeenNonSyn) != 0 {
buffer.WriteString("SeenNonSyn ")
}
if (c.Flags & NodePort) != 0 {
buffer.WriteString("NodePort ")
}
if (c.Flags & ProxyRedirect) != 0 {
buffer.WriteString("ProxyRedirect ")
}
if (c.Flags & DSR) != 0 {
buffer.WriteString("DSR ")
}
unknownFlags := c.Flags
unknownFlags &^= MaxFlags - 1
if unknownFlags != 0 {
buffer.WriteString(fmt.Sprintf("Unknown=%#04x ", unknownFlags))
}
buffer.WriteString("]")
return buffer.String()
}
// String returns the readable format
func (c *CtEntry) String() string {
return fmt.Sprintf("expires=%d RxPackets=%d RxBytes=%d RxFlagsSeen=%#02x LastRxReport=%d TxPackets=%d TxBytes=%d TxFlagsSeen=%#02x LastTxReport=%d %s RevNAT=%d SourceSecurityID=%d IfIndex=%d \n",
c.Lifetime,
c.RxPackets,
c.RxBytes,
c.RxFlagsSeen,
c.LastRxReport,
c.TxPackets,
c.TxBytes,
c.TxFlagsSeen,
c.LastTxReport,
c.flagsString(),
byteorder.NetworkToHost(c.RevNAT),
c.SourceSecurityID,
c.IfIndex)
}<|fim▁end|> | // This is necessary to prevent callers from implicitly converting
// the CtKey4Global type here into a local key type in the nested
// TupleKey4Global field.
func (k *CtKey4Global) ToNetwork() CtKey { |
<|file_name|>Task.js<|end_file_name|><|fim▁begin|>/*
Node-OpenDroneMap Node.js App and REST API to access OpenDroneMap.
Copyright (C) 2016 Node-OpenDroneMap Contributors
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/>.
*/
"use strict";
const config = require('../config');
const async = require('async');
const assert = require('assert');
const logger = require('./logger');
const fs = require('fs');
const glob = require("glob");
const path = require('path');
const rmdir = require('rimraf');
const odmRunner = require('./odmRunner');
const processRunner = require('./processRunner');
const archiver = require('archiver');
const Directories = require('./Directories');
const kill = require('tree-kill');
const S3 = require('./S3');
const request = require('request');
const utils = require('./utils');
const statusCodes = require('./statusCodes');
module.exports = class Task{
constructor(uuid, name, options = [], webhook = null, skipPostProcessing = false, outputs = [], done = () => {}){
assert(uuid !== undefined, "uuid must be set");
assert(done !== undefined, "ready must be set");
this.uuid = uuid;
this.name = name !== "" ? name : "Task of " + (new Date()).toISOString();
this.dateCreated = new Date().getTime();
this.processingTime = -1;
this.setStatus(statusCodes.QUEUED);
this.options = options;
this.gcpFiles = [];
this.output = [];
this.runningProcesses = [];
this.webhook = webhook;
this.skipPostProcessing = skipPostProcessing;
this.outputs = utils.parseUnsafePathsList(outputs);
async.series([
// Read images info
cb => {
fs.readdir(this.getImagesFolderPath(), (err, files) => {
if (err) cb(err);
else{
this.images = files;
logger.debug(`Found ${this.images.length} images for ${this.uuid}`);
cb(null);
}
});
},
// Find GCP (if any)
cb => {
fs.readdir(this.getGcpFolderPath(), (err, files) => {
if (err) cb(err);
else{
files.forEach(file => {
if (/\.txt$/gi.test(file)){
this.gcpFiles.push(file);
}
});
logger.debug(`Found ${this.gcpFiles.length} GCP files (${this.gcpFiles.join(" ")}) for ${this.uuid}`);
cb(null);
}
});
}
], err => {
done(err, this);
});
}
static CreateFromSerialized(taskJson, done){
new Task(taskJson.uuid,
taskJson.name,
taskJson.options,
taskJson.webhook,
taskJson.skipPostProcessing,
taskJson.outputs,
(err, task) => {
if (err) done(err);
else{
// Override default values with those
// provided in the taskJson
for (let k in taskJson){
task[k] = taskJson[k];
}
// Tasks that were running should be put back to QUEUED state
if (task.status.code === statusCodes.RUNNING){
task.status.code = statusCodes.QUEUED;
}
done(null, task);
}
});
}
// Get path where images are stored for this task
// (relative to nodejs process CWD)
getImagesFolderPath(){
return path.join(this.getProjectFolderPath(), "images");
}
// Get path where GCP file(s) are stored
// (relative to nodejs process CWD)
getGcpFolderPath(){
return path.join(this.getProjectFolderPath(), "gcp");
}
// Get path of project (where all images and assets folder are contained)
// (relative to nodejs process CWD)
getProjectFolderPath(){
return path.join(Directories.data, this.uuid);
}
// Get the path of the archive where all assets
// outputted by this task are stored.
getAssetsArchivePath(filename){
if (filename == 'all.zip'){
// OK, do nothing
}else if (filename == 'orthophoto.tif'){
if (config.test){
if (config.testSkipOrthophotos) return false;
else filename = path.join('..', '..', 'processing_results', 'odm_orthophoto', `odm_${filename}`);
}else{
filename = path.join('odm_orthophoto', `odm_${filename}`);
}
}else{
return false; // Invalid
}
return path.join(this.getProjectFolderPath(), filename);
}
// Deletes files and folders related to this task
cleanup(cb){
rmdir(this.getProjectFolderPath(), cb);
}
setStatus(code, extra){
this.status = {
code: code
};
for (let k in extra){
this.status[k] = extra[k];
}
}
updateProcessingTime(resetTime){
this.processingTime = resetTime ?
-1 :
new Date().getTime() - this.dateCreated;
}
startTrackingProcessingTime(){
this.updateProcessingTime();
if (!this._updateProcessingTimeInterval){
this._updateProcessingTimeInterval = setInterval(() => {
this.updateProcessingTime();
}, 1000);
}
}
stopTrackingProcessingTime(resetTime){
this.updateProcessingTime(resetTime);
if (this._updateProcessingTimeInterval){
clearInterval(this._updateProcessingTimeInterval);
this._updateProcessingTimeInterval = null;
}
}
getStatus(){
return this.status.code;
}
isCanceled(){
return this.status.code === statusCodes.CANCELED;
}
// Cancels the current task (unless it's already canceled)
cancel(cb){
if (this.status.code !== statusCodes.CANCELED){
let wasRunning = this.status.code === statusCodes.RUNNING;
this.setStatus(statusCodes.CANCELED);
if (wasRunning){
this.runningProcesses.forEach(proc => {
// TODO: this does NOT guarantee that
// the process will immediately terminate.
// For eaxmple in the case of the ODM process, the process will continue running for a while
// This might need to be fixed on ODM's end.
// During testing, proc is undefined
if (proc) kill(proc.pid);
});
this.runningProcesses = [];
}
this.stopTrackingProcessingTime(true);
cb(null);
}else{
cb(new Error("Task already cancelled"));
}
}
// Starts processing the task with OpenDroneMap
// This will spawn a new process.
start(done){
const finished = err => {
this.stopTrackingProcessingTime();
done(err);
};
const postProcess = () => {
const createZipArchive = (outputFilename, files) => {
return (done) => {
this.output.push(`Compressing ${outputFilename}\n`);
let output = fs.createWriteStream(this.getAssetsArchivePath(outputFilename));
let archive = archiver.create('zip', {
zlib: { level: 1 } // Sets the compression level (1 = best speed since most assets are already compressed)
});
archive.on('finish', () => {
// TODO: is this being fired twice?
done();
});
archive.on('error', err => {
logger.error(`Could not archive .zip file: ${err.message}`);
done(err);
});
archive.pipe(output);
let globs = [];
const sourcePath = !config.test ?
this.getProjectFolderPath() :
path.join("tests", "processing_results");
// Process files and directories first
files.forEach(file => {
let filePath = path.join(sourcePath, file);
// Skip non-existing items
if (!fs.existsSync(filePath)) return;
let isGlob = /\*/.test(file),
isDirectory = !isGlob && fs.lstatSync(filePath).isDirectory();
if (isDirectory){
archive.directory(filePath, file);
}else if (isGlob){
globs.push(filePath);
}else{
archive.file(filePath, {name: file});
}
});
// Check for globs
if (globs.length !== 0){
let pending = globs.length;
globs.forEach(pattern => {
glob(pattern, (err, files) => {
if (err) done(err);
else{
files.forEach(file => {
if (fs.lstatSync(file).isFile()){
archive.file(file, {name: path.basename(file)});
}else{
logger.debug(`Could not add ${file} from glob`);
}
});
if (--pending === 0){
archive.finalize();
}
}
});
});
}else{
archive.finalize();
}
};
};
const runPostProcessingScript = () => {
return (done) => {
this.runningProcesses.push(
processRunner.runPostProcessingScript({
projectFolderPath: this.getProjectFolderPath()
}, (err, code, signal) => {
if (err) done(err);
else{
if (code === 0) done();
else done(new Error(`Process exited with code ${code}`));
}
}, output => {
this.output.push(output);
})
);
};
};
// All paths are relative to the project directory (./data/<uuid>/)
let allPaths = ['odm_orthophoto/odm_orthophoto.tif', 'odm_orthophoto/odm_orthophoto.mbtiles',<|fim▁hole|> 'odm_dem/dsm.tif', 'odm_dem/dtm.tif', 'dsm_tiles', 'dtm_tiles',
'orthophoto_tiles', 'potree_pointcloud', 'images.json'];
// Did the user request different outputs than the default?
if (this.outputs.length > 0) allPaths = this.outputs;
let tasks = [];
if (config.test){
if (config.testSkipOrthophotos){
logger.info("Test mode will skip orthophoto generation");
// Exclude these folders from the all.zip archive
['odm_orthophoto', 'orthophoto_tiles'].forEach(dir => {
allPaths.splice(allPaths.indexOf(dir), 1);
});
}
if (config.testSkipDems){
logger.info("Test mode will skip DEMs generation");
// Exclude these folders from the all.zip archive
['odm_dem/dsm.tif', 'odm_dem/dtm.tif', 'dsm_tiles', 'dtm_tiles'].forEach(p => {
allPaths.splice(allPaths.indexOf(p), 1);
});
}
if (config.testFailTasks){
logger.info("Test mode will fail the task");
tasks.push(done => done(new Error("Test fail")));
}
}
if (!this.skipPostProcessing) tasks.push(runPostProcessingScript());
tasks.push(createZipArchive('all.zip', allPaths));
// Upload to S3 all paths + all.zip file (if config says so)
if (S3.enabled()){
tasks.push((done) => {
let s3Paths;
if (config.test){
s3Paths = ['all.zip']; // During testing only upload all.zip
}else if (config.s3UploadEverything){
s3Paths = ['all.zip'].concat(allPaths);
}else{
s3Paths = ['all.zip', 'odm_orthophoto/odm_orthophoto.tif'];
}
S3.uploadPaths(this.getProjectFolderPath(), config.s3Bucket, this.uuid, s3Paths,
err => {
if (!err) this.output.push("Done uploading to S3!");
done(err);
}, output => this.output.push(output));
});
}
async.series(tasks, (err) => {
if (!err){
this.setStatus(statusCodes.COMPLETED);
finished();
}else{
this.setStatus(statusCodes.FAILED);
finished(err);
}
});
};
if (this.status.code === statusCodes.QUEUED){
this.startTrackingProcessingTime();
this.setStatus(statusCodes.RUNNING);
let runnerOptions = this.options.reduce((result, opt) => {
result[opt.name] = opt.value;
return result;
}, {});
runnerOptions["project-path"] = fs.realpathSync(Directories.data);
if (this.gcpFiles.length > 0){
runnerOptions.gcp = fs.realpathSync(path.join(this.getGcpFolderPath(), this.gcpFiles[0]));
}
this.runningProcesses.push(odmRunner.run(runnerOptions, this.uuid, (err, code, signal) => {
if (err){
this.setStatus(statusCodes.FAILED, {errorMessage: `Could not start process (${err.message})`});
finished(err);
}else{
// Don't evaluate if we caused the process to exit via SIGINT?
if (this.status.code !== statusCodes.CANCELED){
if (code === 0){
postProcess();
}else{
this.setStatus(statusCodes.FAILED, {errorMessage: `Process exited with code ${code}`});
finished();
}
}else{
finished();
}
}
}, output => {
// Replace console colors
output = output.replace(/\x1b\[[0-9;]*m/g, "");
// Split lines and trim
output.trim().split('\n').forEach(line => {
this.output.push(line.trim());
});
})
);
return true;
}else{
return false;
}
}
// Re-executes the task (by setting it's state back to QUEUED)
// Only tasks that have been canceled, completed or have failed can be restarted.
restart(options, cb){
if ([statusCodes.CANCELED, statusCodes.FAILED, statusCodes.COMPLETED].indexOf(this.status.code) !== -1){
this.setStatus(statusCodes.QUEUED);
this.dateCreated = new Date().getTime();
this.output = [];
this.stopTrackingProcessingTime(true);
if (options !== undefined) this.options = options;
cb(null);
}else{
cb(new Error("Task cannot be restarted"));
}
}
// Returns the description of the task.
getInfo(){
return {
uuid: this.uuid,
name: this.name,
dateCreated: this.dateCreated,
processingTime: this.processingTime,
status: this.status,
options: this.options,
imagesCount: this.images.length
};
}
// Returns the output of the OpenDroneMap process
// Optionally starting from a certain line number
getOutput(startFromLine = 0){
return this.output.slice(startFromLine, this.output.length);
}
// Reads the contents of the tasks's
// images.json and returns its JSON representation
readImagesDatabase(callback){
const imagesDbPath = !config.test ?
path.join(this.getProjectFolderPath(), 'images.json') :
path.join('tests', 'processing_results', 'images.json');
fs.readFile(imagesDbPath, 'utf8', (err, data) => {
if (err) callback(err);
else{
try{
const json = JSON.parse(data);
callback(null, json);
}catch(e){
callback(e);
}
}
});
}
callWebhooks(){
// Hooks can be passed via command line
// or for each individual task
const hooks = [this.webhook, config.webhook];
this.readImagesDatabase((err, images) => {
if (err) logger.warn(err); // Continue with callback
if (!images) images = [];
let json = this.getInfo();
json.images = images;
hooks.forEach(hook => {
if (hook && hook.length > 3){
const notifyCallback = (attempt) => {
if (attempt > 5){
logger.warn(`Webhook invokation failed, will not retry: ${hook}`);
return;
}
request.post(hook, { json },
(error, response) => {
if (error || response.statusCode != 200){
logger.warn(`Webhook invokation failed, will retry in a bit: ${hook}`);
setTimeout(() => {
notifyCallback(attempt + 1);
}, attempt * 5000);
}else{
logger.debug(`Webhook invoked: ${hook}`);
}
});
};
notifyCallback(0);
}
});
});
}
// Returns the data necessary to serialize this
// task to restore it later.
serialize(){
return {
uuid: this.uuid,
name: this.name,
dateCreated: this.dateCreated,
status: this.status,
options: this.options,
webhook: this.webhook,
skipPostProcessing: !!this.skipPostProcessing,
outputs: this.outputs || []
};
}
};<|fim▁end|> | 'odm_georeferencing', 'odm_texturing', |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast;
use codemap::{BytePos, CharPos, CodeMap, Pos, Span};
use codemap;
use diagnostic::SpanHandler;
use ext::tt::transcribe::tt_next_token;
use parse::token;
use parse::token::str_to_ident;
use std::borrow::{IntoCow, Cow};
use std::char;
use std::fmt;
use std::mem::replace;
use std::rc::Rc;
pub use ext::tt::transcribe::{TtReader, new_tt_reader, new_tt_reader_with_doc_flag};
pub mod comments;
pub trait Reader {
fn is_eof(&self) -> bool;
fn next_token(&mut self) -> TokenAndSpan;
/// Report a fatal error with the current span.
fn fatal(&self, &str) -> !;
/// Report a non-fatal error with the current span.
fn err(&self, &str);
fn peek(&self) -> TokenAndSpan;
/// Get a token the parser cares about.
fn real_token(&mut self) -> TokenAndSpan {
let mut t = self.next_token();
loop {
match t.tok {
token::Whitespace | token::Comment | token::Shebang(_) => {
t = self.next_token();
},
_ => break
}
}
t
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct TokenAndSpan {
pub tok: token::Token,
pub sp: Span,
}
pub struct StringReader<'a> {
pub span_diagnostic: &'a SpanHandler,
/// The absolute offset within the codemap of the next character to read
pub pos: BytePos,
/// The absolute offset within the codemap of the last character read(curr)
pub last_pos: BytePos,
/// The column of the next character to read
pub col: CharPos,
/// The last character to be read
pub curr: Option<char>,
pub filemap: Rc<codemap::FileMap>,
/* cached: */
pub peek_tok: token::Token,
pub peek_span: Span,
// FIXME (Issue #16472): This field should go away after ToToken impls
// are revised to go directly to token-trees.
/// Is \x00<name>,<ctxt>\x00 is interpreted as encoded ast::Ident?
read_embedded_ident: bool,
// cache a direct reference to the source text, so that we don't have to
// retrieve it via `self.filemap.src.as_ref().unwrap()` all the time.
source_text: Rc<String>
}
impl<'a> Reader for StringReader<'a> {
fn is_eof(&self) -> bool { self.curr.is_none() }
/// Return the next token. EFFECT: advances the string_reader.
fn next_token(&mut self) -> TokenAndSpan {
let ret_val = TokenAndSpan {
tok: replace(&mut self.peek_tok, token::Underscore),
sp: self.peek_span,
};
self.advance_token();
ret_val
}
fn fatal(&self, m: &str) -> ! {
self.fatal_span(self.peek_span, m)
}
fn err(&self, m: &str) {
self.err_span(self.peek_span, m)
}
fn peek(&self) -> TokenAndSpan {
// FIXME(pcwalton): Bad copy!
TokenAndSpan {
tok: self.peek_tok.clone(),
sp: self.peek_span,
}
}
}
impl<'a> Reader for TtReader<'a> {
fn is_eof(&self) -> bool {
self.cur_tok == token::Eof
}
fn next_token(&mut self) -> TokenAndSpan {
let r = tt_next_token(self);
debug!("TtReader: r={:?}", r);
r
}
fn fatal(&self, m: &str) -> ! {
self.sp_diag.span_fatal(self.cur_span, m);
}
fn err(&self, m: &str) {
self.sp_diag.span_err(self.cur_span, m);
}
fn peek(&self) -> TokenAndSpan {<|fim▁hole|> tok: self.cur_tok.clone(),
sp: self.cur_span,
}
}
}
// FIXME (Issue #16472): This function should go away after
// ToToken impls are revised to go directly to token-trees.
pub fn make_reader_with_embedded_idents<'b>(span_diagnostic: &'b SpanHandler,
filemap: Rc<codemap::FileMap>)
-> StringReader<'b> {
let mut sr = StringReader::new_raw(span_diagnostic, filemap);
sr.read_embedded_ident = true;
sr.advance_token();
sr
}
impl<'a> StringReader<'a> {
/// For comments.rs, which hackily pokes into pos and curr
pub fn new_raw<'b>(span_diagnostic: &'b SpanHandler,
filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
if filemap.src.is_none() {
span_diagnostic.handler.bug(&format!("Cannot lex filemap without source: {}",
filemap.name)[..]);
}
let source_text = (*filemap.src.as_ref().unwrap()).clone();
let mut sr = StringReader {
span_diagnostic: span_diagnostic,
pos: filemap.start_pos,
last_pos: filemap.start_pos,
col: CharPos(0),
curr: Some('\n'),
filemap: filemap,
/* dummy values; not read */
peek_tok: token::Eof,
peek_span: codemap::DUMMY_SP,
read_embedded_ident: false,
source_text: source_text
};
sr.bump();
sr
}
pub fn new<'b>(span_diagnostic: &'b SpanHandler,
filemap: Rc<codemap::FileMap>) -> StringReader<'b> {
let mut sr = StringReader::new_raw(span_diagnostic, filemap);
sr.advance_token();
sr
}
pub fn curr_is(&self, c: char) -> bool {
self.curr == Some(c)
}
/// Report a fatal lexical error with a given span.
pub fn fatal_span(&self, sp: Span, m: &str) -> ! {
self.span_diagnostic.span_fatal(sp, m)
}
/// Report a lexical error with a given span.
pub fn err_span(&self, sp: Span, m: &str) {
self.span_diagnostic.span_err(sp, m)
}
/// Report a fatal error spanning [`from_pos`, `to_pos`).
fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> ! {
self.fatal_span(codemap::mk_sp(from_pos, to_pos), m)
}
/// Report a lexical error spanning [`from_pos`, `to_pos`).
fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) {
self.err_span(codemap::mk_sp(from_pos, to_pos), m)
}
/// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
/// escaped character to the error message
fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> ! {
let mut m = m.to_string();
m.push_str(": ");
for c in c.escape_default() { m.push(c) }
self.fatal_span_(from_pos, to_pos, &m[..]);
}
/// Report a lexical error spanning [`from_pos`, `to_pos`), appending an
/// escaped character to the error message
fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) {
let mut m = m.to_string();
m.push_str(": ");
for c in c.escape_default() { m.push(c) }
self.err_span_(from_pos, to_pos, &m[..]);
}
/// Report a lexical error spanning [`from_pos`, `to_pos`), appending the
/// offending string to the error message
fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> ! {
m.push_str(": ");
let from = self.byte_offset(from_pos).to_usize();
let to = self.byte_offset(to_pos).to_usize();
m.push_str(&self.source_text[from..to]);
self.fatal_span_(from_pos, to_pos, &m[..]);
}
/// Advance peek_tok and peek_span to refer to the next token, and
/// possibly update the interner.
fn advance_token(&mut self) {
match self.scan_whitespace_or_comment() {
Some(comment) => {
self.peek_span = comment.sp;
self.peek_tok = comment.tok;
},
None => {
if self.is_eof() {
self.peek_tok = token::Eof;
} else {
let start_bytepos = self.last_pos;
self.peek_tok = self.next_token_inner();
self.peek_span = codemap::mk_sp(start_bytepos,
self.last_pos);
};
}
}
}
fn byte_offset(&self, pos: BytePos) -> BytePos {
(pos - self.filemap.start_pos)
}
/// Calls `f` with a string slice of the source text spanning from `start`
/// up to but excluding `self.last_pos`, meaning the slice does not include
/// the character `self.curr`.
pub fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T where
F: FnOnce(&str) -> T,
{
self.with_str_from_to(start, self.last_pos, f)
}
/// Create a Name from a given offset to the current offset, each
/// adjusted 1 towards each other (assumes that on either side there is a
/// single-byte delimiter).
pub fn name_from(&self, start: BytePos) -> ast::Name {
debug!("taking an ident from {:?} to {:?}", start, self.last_pos);
self.with_str_from(start, token::intern)
}
/// As name_from, with an explicit endpoint.
pub fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name {
debug!("taking an ident from {:?} to {:?}", start, end);
self.with_str_from_to(start, end, token::intern)
}
/// Calls `f` with a string slice of the source text spanning from `start`
/// up to but excluding `end`.
fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T where
F: FnOnce(&str) -> T,
{
f(&self.source_text[self.byte_offset(start).to_usize()..
self.byte_offset(end).to_usize()])
}
/// Converts CRLF to LF in the given string, raising an error on bare CR.
fn translate_crlf<'b>(&self, start: BytePos,
s: &'b str, errmsg: &'b str) -> Cow<'b, str> {
let mut i = 0;
while i < s.len() {
let ch = s.char_at(i);
let next = i + ch.len_utf8();
if ch == '\r' {
if next < s.len() && s.char_at(next) == '\n' {
return translate_crlf_(self, start, s, errmsg, i).into_cow();
}
let pos = start + BytePos(i as u32);
let end_pos = start + BytePos(next as u32);
self.err_span_(pos, end_pos, errmsg);
}
i = next;
}
return s.into_cow();
fn translate_crlf_(rdr: &StringReader, start: BytePos,
s: &str, errmsg: &str, mut i: usize) -> String {
let mut buf = String::with_capacity(s.len());
let mut j = 0;
while i < s.len() {
let ch = s.char_at(i);
let next = i + ch.len_utf8();
if ch == '\r' {
if j < i { buf.push_str(&s[j..i]); }
j = next;
if next >= s.len() || s.char_at(next) != '\n' {
let pos = start + BytePos(i as u32);
let end_pos = start + BytePos(next as u32);
rdr.err_span_(pos, end_pos, errmsg);
}
}
i = next;
}
if j < s.len() { buf.push_str(&s[j..]); }
buf
}
}
/// Advance the StringReader by one character. If a newline is
/// discovered, add it to the FileMap's list of line start offsets.
pub fn bump(&mut self) {
self.last_pos = self.pos;
let current_byte_offset = self.byte_offset(self.pos).to_usize();
if current_byte_offset < self.source_text.len() {
assert!(self.curr.is_some());
let last_char = self.curr.unwrap();
let ch = self.source_text.char_at(current_byte_offset);
let next = current_byte_offset + ch.len_utf8();
let byte_offset_diff = next - current_byte_offset;
self.pos = self.pos + Pos::from_usize(byte_offset_diff);
self.curr = Some(ch);
self.col = self.col + CharPos(1);
if last_char == '\n' {
self.filemap.next_line(self.last_pos);
self.col = CharPos(0);
}
if byte_offset_diff > 1 {
self.filemap.record_multibyte_char(self.last_pos, byte_offset_diff);
}
} else {
self.curr = None;
}
}
pub fn nextch(&self) -> Option<char> {
let offset = self.byte_offset(self.pos).to_usize();
if offset < self.source_text.len() {
Some(self.source_text.char_at(offset))
} else {
None
}
}
pub fn nextch_is(&self, c: char) -> bool {
self.nextch() == Some(c)
}
pub fn nextnextch(&self) -> Option<char> {
let offset = self.byte_offset(self.pos).to_usize();
let s = &self.source_text[..];
if offset >= s.len() { return None }
let next = offset + s.char_at(offset).len_utf8();
if next < s.len() {
Some(s.char_at(next))
} else {
None
}
}
pub fn nextnextch_is(&self, c: char) -> bool {
self.nextnextch() == Some(c)
}
/// Eats <XID_start><XID_continue>*, if possible.
fn scan_optional_raw_name(&mut self) -> Option<ast::Name> {
if !ident_start(self.curr) {
return None
}
let start = self.last_pos;
while ident_continue(self.curr) {
self.bump();
}
self.with_str_from(start, |string| {
if string == "_" {
None
} else {
Some(token::intern(string))
}
})
}
/// PRECONDITION: self.curr is not whitespace
/// Eats any kind of comment.
fn scan_comment(&mut self) -> Option<TokenAndSpan> {
match self.curr {
Some(c) => {
if c.is_whitespace() {
self.span_diagnostic.span_err(codemap::mk_sp(self.last_pos, self.last_pos),
"called consume_any_line_comment, but there was whitespace");
}
},
None => { }
}
if self.curr_is('/') {
match self.nextch() {
Some('/') => {
self.bump();
self.bump();
// line comments starting with "///" or "//!" are doc-comments
if self.curr_is('/') || self.curr_is('!') {
let start_bpos = self.pos - BytePos(3);
while !self.is_eof() {
match self.curr.unwrap() {
'\n' => break,
'\r' => {
if self.nextch_is('\n') {
// CRLF
break
} else {
self.err_span_(self.last_pos, self.pos,
"bare CR not allowed in doc-comment");
}
}
_ => ()
}
self.bump();
}
return self.with_str_from(start_bpos, |string| {
// but comments with only more "/"s are not
let tok = if is_doc_comment(string) {
token::DocComment(token::intern(string))
} else {
token::Comment
};
return Some(TokenAndSpan{
tok: tok,
sp: codemap::mk_sp(start_bpos, self.last_pos)
});
});
} else {
let start_bpos = self.last_pos - BytePos(2);
while !self.curr_is('\n') && !self.is_eof() { self.bump(); }
return Some(TokenAndSpan {
tok: token::Comment,
sp: codemap::mk_sp(start_bpos, self.last_pos)
});
}
}
Some('*') => {
self.bump(); self.bump();
self.scan_block_comment()
}
_ => None
}
} else if self.curr_is('#') {
if self.nextch_is('!') {
// Parse an inner attribute.
if self.nextnextch_is('[') {
return None;
}
// I guess this is the only way to figure out if
// we're at the beginning of the file...
let cmap = CodeMap::new();
cmap.files.borrow_mut().push(self.filemap.clone());
let loc = cmap.lookup_char_pos_adj(self.last_pos);
debug!("Skipping a shebang");
if loc.line == 1 && loc.col == CharPos(0) {
// FIXME: Add shebang "token", return it
let start = self.last_pos;
while !self.curr_is('\n') && !self.is_eof() { self.bump(); }
return Some(TokenAndSpan {
tok: token::Shebang(self.name_from(start)),
sp: codemap::mk_sp(start, self.last_pos)
});
}
}
None
} else {
None
}
}
/// If there is whitespace, shebang, or a comment, scan it. Otherwise,
/// return None.
fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> {
match self.curr.unwrap_or('\0') {
// # to handle shebang at start of file -- this is the entry point
// for skipping over all "junk"
'/' | '#' => {
let c = self.scan_comment();
debug!("scanning a comment {:?}", c);
c
},
c if is_whitespace(Some(c)) => {
let start_bpos = self.last_pos;
while is_whitespace(self.curr) { self.bump(); }
let c = Some(TokenAndSpan {
tok: token::Whitespace,
sp: codemap::mk_sp(start_bpos, self.last_pos)
});
debug!("scanning whitespace: {:?}", c);
c
},
_ => None
}
}
/// Might return a sugared-doc-attr
fn scan_block_comment(&mut self) -> Option<TokenAndSpan> {
// block comments starting with "/**" or "/*!" are doc-comments
let is_doc_comment = self.curr_is('*') || self.curr_is('!');
let start_bpos = self.last_pos - BytePos(2);
let mut level: isize = 1;
let mut has_cr = false;
while level > 0 {
if self.is_eof() {
let msg = if is_doc_comment {
"unterminated block doc-comment"
} else {
"unterminated block comment"
};
let last_bpos = self.last_pos;
self.fatal_span_(start_bpos, last_bpos, msg);
}
let n = self.curr.unwrap();
match n {
'/' if self.nextch_is('*') => {
level += 1;
self.bump();
}
'*' if self.nextch_is('/') => {
level -= 1;
self.bump();
}
'\r' => {
has_cr = true;
}
_ => ()
}
self.bump();
}
self.with_str_from(start_bpos, |string| {
// but comments with only "*"s between two "/"s are not
let tok = if is_block_doc_comment(string) {
let string = if has_cr {
self.translate_crlf(start_bpos, string,
"bare CR not allowed in block doc-comment")
} else { string.into_cow() };
token::DocComment(token::intern(&string[..]))
} else {
token::Comment
};
Some(TokenAndSpan{
tok: tok,
sp: codemap::mk_sp(start_bpos, self.last_pos)
})
})
}
// FIXME (Issue #16472): The scan_embedded_hygienic_ident function
// should go away after we revise the syntax::ext::quote::ToToken
// impls to go directly to token-trees instead of thing -> string
// -> token-trees. (The function is currently used to resolve
// Issues #15750 and #15962.)
//
// Since this function is only used for certain internal macros,
// and the functionality it provides is not exposed to end user
// programs, pnkfelix deliberately chose to write it in a way that
// favors rustc debugging effectiveness over runtime efficiency.
/// Scan through input of form \x00name_NNNNNN,ctxt_CCCCCCC\x00
/// whence: `NNNNNN` is a string of characters forming an integer
/// (the name) and `CCCCCCC` is a string of characters forming an
/// integer (the ctxt), separate by a comma and delimited by a
/// `\x00` marker.
#[inline(never)]
fn scan_embedded_hygienic_ident(&mut self) -> ast::Ident {
fn bump_expecting_char<'a,D:fmt::Debug>(r: &mut StringReader<'a>,
c: char,
described_c: D,
whence: &str) {
match r.curr {
Some(r_c) if r_c == c => r.bump(),
Some(r_c) => panic!("expected {:?}, hit {:?}, {}", described_c, r_c, whence),
None => panic!("expected {:?}, hit EOF, {}", described_c, whence),
}
}
let whence = "while scanning embedded hygienic ident";
// skip over the leading `\x00`
bump_expecting_char(self, '\x00', "nul-byte", whence);
// skip over the "name_"
for c in "name_".chars() {
bump_expecting_char(self, c, c, whence);
}
let start_bpos = self.last_pos;
let base = 10;
// find the integer representing the name
self.scan_digits(base, base);
let encoded_name : u32 = self.with_str_from(start_bpos, |s| {
u32::from_str_radix(s, 10).unwrap_or_else(|_| {
panic!("expected digits representing a name, got {:?}, {}, range [{:?},{:?}]",
s, whence, start_bpos, self.last_pos);
})
});
// skip over the `,`
bump_expecting_char(self, ',', "comma", whence);
// skip over the "ctxt_"
for c in "ctxt_".chars() {
bump_expecting_char(self, c, c, whence);
}
// find the integer representing the ctxt
let start_bpos = self.last_pos;
self.scan_digits(base, base);
let encoded_ctxt : ast::SyntaxContext = self.with_str_from(start_bpos, |s| {
u32::from_str_radix(s, 10).unwrap_or_else(|_| {
panic!("expected digits representing a ctxt, got {:?}, {}", s, whence);
})
});
// skip over the `\x00`
bump_expecting_char(self, '\x00', "nul-byte", whence);
ast::Ident { name: ast::Name(encoded_name),
ctxt: encoded_ctxt, }
}
/// Scan through any digits (base `scan_radix`) or underscores,
/// and return how many digits there were.
///
/// `real_radix` represents the true radix of the number we're
/// interested in, and errors will be emitted for any digits
/// between `real_radix` and `scan_radix`.
fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize {
assert!(real_radix <= scan_radix);
let mut len = 0;
loop {
let c = self.curr;
if c == Some('_') { debug!("skipping a _"); self.bump(); continue; }
match c.and_then(|cc| cc.to_digit(scan_radix)) {
Some(_) => {
debug!("{:?} in scan_digits", c);
// check that the hypothetical digit is actually
// in range for the true radix
if c.unwrap().to_digit(real_radix).is_none() {
self.err_span_(self.last_pos, self.pos,
&format!("invalid digit for a base {} literal",
real_radix));
}
len += 1;
self.bump();
}
_ => return len
}
};
}
/// Lex a LIT_INTEGER or a LIT_FLOAT
fn scan_number(&mut self, c: char) -> token::Lit {
let mut num_digits;
let mut base = 10;
let start_bpos = self.last_pos;
self.bump();
if c == '0' {
match self.curr.unwrap_or('\0') {
'b' => { self.bump(); base = 2; num_digits = self.scan_digits(2, 10); }
'o' => { self.bump(); base = 8; num_digits = self.scan_digits(8, 10); }
'x' => { self.bump(); base = 16; num_digits = self.scan_digits(16, 16); }
'0'...'9' | '_' | '.' => {
num_digits = self.scan_digits(10, 10) + 1;
}
_ => {
// just a 0
return token::Integer(self.name_from(start_bpos));
}
}
} else if c.is_digit(10) {
num_digits = self.scan_digits(10, 10) + 1;
} else {
num_digits = 0;
}
if num_digits == 0 {
self.err_span_(start_bpos, self.last_pos, "no valid digits found for number");
return token::Integer(token::intern("0"));
}
// might be a float, but don't be greedy if this is actually an
// integer literal followed by field/method access or a range pattern
// (`0..2` and `12.foo()`)
if self.curr_is('.') && !self.nextch_is('.') && !self.nextch().unwrap_or('\0')
.is_xid_start() {
// might have stuff after the ., and if it does, it needs to start
// with a number
self.bump();
if self.curr.unwrap_or('\0').is_digit(10) {
self.scan_digits(10, 10);
self.scan_float_exponent();
}
let last_pos = self.last_pos;
self.check_float_base(start_bpos, last_pos, base);
return token::Float(self.name_from(start_bpos));
} else {
// it might be a float if it has an exponent
if self.curr_is('e') || self.curr_is('E') {
self.scan_float_exponent();
let last_pos = self.last_pos;
self.check_float_base(start_bpos, last_pos, base);
return token::Float(self.name_from(start_bpos));
}
// but we certainly have an integer!
return token::Integer(self.name_from(start_bpos));
}
}
/// Scan over `n_digits` hex digits, stopping at `delim`, reporting an
/// error if too many or too few digits are encountered.
fn scan_hex_digits(&mut self,
n_digits: usize,
delim: char,
below_0x7f_only: bool)
-> bool {
debug!("scanning {} digits until {:?}", n_digits, delim);
let start_bpos = self.last_pos;
let mut accum_int = 0;
let mut valid = true;
for _ in 0..n_digits {
if self.is_eof() {
let last_bpos = self.last_pos;
self.fatal_span_(start_bpos, last_bpos, "unterminated numeric character escape");
}
if self.curr_is(delim) {
let last_bpos = self.last_pos;
self.err_span_(start_bpos, last_bpos, "numeric character escape is too short");
valid = false;
break;
}
let c = self.curr.unwrap_or('\x00');
accum_int *= 16;
accum_int += c.to_digit(16).unwrap_or_else(|| {
self.err_span_char(self.last_pos, self.pos,
"illegal character in numeric character escape", c);
valid = false;
0
});
self.bump();
}
if below_0x7f_only && accum_int >= 0x80 {
self.err_span_(start_bpos,
self.last_pos,
"this form of character escape may only be used \
with characters in the range [\\x00-\\x7f]");
valid = false;
}
match char::from_u32(accum_int) {
Some(_) => valid,
None => {
let last_bpos = self.last_pos;
self.err_span_(start_bpos, last_bpos, "illegal numeric character escape");
false
}
}
}
/// Scan for a single (possibly escaped) byte or char
/// in a byte, (non-raw) byte string, char, or (non-raw) string literal.
/// `start` is the position of `first_source_char`, which is already consumed.
///
/// Returns true if there was a valid char/byte, false otherwise.
fn scan_char_or_byte(&mut self, start: BytePos, first_source_char: char,
ascii_only: bool, delim: char) -> bool {
match first_source_char {
'\\' => {
// '\X' for some X must be a character constant:
let escaped = self.curr;
let escaped_pos = self.last_pos;
self.bump();
match escaped {
None => {}, // EOF here is an error that will be checked later.
Some(e) => {
return match e {
'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true,
'x' => self.scan_byte_escape(delim, !ascii_only),
'u' if self.curr_is('{') => {
let valid = self.scan_unicode_escape(delim);
if valid && ascii_only {
self.err_span_(
escaped_pos,
self.last_pos,
"unicode escape sequences cannot be used as a byte or in \
a byte string"
);
false
} else {
valid
}
}
'\n' if delim == '"' => {
self.consume_whitespace();
true
},
'\r' if delim == '"' && self.curr_is('\n') => {
self.consume_whitespace();
true
}
c => {
let last_pos = self.last_pos;
self.err_span_char(
escaped_pos, last_pos,
if ascii_only { "unknown byte escape" }
else { "unknown character escape" },
c);
if e == '\r' {
let sp = codemap::mk_sp(escaped_pos, last_pos);
self.span_diagnostic.span_help(
sp,
"this is an isolated carriage return; consider checking \
your editor and version control settings")
}
false
}
}
}
}
}
'\t' | '\n' | '\r' | '\'' if delim == '\'' => {
let last_pos = self.last_pos;
self.err_span_char(
start, last_pos,
if ascii_only { "byte constant must be escaped" }
else { "character constant must be escaped" },
first_source_char);
return false;
}
'\r' => {
if self.curr_is('\n') {
self.bump();
return true;
} else {
self.err_span_(start, self.last_pos,
"bare CR not allowed in string, use \\r instead");
return false;
}
}
_ => if ascii_only && first_source_char > '\x7F' {
let last_pos = self.last_pos;
self.err_span_char(
start, last_pos,
"byte constant must be ASCII. \
Use a \\xHH escape for a non-ASCII byte", first_source_char);
return false;
}
}
true
}
/// Scan over a \u{...} escape
///
/// At this point, we have already seen the \ and the u, the { is the current character. We
/// will read at least one digit, and up to 6, and pass over the }.
fn scan_unicode_escape(&mut self, delim: char) -> bool {
self.bump(); // past the {
let start_bpos = self.last_pos;
let mut count = 0;
let mut accum_int = 0;
let mut valid = true;
while !self.curr_is('}') && count <= 6 {
let c = match self.curr {
Some(c) => c,
None => {
self.fatal_span_(start_bpos, self.last_pos,
"unterminated unicode escape (found EOF)");
}
};
accum_int *= 16;
accum_int += c.to_digit(16).unwrap_or_else(|| {
if c == delim {
self.fatal_span_(self.last_pos, self.pos,
"unterminated unicode escape (needed a `}`)");
} else {
self.err_span_char(self.last_pos, self.pos,
"illegal character in unicode escape", c);
}
valid = false;
0
});
self.bump();
count += 1;
}
if count > 6 {
self.err_span_(start_bpos, self.last_pos,
"overlong unicode escape (can have at most 6 hex digits)");
valid = false;
}
self.bump(); // past the ending }
if valid && (char::from_u32(accum_int).is_none() || count == 0) {
self.err_span_(start_bpos, self.last_pos, "illegal unicode character escape");
valid= false;
}
valid
}
/// Scan over a float exponent.
fn scan_float_exponent(&mut self) {
if self.curr_is('e') || self.curr_is('E') {
self.bump();
if self.curr_is('-') || self.curr_is('+') {
self.bump();
}
if self.scan_digits(10, 10) == 0 {
self.err_span_(self.last_pos, self.pos, "expected at least one digit in exponent")
}
}
}
/// Check that a base is valid for a floating literal, emitting a nice
/// error if it isn't.
fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) {
match base {
16 => self.err_span_(start_bpos, last_bpos, "hexadecimal float literal is not \
supported"),
8 => self.err_span_(start_bpos, last_bpos, "octal float literal is not supported"),
2 => self.err_span_(start_bpos, last_bpos, "binary float literal is not supported"),
_ => ()
}
}
fn binop(&mut self, op: token::BinOpToken) -> token::Token {
self.bump();
if self.curr_is('=') {
self.bump();
return token::BinOpEq(op);
} else {
return token::BinOp(op);
}
}
/// Return the next token from the string, advances the input past that
/// token, and updates the interner
fn next_token_inner(&mut self) -> token::Token {
let c = self.curr;
if ident_start(c) && match (c.unwrap(), self.nextch(), self.nextnextch()) {
// Note: r as in r" or r#" is part of a raw string literal,
// b as in b' is part of a byte literal.
// They are not identifiers, and are handled further down.
('r', Some('"'), _) | ('r', Some('#'), _) |
('b', Some('"'), _) | ('b', Some('\''), _) |
('b', Some('r'), Some('"')) | ('b', Some('r'), Some('#')) => false,
_ => true
} {
let start = self.last_pos;
while ident_continue(self.curr) {
self.bump();
}
return self.with_str_from(start, |string| {
if string == "_" {
token::Underscore
} else {
// FIXME: perform NFKC normalization here. (Issue #2253)
if self.curr_is(':') && self.nextch_is(':') {
token::Ident(str_to_ident(string), token::ModName)
} else {
token::Ident(str_to_ident(string), token::Plain)
}
}
});
}
if is_dec_digit(c) {
let num = self.scan_number(c.unwrap());
let suffix = self.scan_optional_raw_name();
debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix);
return token::Literal(num, suffix)
}
if self.read_embedded_ident {
match (c.unwrap(), self.nextch(), self.nextnextch()) {
('\x00', Some('n'), Some('a')) => {
let ast_ident = self.scan_embedded_hygienic_ident();
return if self.curr_is(':') && self.nextch_is(':') {
token::Ident(ast_ident, token::ModName)
} else {
token::Ident(ast_ident, token::Plain)
};
}
_ => {}
}
}
match c.expect("next_token_inner called at EOF") {
// One-byte tokens.
';' => { self.bump(); return token::Semi; }
',' => { self.bump(); return token::Comma; }
'.' => {
self.bump();
return if self.curr_is('.') {
self.bump();
if self.curr_is('.') {
self.bump();
token::DotDotDot
} else {
token::DotDot
}
} else {
token::Dot
};
}
'(' => { self.bump(); return token::OpenDelim(token::Paren); }
')' => { self.bump(); return token::CloseDelim(token::Paren); }
'{' => { self.bump(); return token::OpenDelim(token::Brace); }
'}' => { self.bump(); return token::CloseDelim(token::Brace); }
'[' => { self.bump(); return token::OpenDelim(token::Bracket); }
']' => { self.bump(); return token::CloseDelim(token::Bracket); }
'@' => { self.bump(); return token::At; }
'#' => { self.bump(); return token::Pound; }
'~' => { self.bump(); return token::Tilde; }
'?' => { self.bump(); return token::Question; }
':' => {
self.bump();
if self.curr_is(':') {
self.bump();
return token::ModSep;
} else {
return token::Colon;
}
}
'$' => { self.bump(); return token::Dollar; }
// Multi-byte tokens.
'=' => {
self.bump();
if self.curr_is('=') {
self.bump();
return token::EqEq;
} else if self.curr_is('>') {
self.bump();
return token::FatArrow;
} else {
return token::Eq;
}
}
'!' => {
self.bump();
if self.curr_is('=') {
self.bump();
return token::Ne;
} else { return token::Not; }
}
'<' => {
self.bump();
match self.curr.unwrap_or('\x00') {
'=' => { self.bump(); return token::Le; }
'<' => { return self.binop(token::Shl); }
'-' => {
self.bump();
match self.curr.unwrap_or('\x00') {
_ => { return token::LArrow; }
}
}
_ => { return token::Lt; }
}
}
'>' => {
self.bump();
match self.curr.unwrap_or('\x00') {
'=' => { self.bump(); return token::Ge; }
'>' => { return self.binop(token::Shr); }
_ => { return token::Gt; }
}
}
'\'' => {
// Either a character constant 'a' OR a lifetime name 'abc
self.bump();
let start = self.last_pos;
// the eof will be picked up by the final `'` check below
let c2 = self.curr.unwrap_or('\x00');
self.bump();
// If the character is an ident start not followed by another single
// quote, then this is a lifetime name:
if ident_start(Some(c2)) && !self.curr_is('\'') {
while ident_continue(self.curr) {
self.bump();
}
// Include the leading `'` in the real identifier, for macro
// expansion purposes. See #12512 for the gory details of why
// this is necessary.
let ident = self.with_str_from(start, |lifetime_name| {
str_to_ident(&format!("'{}", lifetime_name))
});
// Conjure up a "keyword checking ident" to make sure that
// the lifetime name is not a keyword.
let keyword_checking_ident =
self.with_str_from(start, |lifetime_name| {
str_to_ident(lifetime_name)
});
let keyword_checking_token =
&token::Ident(keyword_checking_ident, token::Plain);
let last_bpos = self.last_pos;
if keyword_checking_token.is_keyword(token::keywords::SelfValue) {
self.err_span_(start,
last_bpos,
"invalid lifetime name: 'self \
is no longer a special lifetime");
} else if keyword_checking_token.is_any_keyword() &&
!keyword_checking_token.is_keyword(token::keywords::Static)
{
self.err_span_(start,
last_bpos,
"invalid lifetime name");
}
return token::Lifetime(ident);
}
// Otherwise it is a character constant:
let valid = self.scan_char_or_byte(start, c2, /* ascii_only = */ false, '\'');
if !self.curr_is('\'') {
let last_bpos = self.last_pos;
self.fatal_span_verbose(
// Byte offsetting here is okay because the
// character before position `start` is an
// ascii single quote.
start - BytePos(1), last_bpos,
"unterminated character constant".to_string());
}
let id = if valid { self.name_from(start) } else { token::intern("0") };
self.bump(); // advance curr past token
let suffix = self.scan_optional_raw_name();
return token::Literal(token::Char(id), suffix);
}
'b' => {
self.bump();
let lit = match self.curr {
Some('\'') => self.scan_byte(),
Some('"') => self.scan_byte_string(),
Some('r') => self.scan_raw_byte_string(),
_ => unreachable!() // Should have been a token::Ident above.
};
let suffix = self.scan_optional_raw_name();
return token::Literal(lit, suffix);
}
'"' => {
let start_bpos = self.last_pos;
let mut valid = true;
self.bump();
while !self.curr_is('"') {
if self.is_eof() {
let last_bpos = self.last_pos;
self.fatal_span_(start_bpos, last_bpos, "unterminated double quote string");
}
let ch_start = self.last_pos;
let ch = self.curr.unwrap();
self.bump();
valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only = */ false, '"');
}
// adjust for the ASCII " at the start of the literal
let id = if valid { self.name_from(start_bpos + BytePos(1)) }
else { token::intern("??") };
self.bump();
let suffix = self.scan_optional_raw_name();
return token::Literal(token::Str_(id), suffix);
}
'r' => {
let start_bpos = self.last_pos;
self.bump();
let mut hash_count = 0;
while self.curr_is('#') {
self.bump();
hash_count += 1;
}
if self.is_eof() {
let last_bpos = self.last_pos;
self.fatal_span_(start_bpos, last_bpos, "unterminated raw string");
} else if !self.curr_is('"') {
let last_bpos = self.last_pos;
let curr_char = self.curr.unwrap();
self.fatal_span_char(start_bpos, last_bpos,
"only `#` is allowed in raw string delimitation; \
found illegal character",
curr_char);
}
self.bump();
let content_start_bpos = self.last_pos;
let mut content_end_bpos;
let mut valid = true;
'outer: loop {
if self.is_eof() {
let last_bpos = self.last_pos;
self.fatal_span_(start_bpos, last_bpos, "unterminated raw string");
}
//if self.curr_is('"') {
//content_end_bpos = self.last_pos;
//for _ in 0..hash_count {
//self.bump();
//if !self.curr_is('#') {
//continue 'outer;
let c = self.curr.unwrap();
match c {
'"' => {
content_end_bpos = self.last_pos;
for _ in 0..hash_count {
self.bump();
if !self.curr_is('#') {
continue 'outer;
}
}
break;
},
'\r' => {
if !self.nextch_is('\n') {
let last_bpos = self.last_pos;
self.err_span_(start_bpos, last_bpos, "bare CR not allowed in raw \
string, use \\r instead");
valid = false;
}
}
_ => ()
}
self.bump();
}
self.bump();
let id = if valid {
self.name_from_to(content_start_bpos, content_end_bpos)
} else {
token::intern("??")
};
let suffix = self.scan_optional_raw_name();
return token::Literal(token::StrRaw(id, hash_count), suffix);
}
'-' => {
if self.nextch_is('>') {
self.bump();
self.bump();
return token::RArrow;
} else { return self.binop(token::Minus); }
}
'&' => {
if self.nextch_is('&') {
self.bump();
self.bump();
return token::AndAnd;
} else { return self.binop(token::And); }
}
'|' => {
match self.nextch() {
Some('|') => { self.bump(); self.bump(); return token::OrOr; }
_ => { return self.binop(token::Or); }
}
}
'+' => { return self.binop(token::Plus); }
'*' => { return self.binop(token::Star); }
'/' => { return self.binop(token::Slash); }
'^' => { return self.binop(token::Caret); }
'%' => { return self.binop(token::Percent); }
c => {
let last_bpos = self.last_pos;
let bpos = self.pos;
self.fatal_span_char(last_bpos, bpos, "unknown start of token", c);
}
}
}
fn consume_whitespace(&mut self) {
while is_whitespace(self.curr) && !self.is_eof() { self.bump(); }
}
fn read_to_eol(&mut self) -> String {
let mut val = String::new();
while !self.curr_is('\n') && !self.is_eof() {
val.push(self.curr.unwrap());
self.bump();
}
if self.curr_is('\n') { self.bump(); }
return val
}
fn read_one_line_comment(&mut self) -> String {
let val = self.read_to_eol();
assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/')
|| (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!'));
return val;
}
fn consume_non_eol_whitespace(&mut self) {
while is_whitespace(self.curr) && !self.curr_is('\n') && !self.is_eof() {
self.bump();
}
}
fn peeking_at_comment(&self) -> bool {
(self.curr_is('/') && self.nextch_is('/'))
|| (self.curr_is('/') && self.nextch_is('*'))
// consider shebangs comments, but not inner attributes
|| (self.curr_is('#') && self.nextch_is('!') && !self.nextnextch_is('['))
}
fn scan_byte(&mut self) -> token::Lit {
self.bump();
let start = self.last_pos;
// the eof will be picked up by the final `'` check below
let c2 = self.curr.unwrap_or('\x00');
self.bump();
let valid = self.scan_char_or_byte(start, c2, /* ascii_only = */ true, '\'');
if !self.curr_is('\'') {
// Byte offsetting here is okay because the
// character before position `start` are an
// ascii single quote and ascii 'b'.
let last_pos = self.last_pos;
self.fatal_span_verbose(
start - BytePos(2), last_pos,
"unterminated byte constant".to_string());
}
let id = if valid { self.name_from(start) } else { token::intern("?") };
self.bump(); // advance curr past token
return token::Byte(id);
}
fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool {
self.scan_hex_digits(2, delim, below_0x7f_only)
}
fn scan_byte_string(&mut self) -> token::Lit {
self.bump();
let start = self.last_pos;
let mut valid = true;
while !self.curr_is('"') {
if self.is_eof() {
let last_pos = self.last_pos;
self.fatal_span_(start, last_pos,
"unterminated double quote byte string");
}
let ch_start = self.last_pos;
let ch = self.curr.unwrap();
self.bump();
valid &= self.scan_char_or_byte(ch_start, ch, /* ascii_only = */ true, '"');
}
let id = if valid { self.name_from(start) } else { token::intern("??") };
self.bump();
return token::Binary(id);
}
fn scan_raw_byte_string(&mut self) -> token::Lit {
let start_bpos = self.last_pos;
self.bump();
let mut hash_count = 0;
while self.curr_is('#') {
self.bump();
hash_count += 1;
}
if self.is_eof() {
let last_pos = self.last_pos;
self.fatal_span_(start_bpos, last_pos, "unterminated raw string");
} else if !self.curr_is('"') {
let last_pos = self.last_pos;
let ch = self.curr.unwrap();
self.fatal_span_char(start_bpos, last_pos,
"only `#` is allowed in raw string delimitation; \
found illegal character",
ch);
}
self.bump();
let content_start_bpos = self.last_pos;
let mut content_end_bpos;
'outer: loop {
match self.curr {
None => {
let last_pos = self.last_pos;
self.fatal_span_(start_bpos, last_pos, "unterminated raw string")
},
Some('"') => {
content_end_bpos = self.last_pos;
for _ in 0..hash_count {
self.bump();
if !self.curr_is('#') {
continue 'outer;
}
}
break;
},
Some(c) => if c > '\x7F' {
let last_pos = self.last_pos;
self.err_span_char(
last_pos, last_pos, "raw byte string must be ASCII", c);
}
}
self.bump();
}
self.bump();
return token::BinaryRaw(self.name_from_to(content_start_bpos,
content_end_bpos),
hash_count);
}
}
pub fn is_whitespace(c: Option<char>) -> bool {
match c.unwrap_or('\x00') { // None can be null for now... it's not whitespace
' ' | '\n' | '\t' | '\r' => true,
_ => false
}
}
fn in_range(c: Option<char>, lo: char, hi: char) -> bool {
match c {
Some(c) => lo <= c && c <= hi,
_ => false
}
}
fn is_dec_digit(c: Option<char>) -> bool { return in_range(c, '0', '9'); }
pub fn is_doc_comment(s: &str) -> bool {
let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/')
|| s.starts_with("//!");
debug!("is {:?} a doc comment? {}", s, res);
res
}
pub fn is_block_doc_comment(s: &str) -> bool {
let res = (s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*')
|| s.starts_with("/*!");
debug!("is {:?} a doc comment? {}", s, res);
res
}
fn ident_start(c: Option<char>) -> bool {
let c = match c { Some(c) => c, None => return false };
(c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| c == '_'
|| (c > '\x7f' && c.is_xid_start())
}
fn ident_continue(c: Option<char>) -> bool {
let c = match c { Some(c) => c, None => return false };
(c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == '_'
|| (c > '\x7f' && c.is_xid_continue())
}
#[cfg(test)]
mod test {
use super::*;
use codemap::{BytePos, CodeMap, Span, NO_EXPANSION};
use diagnostic;
use parse::token;
use parse::token::{str_to_ident};
use std::io;
fn mk_sh() -> diagnostic::SpanHandler {
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let emitter = diagnostic::EmitterWriter::new(Box::new(io::sink()), None);
let handler = diagnostic::mk_handler(true, Box::new(emitter));
diagnostic::mk_span_handler(handler, CodeMap::new())
}
// open a string reader for the given string
fn setup<'a>(span_handler: &'a diagnostic::SpanHandler,
teststr: String) -> StringReader<'a> {
let fm = span_handler.cm.new_filemap("zebra.rs".to_string(), teststr);
StringReader::new(span_handler, fm)
}
#[test] fn t1 () {
let span_handler = mk_sh();
let mut string_reader = setup(&span_handler,
"/* my source file */ \
fn main() { println!(\"zebra\"); }\n".to_string());
let id = str_to_ident("fn");
assert_eq!(string_reader.next_token().tok, token::Comment);
assert_eq!(string_reader.next_token().tok, token::Whitespace);
let tok1 = string_reader.next_token();
let tok2 = TokenAndSpan{
tok:token::Ident(id, token::Plain),
sp:Span {lo:BytePos(21),hi:BytePos(23),expn_id: NO_EXPANSION}};
assert_eq!(tok1,tok2);
assert_eq!(string_reader.next_token().tok, token::Whitespace);
// the 'main' id is already read:
assert_eq!(string_reader.last_pos.clone(), BytePos(28));
// read another token:
let tok3 = string_reader.next_token();
let tok4 = TokenAndSpan{
tok:token::Ident(str_to_ident("main"), token::Plain),
sp:Span {lo:BytePos(24),hi:BytePos(28),expn_id: NO_EXPANSION}};
assert_eq!(tok3,tok4);
// the lparen is already read:
assert_eq!(string_reader.last_pos.clone(), BytePos(29))
}
// check that the given reader produces the desired stream
// of tokens (stop checking after exhausting the expected vec)
fn check_tokenization (mut string_reader: StringReader, expected: Vec<token::Token> ) {
for expected_tok in &expected {
assert_eq!(&string_reader.next_token().tok, expected_tok);
}
}
// make the identifier by looking up the string in the interner
fn mk_ident(id: &str, style: token::IdentStyle) -> token::Token {
token::Ident(str_to_ident(id), style)
}
#[test] fn doublecolonparsing () {
check_tokenization(setup(&mk_sh(), "a b".to_string()),
vec![mk_ident("a", token::Plain),
token::Whitespace,
mk_ident("b", token::Plain)]);
}
#[test] fn dcparsing_2 () {
check_tokenization(setup(&mk_sh(), "a::b".to_string()),
vec![mk_ident("a",token::ModName),
token::ModSep,
mk_ident("b", token::Plain)]);
}
#[test] fn dcparsing_3 () {
check_tokenization(setup(&mk_sh(), "a ::b".to_string()),
vec![mk_ident("a", token::Plain),
token::Whitespace,
token::ModSep,
mk_ident("b", token::Plain)]);
}
#[test] fn dcparsing_4 () {
check_tokenization(setup(&mk_sh(), "a:: b".to_string()),
vec![mk_ident("a",token::ModName),
token::ModSep,
token::Whitespace,
mk_ident("b", token::Plain)]);
}
#[test] fn character_a() {
assert_eq!(setup(&mk_sh(), "'a'".to_string()).next_token().tok,
token::Literal(token::Char(token::intern("a")), None));
}
#[test] fn character_space() {
assert_eq!(setup(&mk_sh(), "' '".to_string()).next_token().tok,
token::Literal(token::Char(token::intern(" ")), None));
}
#[test] fn character_escaped() {
assert_eq!(setup(&mk_sh(), "'\\n'".to_string()).next_token().tok,
token::Literal(token::Char(token::intern("\\n")), None));
}
#[test] fn lifetime_name() {
assert_eq!(setup(&mk_sh(), "'abc".to_string()).next_token().tok,
token::Lifetime(token::str_to_ident("'abc")));
}
#[test] fn raw_string() {
assert_eq!(setup(&mk_sh(),
"r###\"\"#a\\b\x00c\"\"###".to_string()).next_token()
.tok,
token::Literal(token::StrRaw(token::intern("\"#a\\b\x00c\""), 3), None));
}
#[test] fn literal_suffixes() {
macro_rules! test {
($input: expr, $tok_type: ident, $tok_contents: expr) => {{
assert_eq!(setup(&mk_sh(), format!("{}suffix", $input)).next_token().tok,
token::Literal(token::$tok_type(token::intern($tok_contents)),
Some(token::intern("suffix"))));
// with a whitespace separator:
assert_eq!(setup(&mk_sh(), format!("{} suffix", $input)).next_token().tok,
token::Literal(token::$tok_type(token::intern($tok_contents)),
None));
}}
}
test!("'a'", Char, "a");
test!("b'a'", Byte, "a");
test!("\"a\"", Str_, "a");
test!("b\"a\"", Binary, "a");
test!("1234", Integer, "1234");
test!("0b101", Integer, "0b101");
test!("0xABC", Integer, "0xABC");
test!("1.0", Float, "1.0");
test!("1.0e10", Float, "1.0e10");
assert_eq!(setup(&mk_sh(), "2us".to_string()).next_token().tok,
token::Literal(token::Integer(token::intern("2")),
Some(token::intern("us"))));
assert_eq!(setup(&mk_sh(), "r###\"raw\"###suffix".to_string()).next_token().tok,
token::Literal(token::StrRaw(token::intern("raw"), 3),
Some(token::intern("suffix"))));
assert_eq!(setup(&mk_sh(), "br###\"raw\"###suffix".to_string()).next_token().tok,
token::Literal(token::BinaryRaw(token::intern("raw"), 3),
Some(token::intern("suffix"))));
}
#[test] fn line_doc_comments() {
assert!(is_doc_comment("///"));
assert!(is_doc_comment("/// blah"));
assert!(!is_doc_comment("////"));
}
#[test] fn nested_block_comments() {
let sh = mk_sh();
let mut lexer = setup(&sh, "/* /* */ */'a'".to_string());
match lexer.next_token().tok {
token::Comment => { },
_ => panic!("expected a comment!")
}
assert_eq!(lexer.next_token().tok, token::Literal(token::Char(token::intern("a")), None));
}
}<|fim▁end|> | TokenAndSpan { |
<|file_name|>HTMLUnescape.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
###############################################################################
#
# HTMLUnescape
# Replaces character entity names in the specified text with equivalent HTML markup characters.
#
# 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.
#
#<|fim▁hole|>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 HTMLUnescape(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the HTMLUnescape Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(HTMLUnescape, self).__init__(temboo_session, '/Library/Utilities/Encoding/HTMLUnescape')
def new_input_set(self):
return HTMLUnescapeInputSet()
def _make_result_set(self, result, path):
return HTMLUnescapeResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return HTMLUnescapeChoreographyExecution(session, exec_id, path)
class HTMLUnescapeInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the HTMLUnescape
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_EscapedHTML(self, value):
"""
Set the value of the EscapedHTML input for this Choreo. ((required, string) The escaped HTML that should be unescaped.)
"""
super(HTMLUnescapeInputSet, self)._set_input('EscapedHTML', value)
class HTMLUnescapeResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the HTMLUnescape Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_UnescapedHTML(self):
"""
Retrieve the value for the "UnescapedHTML" output from this Choreo execution. ((string) The unescaped HTML.)
"""
return self._output.get('UnescapedHTML', None)
class HTMLUnescapeChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return HTMLUnescapeResultSet(response, path)<|fim▁end|> | ###############################################################################
|
<|file_name|>feerate.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <policy/feerate.h>
#include <tinyformat.h>
const std::string CURRENCY_UNIT = "UFO";
CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nBytes_)
{
assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max()));
int64_t nSize = int64_t(nBytes_);
<|fim▁hole|> nSatoshisPerK = 0;
}
CAmount CFeeRate::GetFee(size_t nBytes_) const
{
assert(nBytes_ <= uint64_t(std::numeric_limits<int64_t>::max()));
int64_t nSize = int64_t(nBytes_);
CAmount nFee = nSatoshisPerK * nSize / 1000;
if (nFee == 0 && nSize != 0) {
if (nSatoshisPerK > 0)
nFee = CAmount(1);
if (nSatoshisPerK < 0)
nFee = CAmount(-1);
}
return nFee;
}
std::string CFeeRate::ToString() const
{
return strprintf("%d.%08d %s/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN, CURRENCY_UNIT);
}<|fim▁end|> | if (nSize > 0)
nSatoshisPerK = nFeePaid * 1000 / nSize;
else |
<|file_name|>h.js<|end_file_name|><|fim▁begin|><|fim▁hole|>// FILE H TWO
module.exports = 2<|fim▁end|> | |
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):<|fim▁hole|>
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),
('name', models.CharField(max_length=255, verbose_name='Category Name')),
('description', models.TextField(null=True)),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='PropertyName',
fields=[
('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),
('name', models.CharField(max_length=255, verbose_name='Property Name')),
('description', models.TextField(null=True)),
('category', models.ForeignKey(to='category.Category')),
],
options={
},
bases=(models.Model,),
),
]<|fim▁end|> | |
<|file_name|>el.js<|end_file_name|><|fim▁begin|>(function ($) {
$.Redactor.opts.langs['el'] = {
html: 'HTML',
video: 'Εισαγωγή βίντεο...',
image: 'Εισαγωγή εικόνας...',
table: 'Πίνακας',
link: 'Σύνδεσμος',
link_insert: 'Εισαγωγή συνδέσμου...',
link_edit: 'Edit link',
unlink: 'Ακύρωση συνδέσμου',
formatting: 'Μορφοποίηση',
paragraph: 'Παράγραφος',
quote: 'Παράθεση',
code: 'Κώδικας',
header1: 'Κεφαλίδα 1',
header2: 'Κεφαλίδα 2',
header3: 'Κεφαλίδα 3',
header4: 'Κεφαλίδα 4',
bold: 'Έντονα',
italic: 'Πλάγια',
fontcolor: 'Χρώμα γραμματοσειράς',
backcolor: 'Χρώμα επισήμανσης κειμένου',
unorderedlist: 'Κουκκίδες',
orderedlist: 'Αρίθμηση',
outdent: 'Μείωση εσοχής',
indent: 'Αύξηση εσοχής',
cancel: 'Ακύρωση',
insert: 'Εισαγωγή',
save: 'Αποθήκευση',
_delete: 'Διαγραφή',
insert_table: 'Εισαγωγή πίνακα...',
insert_row_above: 'Προσθήκη σειράς επάνω',
insert_row_below: 'Προσθήκη σειράς κάτω',
insert_column_left: 'Προσθήκη στήλης αριστερά',
insert_column_right: 'Προσθήκη στήλης δεξιά',
delete_column: 'Διαγραφή στήλης',
delete_row: 'Διαγραφή σειράς',
delete_table: 'Διαγραφή πίνακα',
rows: 'Γραμμές',
columns: 'Στήλες',
add_head: 'Προσθήκη κεφαλίδας',
delete_head: 'Διαγραφή κεφαλίδας',
title: 'Τίτλος',
image_position: 'Θέση',
none: 'Καμία',
left: 'Αριστερά',
right: 'Δεξιά',
image_web_link: 'Υπερσύνδεσμος εικόνας',
text: 'Κείμενο',
mailto: 'Email',
web: 'URL',
video_html_code: 'Video Embed Code',
file: 'Εισαγωγή αρχείου...',
upload: 'Upload',
download: 'Download',<|fim▁hole|> choose: 'Επέλεξε',
or_choose: 'ή επέλεξε',
drop_file_here: 'Σύρατε αρχεία εδώ',
align_left: 'Στοίχιση αριστερά',
align_center: 'Στοίχιση στο κέντρο',
align_right: 'Στοίχιση δεξιά',
align_justify: 'Πλήρησ στοίχηση',
horizontalrule: 'Εισαγωγή οριζόντιας γραμμής',
deleted: 'Διαγράφτηκε',
anchor: 'Anchor',
link_new_tab: 'Open link in new tab',
underline: 'Underline',
alignment: 'Alignment',
filename: 'Name (optional)',
edit: 'Edit'
};
})( jQuery );<|fim▁end|> | |
<|file_name|>package-info.java<|end_file_name|><|fim▁begin|>/**<|fim▁hole|> *@author dgagarsky
*@since 01.12.2016
*/
package ru.job4j;<|fim▁end|> | * For JavaDocs. |
<|file_name|>data.py<|end_file_name|><|fim▁begin|>from unicodecsv import DictReader
class CSVImporter(object):
""" A CSV-backed resource with the datas in it. """
def __init__(self, fh):
self.reader = DictReader(fh)
self.data = list(self.reader)
@property
def headers(self):
headers = set()
for row in self.data:
headers = headers.union(row.keys())
return headers<|fim▁hole|>
def __iter__(self):
return self.data.__iter__()<|fim▁end|> |
def __len__(self):
return len(self.data) |
<|file_name|>sequences.py<|end_file_name|><|fim▁begin|>from __future__ import print_function, division
from sympy.core.basic import Basic
from sympy.core.mul import Mul
from sympy.core.singleton import S, Singleton
from sympy.core.symbol import Dummy, Symbol
from sympy.core.compatibility import (range, integer_types, with_metaclass,
is_sequence, iterable, ordered)
from sympy.core.decorators import call_highest_priority
from sympy.core.cache import cacheit
from sympy.core.sympify import sympify
from sympy.core.containers import Tuple
from sympy.core.evaluate import global_evaluate
from sympy.polys import lcm, factor
from sympy.sets.sets import Interval, Intersection
from sympy.utilities.iterables import flatten
from sympy.tensor.indexed import Idx
from sympy.simplify import simplify
from sympy import expand
###############################################################################
# SEQUENCES #
###############################################################################
class SeqBase(Basic):
"""Base class for sequences"""
is_commutative = True
_op_priority = 15
@staticmethod
def _start_key(expr):
"""Return start (if possible) else S.Infinity.
adapted from Set._infimum_key
"""
try:
start = expr.start
except (NotImplementedError,
AttributeError, ValueError):
start = S.Infinity
return start
def _intersect_interval(self, other):
"""Returns start and stop.
Takes intersection over the two intervals.
"""
interval = Intersection(self.interval, other.interval)
return interval.inf, interval.sup
@property
def gen(self):
"""Returns the generator for the sequence"""
raise NotImplementedError("(%s).gen" % self)
@property
def interval(self):
"""The interval on which the sequence is defined"""
raise NotImplementedError("(%s).interval" % self)
@property
def start(self):
"""The starting point of the sequence. This point is included"""
raise NotImplementedError("(%s).start" % self)
@property
def stop(self):
"""The ending point of the sequence. This point is included"""
raise NotImplementedError("(%s).stop" % self)
@property
def length(self):
"""Length of the sequence"""
raise NotImplementedError("(%s).length" % self)
@property
def variables(self):
"""Returns a tuple of variables that are bounded"""
return ()
@property
def free_symbols(self):
"""
This method returns the symbols in the object, excluding those
that take on a specific value (i.e. the dummy symbols).
Examples
========
>>> from sympy import SeqFormula
>>> from sympy.abc import n, m
>>> SeqFormula(m*n**2, (n, 0, 5)).free_symbols
{m}
"""
return (set(j for i in self.args for j in i.free_symbols
.difference(self.variables)))
@cacheit
def coeff(self, pt):
"""Returns the coefficient at point pt"""
if pt < self.start or pt > self.stop:
raise IndexError("Index %s out of bounds %s" % (pt, self.interval))
return self._eval_coeff(pt)
def _eval_coeff(self, pt):
raise NotImplementedError("The _eval_coeff method should be added to"
"%s to return coefficient so it is available"
"when coeff calls it."
% self.func)
def _ith_point(self, i):
"""Returns the i'th point of a sequence.
If start point is negative infinity, point is returned from the end.
Assumes the first point to be indexed zero.
Examples
=========
>>> from sympy import oo
>>> from sympy.series.sequences import SeqPer
bounded
>>> SeqPer((1, 2, 3), (-10, 10))._ith_point(0)
-10
>>> SeqPer((1, 2, 3), (-10, 10))._ith_point(5)
-5
End is at infinity
>>> SeqPer((1, 2, 3), (0, oo))._ith_point(5)
5
Starts at negative infinity
>>> SeqPer((1, 2, 3), (-oo, 0))._ith_point(5)
-5
"""
if self.start is S.NegativeInfinity:
initial = self.stop
else:
initial = self.start
if self.start is S.NegativeInfinity:
step = -1
else:
step = 1
return initial + i*step
def _add(self, other):
"""
Should only be used internally.
self._add(other) returns a new, term-wise added sequence if self
knows how to add with other, otherwise it returns ``None``.
``other`` should only be a sequence object.
Used within :class:`SeqAdd` class.
"""
return None
def _mul(self, other):
"""
Should only be used internally.
self._mul(other) returns a new, term-wise multiplied sequence if self
knows how to multiply with other, otherwise it returns ``None``.
``other`` should only be a sequence object.
Used within :class:`SeqMul` class.
"""<|fim▁hole|> return None
def coeff_mul(self, other):
"""
Should be used when ``other`` is not a sequence. Should be
defined to define custom behaviour.
Examples
========
>>> from sympy import S, oo, SeqFormula
>>> from sympy.abc import n
>>> SeqFormula(n**2).coeff_mul(2)
SeqFormula(2*n**2, (n, 0, oo))
Notes
=====
'*' defines multiplication of sequences with sequences only.
"""
return Mul(self, other)
def __add__(self, other):
"""Returns the term-wise addition of 'self' and 'other'.
``other`` should be a sequence.
Examples
========
>>> from sympy import S, oo, SeqFormula
>>> from sympy.abc import n
>>> SeqFormula(n**2) + SeqFormula(n**3)
SeqFormula(n**3 + n**2, (n, 0, oo))
"""
if not isinstance(other, SeqBase):
raise TypeError('cannot add sequence and %s' % type(other))
return SeqAdd(self, other)
@call_highest_priority('__add__')
def __radd__(self, other):
return self + other
def __sub__(self, other):
"""Returns the term-wise subtraction of 'self' and 'other'.
``other`` should be a sequence.
Examples
========
>>> from sympy import S, oo, SeqFormula
>>> from sympy.abc import n
>>> SeqFormula(n**2) - (SeqFormula(n))
SeqFormula(n**2 - n, (n, 0, oo))
"""
if not isinstance(other, SeqBase):
raise TypeError('cannot subtract sequence and %s' % type(other))
return SeqAdd(self, -other)
@call_highest_priority('__sub__')
def __rsub__(self, other):
return (-self) + other
def __neg__(self):
"""Negates the sequence.
Examples
========
>>> from sympy import S, oo, SeqFormula
>>> from sympy.abc import n
>>> -SeqFormula(n**2)
SeqFormula(-n**2, (n, 0, oo))
"""
return self.coeff_mul(-1)
def __mul__(self, other):
"""Returns the term-wise multiplication of 'self' and 'other'.
``other`` should be a sequence. For ``other`` not being a
sequence see :func:`coeff_mul` method.
Examples
========
>>> from sympy import S, oo, SeqFormula
>>> from sympy.abc import n
>>> SeqFormula(n**2) * (SeqFormula(n))
SeqFormula(n**3, (n, 0, oo))
"""
if not isinstance(other, SeqBase):
raise TypeError('cannot multiply sequence and %s' % type(other))
return SeqMul(self, other)
@call_highest_priority('__mul__')
def __rmul__(self, other):
return self * other
def __iter__(self):
for i in range(self.length):
pt = self._ith_point(i)
yield self.coeff(pt)
def __getitem__(self, index):
if isinstance(index, integer_types):
index = self._ith_point(index)
return self.coeff(index)
elif isinstance(index, slice):
start, stop = index.start, index.stop
if start is None:
start = 0
if stop is None:
stop = self.length
return [self.coeff(self._ith_point(i)) for i in
range(start, stop, index.step or 1)]
def find_linear_recurrence(self,n,d=None,gfvar=None):
r"""
Finds the shortest linear recurrence that satisfies the first n
terms of sequence of order `\leq` n/2 if possible.
If d is specified, find shortest linear recurrence of order
`\leq` min(d, n/2) if possible.
Returns list of coefficients ``[b(1), b(2), ...]`` corresponding to the
recurrence relation ``x(n) = b(1)*x(n-1) + b(2)*x(n-2) + ...``
Returns ``[]`` if no recurrence is found.
If gfvar is specified, also returns ordinary generating function as a
function of gfvar.
Examples
========
>>> from sympy import sequence, sqrt, oo, lucas
>>> from sympy.abc import n, x, y
>>> sequence(n**2).find_linear_recurrence(10, 2)
[]
>>> sequence(n**2).find_linear_recurrence(10)
[3, -3, 1]
>>> sequence(2**n).find_linear_recurrence(10)
[2]
>>> sequence(23*n**4+91*n**2).find_linear_recurrence(10)
[5, -10, 10, -5, 1]
>>> sequence(sqrt(5)*(((1 + sqrt(5))/2)**n - (-(1 + sqrt(5))/2)**(-n))/5).find_linear_recurrence(10)
[1, 1]
>>> sequence(x+y*(-2)**(-n), (n, 0, oo)).find_linear_recurrence(30)
[1/2, 1/2]
>>> sequence(3*5**n + 12).find_linear_recurrence(20,gfvar=x)
([6, -5], 3*(-21*x + 5)/((x - 1)*(5*x - 1)))
>>> sequence(lucas(n)).find_linear_recurrence(15,gfvar=x)
([1, 1], (x - 2)/(x**2 + x - 1))
"""
from sympy.matrices import Matrix
x = [simplify(expand(t)) for t in self[:n]]
lx = len(x)
if d == None:
r = lx//2
else:
r = min(d,lx//2)
coeffs = []
for l in range(1, r+1):
l2 = 2*l
mlist = []
for k in range(l):
mlist.append(x[k:k+l])
m = Matrix(mlist)
if m.det() != 0:
y = simplify(m.LUsolve(Matrix(x[l:l2])))
if lx == l2:
coeffs = flatten(y[::-1])
break
mlist = []
for k in range(l,lx-l):
mlist.append(x[k:k+l])
m = Matrix(mlist)
if m*y == Matrix(x[l2:]):
coeffs = flatten(y[::-1])
break
if gfvar == None:
return coeffs
else:
l = len(coeffs)
if l == 0:
return [], None
else:
n, d = x[l-1]*gfvar**(l-1), 1 - coeffs[l-1]*gfvar**l
for i in range(l-1):
n += x[i]*gfvar**i
for j in range(l-i-1):
n -= coeffs[i]*x[j]*gfvar**(i+j+1)
d -= coeffs[i]*gfvar**(i+1)
return coeffs, simplify(factor(n)/factor(d))
class EmptySequence(with_metaclass(Singleton, SeqBase)):
"""Represents an empty sequence.
The empty sequence is available as a
singleton as ``S.EmptySequence``.
Examples
========
>>> from sympy import S, SeqPer, oo
>>> from sympy.abc import x
>>> S.EmptySequence
EmptySequence()
>>> SeqPer((1, 2), (x, 0, 10)) + S.EmptySequence
SeqPer((1, 2), (x, 0, 10))
>>> SeqPer((1, 2)) * S.EmptySequence
EmptySequence()
>>> S.EmptySequence.coeff_mul(-1)
EmptySequence()
"""
@property
def interval(self):
return S.EmptySet
@property
def length(self):
return S.Zero
def coeff_mul(self, coeff):
"""See docstring of SeqBase.coeff_mul"""
return self
def __iter__(self):
return iter([])
class SeqExpr(SeqBase):
"""Sequence expression class.
Various sequences should inherit from this class.
Examples
========
>>> from sympy.series.sequences import SeqExpr
>>> from sympy.abc import x
>>> s = SeqExpr((1, 2, 3), (x, 0, 10))
>>> s.gen
(1, 2, 3)
>>> s.interval
Interval(0, 10)
>>> s.length
11
See Also
========
sympy.series.sequences.SeqPer
sympy.series.sequences.SeqFormula
"""
@property
def gen(self):
return self.args[0]
@property
def interval(self):
return Interval(self.args[1][1], self.args[1][2])
@property
def start(self):
return self.interval.inf
@property
def stop(self):
return self.interval.sup
@property
def length(self):
return self.stop - self.start + 1
@property
def variables(self):
return (self.args[1][0],)
class SeqPer(SeqExpr):
"""Represents a periodic sequence.
The elements are repeated after a given period.
Examples
========
>>> from sympy import SeqPer, oo
>>> from sympy.abc import k
>>> s = SeqPer((1, 2, 3), (0, 5))
>>> s.periodical
(1, 2, 3)
>>> s.period
3
For value at a particular point
>>> s.coeff(3)
1
supports slicing
>>> s[:]
[1, 2, 3, 1, 2, 3]
iterable
>>> list(s)
[1, 2, 3, 1, 2, 3]
sequence starts from negative infinity
>>> SeqPer((1, 2, 3), (-oo, 0))[0:6]
[1, 2, 3, 1, 2, 3]
Periodic formulas
>>> SeqPer((k, k**2, k**3), (k, 0, oo))[0:6]
[0, 1, 8, 3, 16, 125]
See Also
========
sympy.series.sequences.SeqFormula
"""
def __new__(cls, periodical, limits=None):
periodical = sympify(periodical)
def _find_x(periodical):
free = periodical.free_symbols
if len(periodical.free_symbols) == 1:
return free.pop()
else:
return Dummy('k')
x, start, stop = None, None, None
if limits is None:
x, start, stop = _find_x(periodical), 0, S.Infinity
if is_sequence(limits, Tuple):
if len(limits) == 3:
x, start, stop = limits
elif len(limits) == 2:
x = _find_x(periodical)
start, stop = limits
if not isinstance(x, (Symbol, Idx)) or start is None or stop is None:
raise ValueError('Invalid limits given: %s' % str(limits))
if start is S.NegativeInfinity and stop is S.Infinity:
raise ValueError("Both the start and end value"
"cannot be unbounded")
limits = sympify((x, start, stop))
if is_sequence(periodical, Tuple):
periodical = sympify(tuple(flatten(periodical)))
else:
raise ValueError("invalid period %s should be something "
"like e.g (1, 2) " % periodical)
if Interval(limits[1], limits[2]) is S.EmptySet:
return S.EmptySequence
return Basic.__new__(cls, periodical, limits)
@property
def period(self):
return len(self.gen)
@property
def periodical(self):
return self.gen
def _eval_coeff(self, pt):
if self.start is S.NegativeInfinity:
idx = (self.stop - pt) % self.period
else:
idx = (pt - self.start) % self.period
return self.periodical[idx].subs(self.variables[0], pt)
def _add(self, other):
"""See docstring of SeqBase._add"""
if isinstance(other, SeqPer):
per1, lper1 = self.periodical, self.period
per2, lper2 = other.periodical, other.period
per_length = lcm(lper1, lper2)
new_per = []
for x in range(per_length):
ele1 = per1[x % lper1]
ele2 = per2[x % lper2]
new_per.append(ele1 + ele2)
start, stop = self._intersect_interval(other)
return SeqPer(new_per, (self.variables[0], start, stop))
def _mul(self, other):
"""See docstring of SeqBase._mul"""
if isinstance(other, SeqPer):
per1, lper1 = self.periodical, self.period
per2, lper2 = other.periodical, other.period
per_length = lcm(lper1, lper2)
new_per = []
for x in range(per_length):
ele1 = per1[x % lper1]
ele2 = per2[x % lper2]
new_per.append(ele1 * ele2)
start, stop = self._intersect_interval(other)
return SeqPer(new_per, (self.variables[0], start, stop))
def coeff_mul(self, coeff):
"""See docstring of SeqBase.coeff_mul"""
coeff = sympify(coeff)
per = [x * coeff for x in self.periodical]
return SeqPer(per, self.args[1])
class SeqFormula(SeqExpr):
"""Represents sequence based on a formula.
Elements are generated using a formula.
Examples
========
>>> from sympy import SeqFormula, oo, Symbol
>>> n = Symbol('n')
>>> s = SeqFormula(n**2, (n, 0, 5))
>>> s.formula
n**2
For value at a particular point
>>> s.coeff(3)
9
supports slicing
>>> s[:]
[0, 1, 4, 9, 16, 25]
iterable
>>> list(s)
[0, 1, 4, 9, 16, 25]
sequence starts from negative infinity
>>> SeqFormula(n**2, (-oo, 0))[0:6]
[0, 1, 4, 9, 16, 25]
See Also
========
sympy.series.sequences.SeqPer
"""
def __new__(cls, formula, limits=None):
formula = sympify(formula)
def _find_x(formula):
free = formula.free_symbols
if len(formula.free_symbols) == 1:
return free.pop()
elif len(formula.free_symbols) == 0:
return Dummy('k')
else:
raise ValueError(
" specify dummy variables for %s. If the formula contains"
" more than one free symbol, a dummy variable should be"
" supplied explicitly e.g., SeqFormula(m*n**2, (n, 0, 5))"
% formula)
x, start, stop = None, None, None
if limits is None:
x, start, stop = _find_x(formula), 0, S.Infinity
if is_sequence(limits, Tuple):
if len(limits) == 3:
x, start, stop = limits
elif len(limits) == 2:
x = _find_x(formula)
start, stop = limits
if not isinstance(x, (Symbol, Idx)) or start is None or stop is None:
raise ValueError('Invalid limits given: %s' % str(limits))
if start is S.NegativeInfinity and stop is S.Infinity:
raise ValueError("Both the start and end value"
"cannot be unbounded")
limits = sympify((x, start, stop))
if Interval(limits[1], limits[2]) is S.EmptySet:
return S.EmptySequence
return Basic.__new__(cls, formula, limits)
@property
def formula(self):
return self.gen
def _eval_coeff(self, pt):
d = self.variables[0]
return self.formula.subs(d, pt)
def _add(self, other):
"""See docstring of SeqBase._add"""
if isinstance(other, SeqFormula):
form1, v1 = self.formula, self.variables[0]
form2, v2 = other.formula, other.variables[0]
formula = form1 + form2.subs(v2, v1)
start, stop = self._intersect_interval(other)
return SeqFormula(formula, (v1, start, stop))
def _mul(self, other):
"""See docstring of SeqBase._mul"""
if isinstance(other, SeqFormula):
form1, v1 = self.formula, self.variables[0]
form2, v2 = other.formula, other.variables[0]
formula = form1 * form2.subs(v2, v1)
start, stop = self._intersect_interval(other)
return SeqFormula(formula, (v1, start, stop))
def coeff_mul(self, coeff):
"""See docstring of SeqBase.coeff_mul"""
coeff = sympify(coeff)
formula = self.formula * coeff
return SeqFormula(formula, self.args[1])
def sequence(seq, limits=None):
"""Returns appropriate sequence object.
If ``seq`` is a sympy sequence, returns :class:`SeqPer` object
otherwise returns :class:`SeqFormula` object.
Examples
========
>>> from sympy import sequence, SeqPer, SeqFormula
>>> from sympy.abc import n
>>> sequence(n**2, (n, 0, 5))
SeqFormula(n**2, (n, 0, 5))
>>> sequence((1, 2, 3), (n, 0, 5))
SeqPer((1, 2, 3), (n, 0, 5))
See Also
========
sympy.series.sequences.SeqPer
sympy.series.sequences.SeqFormula
"""
seq = sympify(seq)
if is_sequence(seq, Tuple):
return SeqPer(seq, limits)
else:
return SeqFormula(seq, limits)
###############################################################################
# OPERATIONS #
###############################################################################
class SeqExprOp(SeqBase):
"""Base class for operations on sequences.
Examples
========
>>> from sympy.series.sequences import SeqExprOp, sequence
>>> from sympy.abc import n
>>> s1 = sequence(n**2, (n, 0, 10))
>>> s2 = sequence((1, 2, 3), (n, 5, 10))
>>> s = SeqExprOp(s1, s2)
>>> s.gen
(n**2, (1, 2, 3))
>>> s.interval
Interval(5, 10)
>>> s.length
6
See Also
========
sympy.series.sequences.SeqAdd
sympy.series.sequences.SeqMul
"""
@property
def gen(self):
"""Generator for the sequence.
returns a tuple of generators of all the argument sequences.
"""
return tuple(a.gen for a in self.args)
@property
def interval(self):
"""Sequence is defined on the intersection
of all the intervals of respective sequences
"""
return Intersection(a.interval for a in self.args)
@property
def start(self):
return self.interval.inf
@property
def stop(self):
return self.interval.sup
@property
def variables(self):
"""Cumulative of all the bound variables"""
return tuple(flatten([a.variables for a in self.args]))
@property
def length(self):
return self.stop - self.start + 1
class SeqAdd(SeqExprOp):
"""Represents term-wise addition of sequences.
Rules:
* The interval on which sequence is defined is the intersection
of respective intervals of sequences.
* Anything + :class:`EmptySequence` remains unchanged.
* Other rules are defined in ``_add`` methods of sequence classes.
Examples
========
>>> from sympy import S, oo, SeqAdd, SeqPer, SeqFormula
>>> from sympy.abc import n
>>> SeqAdd(SeqPer((1, 2), (n, 0, oo)), S.EmptySequence)
SeqPer((1, 2), (n, 0, oo))
>>> SeqAdd(SeqPer((1, 2), (n, 0, 5)), SeqPer((1, 2), (n, 6, 10)))
EmptySequence()
>>> SeqAdd(SeqPer((1, 2), (n, 0, oo)), SeqFormula(n**2, (n, 0, oo)))
SeqAdd(SeqFormula(n**2, (n, 0, oo)), SeqPer((1, 2), (n, 0, oo)))
>>> SeqAdd(SeqFormula(n**3), SeqFormula(n**2))
SeqFormula(n**3 + n**2, (n, 0, oo))
See Also
========
sympy.series.sequences.SeqMul
"""
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get('evaluate', global_evaluate[0])
# flatten inputs
args = list(args)
# adapted from sympy.sets.sets.Union
def _flatten(arg):
if isinstance(arg, SeqBase):
if isinstance(arg, SeqAdd):
return sum(map(_flatten, arg.args), [])
else:
return [arg]
if iterable(arg):
return sum(map(_flatten, arg), [])
raise TypeError("Input must be Sequences or "
" iterables of Sequences")
args = _flatten(args)
args = [a for a in args if a is not S.EmptySequence]
# Addition of no sequences is EmptySequence
if not args:
return S.EmptySequence
if Intersection(a.interval for a in args) is S.EmptySet:
return S.EmptySequence
# reduce using known rules
if evaluate:
return SeqAdd.reduce(args)
args = list(ordered(args, SeqBase._start_key))
return Basic.__new__(cls, *args)
@staticmethod
def reduce(args):
"""Simplify :class:`SeqAdd` using known rules.
Iterates through all pairs and ask the constituent
sequences if they can simplify themselves with any other constituent.
Notes
=====
adapted from ``Union.reduce``
"""
new_args = True
while(new_args):
for id1, s in enumerate(args):
new_args = False
for id2, t in enumerate(args):
if id1 == id2:
continue
new_seq = s._add(t)
# This returns None if s does not know how to add
# with t. Returns the newly added sequence otherwise
if new_seq is not None:
new_args = [a for a in args if a not in (s, t)]
new_args.append(new_seq)
break
if new_args:
args = new_args
break
if len(args) == 1:
return args.pop()
else:
return SeqAdd(args, evaluate=False)
def _eval_coeff(self, pt):
"""adds up the coefficients of all the sequences at point pt"""
return sum(a.coeff(pt) for a in self.args)
class SeqMul(SeqExprOp):
r"""Represents term-wise multiplication of sequences.
Handles multiplication of sequences only. For multiplication
with other objects see :func:`SeqBase.coeff_mul`.
Rules:
* The interval on which sequence is defined is the intersection
of respective intervals of sequences.
* Anything \* :class:`EmptySequence` returns :class:`EmptySequence`.
* Other rules are defined in ``_mul`` methods of sequence classes.
Examples
========
>>> from sympy import S, oo, SeqMul, SeqPer, SeqFormula
>>> from sympy.abc import n
>>> SeqMul(SeqPer((1, 2), (n, 0, oo)), S.EmptySequence)
EmptySequence()
>>> SeqMul(SeqPer((1, 2), (n, 0, 5)), SeqPer((1, 2), (n, 6, 10)))
EmptySequence()
>>> SeqMul(SeqPer((1, 2), (n, 0, oo)), SeqFormula(n**2))
SeqMul(SeqFormula(n**2, (n, 0, oo)), SeqPer((1, 2), (n, 0, oo)))
>>> SeqMul(SeqFormula(n**3), SeqFormula(n**2))
SeqFormula(n**5, (n, 0, oo))
See Also
========
sympy.series.sequences.SeqAdd
"""
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get('evaluate', global_evaluate[0])
# flatten inputs
args = list(args)
# adapted from sympy.sets.sets.Union
def _flatten(arg):
if isinstance(arg, SeqBase):
if isinstance(arg, SeqMul):
return sum(map(_flatten, arg.args), [])
else:
return [arg]
elif iterable(arg):
return sum(map(_flatten, arg), [])
raise TypeError("Input must be Sequences or "
" iterables of Sequences")
args = _flatten(args)
# Multiplication of no sequences is EmptySequence
if not args:
return S.EmptySequence
if Intersection(a.interval for a in args) is S.EmptySet:
return S.EmptySequence
# reduce using known rules
if evaluate:
return SeqMul.reduce(args)
args = list(ordered(args, SeqBase._start_key))
return Basic.__new__(cls, *args)
@staticmethod
def reduce(args):
"""Simplify a :class:`SeqMul` using known rules.
Iterates through all pairs and ask the constituent
sequences if they can simplify themselves with any other constituent.
Notes
=====
adapted from ``Union.reduce``
"""
new_args = True
while(new_args):
for id1, s in enumerate(args):
new_args = False
for id2, t in enumerate(args):
if id1 == id2:
continue
new_seq = s._mul(t)
# This returns None if s does not know how to multiply
# with t. Returns the newly multiplied sequence otherwise
if new_seq is not None:
new_args = [a for a in args if a not in (s, t)]
new_args.append(new_seq)
break
if new_args:
args = new_args
break
if len(args) == 1:
return args.pop()
else:
return SeqMul(args, evaluate=False)
def _eval_coeff(self, pt):
"""multiplies the coefficients of all the sequences at point pt"""
val = 1
for a in self.args:
val *= a.coeff(pt)
return val<|fim▁end|> | |
<|file_name|>functions.js<|end_file_name|><|fim▁begin|>var slidedelay = $('#bannerslider').attr('data-delay');
var pauseonhover = $('#bannerslider').attr('data-pause');
var fadedelay = 2000;
$(document).ready(function() {
if ($('#bannerslider').hasClass("slide") && $('#bannerslider').hasClass("carousel")) {
$('#bannerslider').carousel({
interval: slidedelay,
pause: '"' + pauseonhover + '"'
});
} else if ($('#bannerslider').hasClass("slide") && $('#imageContainer').children().length>1) {
$('#imageContainer').children(':first-child').addClass("showbanner");
setTimeout(nextSlide, slidedelay);
}
});
function nextSlide() {
var images = $('#imageContainer').children();
$(images).each( function(i) {
if ($(this).hasClass("showbanner")) {
$(this).fadeOut(fadedelay).removeClass("showbanner");
var nextIndex = (i == (images.length - 1)) ? 0 : i+1;
$(images[nextIndex]).fadeIn(fadedelay).addClass("showbanner");
setTimeout(nextSlide, slidedelay);
return false<|fim▁hole|> }
});
}<|fim▁end|> | |
<|file_name|>ChainPatternDemo.java<|end_file_name|><|fim▁begin|>package com.action.design.pattern.chain;
/**
* 创建不同类型的记录器。赋予它们不同的错误级别,并在每个记录器中设置下一个记录器。每个记录器中的下一个记录器代表的是链的一部分。
* Created by wuyunfeng on 2017/6/15.
*/
public class ChainPatternDemo {
private static AbstractLogger getChainOfLoggers() {
AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.ERROR);
AbstractLogger fileLogger = new FileLogger(AbstractLogger.DEBUG);
AbstractLogger consoleLogger = new ConsoleLogger(AbstractLogger.INFO);
errorLogger.setNextLogger(fileLogger);
fileLogger.setNextLogger(consoleLogger);
<|fim▁hole|>
}
public static void main(String[] args) {
AbstractLogger loggerChain = getChainOfLoggers();
loggerChain.logMessage(AbstractLogger.INFO, "This is an information.");
loggerChain.logMessage(AbstractLogger.DEBUG,
"This is an debug level information.");
loggerChain.logMessage(AbstractLogger.ERROR,
"This is an error information.");
}
}<|fim▁end|> | return errorLogger; |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>ACCOUNT_NAME = 'Bosch'<|fim▁end|> | |
<|file_name|>HowMuch.rs<|end_file_name|><|fim▁begin|>fn how_much(mut m: i32, mut n: i32) -> Vec<(String, String, String)> {
if m > n {
std::mem::swap(&mut m, &mut n);
}
let mut result: Vec<(String, String, String)> = Vec::new();
let mut c: f32;
let mut b: f32;
for i in m..n+1 {
c = (i as f32-1f32)/9f32;
b = (i as f32-2f32)/7f32;
if c < 0f32 || b < 0f32 {
continue;
}
if c.fract() == 0f32 && b.fract() == 0f32 {
let r_tuple = (format!("M: {}", i),
format!("B: {}", b as i32),
format!("C: {}", c as i32));
result.push(r_tuple);
}
}
return result;
}
fn testing(m: i32, n: i32, exp: Vec<(&str, &str, &str)>) -> () {
let ans: String = format!("{:?}", how_much(m, n));
let sol: String = format!("{:?}", exp);
assert_eq!(ans, sol)
}
fn tests() {
testing(1, 100, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11")]);
testing(1000, 1100, vec![("M: 1045", "B: 149", "C: 116")]);
testing(10000, 9950, vec![("M: 9991", "B: 1427", "C: 1110")]);
testing(0, 200, vec![("M: 37", "B: 5", "C: 4"), ("M: 100", "B: 14", "C: 11"), ("M: 163", "B: 23", "C: 18")]);
testing(2950, 2950, vec![]);
}<|fim▁hole|>fn main() {
tests();
}<|fim▁end|> | |
<|file_name|>foreign_trait.rs<|end_file_name|><|fim▁begin|>#![feature(negative_impls)]
<|fim▁hole|><|fim▁end|> | pub trait ForeignTrait {}
impl ForeignTrait for u32 {}
impl !ForeignTrait for String {} |
<|file_name|>entries.js<|end_file_name|><|fim▁begin|>"use strict";
const hamt = require('../hamt');
const assert = require('chai').assert;
describe('entries', () => {
it('should be empty for empty map', () => {
const h = hamt.make();
const it = hamt.entries(h);
let v = it.next();
assert.ok(v.done);
for (let x of h)
assert.isFalse(true);
});
it('should visit single child', () => {
const h = hamt.make().set('a', 3);
const it = hamt.entries(h);
let v = it.next();
assert.deepEqual(['a', 3], v.value);
assert.notOk(v.done);
v = it.next();
assert.ok(v.done);
assert.deepEqual([['a', 3]], Array.from(h));
});
it('should visit all children', () => {
const h = hamt.make()
.set('a', 3)
.set('b', 5)
.set('c', 7);
const expected = [['a', 3], ['b', 5], ['c', 7]];
{
const it = h.entries();
const results = [];
let v;
for (var i = 0; i < h.count(); ++i) {
v = it.next();
assert.notOk(v.done);
results.push(v.value)
}
v = it.next();
assert.isTrue(v.done);
assert.deepEqual(expected, results);
}
assert.deepEqual(expected, Array.from(h));
});
it('should handle collisions', () => {
const h = hamt.make()
.setHash(0, 'a', 3)
.setHash(0, 'b', 5)
.setHash(0, 'c', 7)
const expected = [['b', 5], ['a', 3], ['c', 7]];
{
const it = h.entries();
const results = [];
let v;
for (var i = 0; i < h.count(); ++i) {<|fim▁hole|> assert.notOk(v.done);
results.push(v.value)
}
v = it.next();
assert.isTrue(v.done);
assert.deepEqual(expected, results);
}
assert.deepEqual(expected, Array.from(h));
});
it('should handle large map correctly', () => {
let h = hamt.make();
let sum = 0;
for (let i = 0; i < 20000; ++i) {
h = h.set(i + '', i);
sum += i;
}
let foundSum = 0;
for (let x of h)
foundSum += x[1];
assert.strictEqual(sum, foundSum);
});
});<|fim▁end|> | v = it.next(); |
<|file_name|>bitcoin_eo.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="eo" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About LitecoinDark</source>
<translation>Pri LitecoinDark</translation>
</message>
<message>
<location line="+39"/>
<source><b>LitecoinDark</b> version</source>
<translation><b>LitecoinDark</b>-a versio</translation>
</message>
<message>
<location line="+57"/>
<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>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The LitecoinDark developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adresaro</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Duoble-klaku por redakti adreson aŭ etikedon</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Kreu novan adreson</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopiu elektitan adreson al la tondejo</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Nova Adreso</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your LitecoinDark 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 type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Kopiu Adreson</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a LitecoinDark address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified LitecoinDark address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Forviŝu</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your LitecoinDark addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Kopiu &Etikedon</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Redaktu</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Eksportu Adresarajn Datumojn</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Diskoma dosiero (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Eraro dum eksportado</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Ne eblis skribi al dosiero %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Etikedo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adreso</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(ne etikedo)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Enigu pasfrazon</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nova pasfrazo</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Ripetu novan pasfrazon</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<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>Enigu novan pasfrazon por la monujo.<br/>Bonvolu, uzu pasfrazon kun <b>10 aŭ pli hazardaj signoj</b>, aŭ <b>ok aŭ pli vortoj</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Ĉifru monujon</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Ĉi tiu operacio devas vian monujan pasfrazon, por malŝlosi la monujon.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Malŝlosu monujon</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Ĉi tiu operacio devas vian monujan pasfrazon, por malĉifri la monujon.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Malĉifru monujon</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Anstataŭigu pasfrazon</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Enigu la malnovan kaj novan monujan pasfrazon.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Konfirmu ĉifrado de monujo</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</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="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Monujo ĉifrita</translation>
</message>
<message>
<location line="-56"/>
<source>LitecoinDark will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your litecoindarks from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Monujo ĉifrado fiaskis</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Ĉifrado de monujo fiaskis, kaŭze de interna eraro. Via monujo ne ĉifritas.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>La pasfrazoj enigitaj ne samas.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Monujo malŝlosado fiaskis</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>La pasfrazo enigita por ĉifrado de monujo ne konformas.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Monujo malĉifrado fiaskis</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Subskribu &mesaĝon...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Sinkronigante kun reto...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Superrigardo</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transakcioj</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Esploru historion de transakcioj</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Eliru</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Eliru de aplikaĵo</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about LitecoinDark</source>
<translation>Vidigu informaĵon pri Bitmono</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Pri &QT</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Vidigu informaĵon pri Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opcioj...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Ĉifru Monujon...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Anstataŭigu pasfrazon...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a LitecoinDark address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for LitecoinDark</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<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="-4"/>
<source>&Verify message...</source>
<translation>&Kontrolu mesaĝon...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>LitecoinDark</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Monujo</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About LitecoinDark</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your LitecoinDark addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified LitecoinDark addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Dosiero</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Agordoj</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Helpo</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>LitecoinDark client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to LitecoinDark network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n horo</numerusform><numerusform>%n horoj</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n tago</numerusform><numerusform>%n tagoj</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n semajno</numerusform><numerusform>%n semajnoj</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Eraro</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<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="-140"/>
<source>Up to date</source>
<translation>Ĝisdata</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Ĝisdatigante...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Sendita transakcio</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Envenanta transakcio</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid LitecoinDark address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Monujo estas <b>ĉifrita</b> kaj nun <b>malŝlosita</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Monujo estas <b>ĉifrita</b> kaj nun <b>ŝlosita</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. LitecoinDark can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Reta Averto</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Redaktu Adreson</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etikedo</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>La etikedo interrilatita kun ĉi tiun adreso</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adreso</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="+21"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>La adreso enigita "%1" jam ekzistas en la adresaro.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid LitecoinDark address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Ne eblis malŝlosi monujon</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>LitecoinDark-Qt</source>
<translation>LitecoinDark-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versio</translation>
</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>Opcioj</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</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.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start LitecoinDark after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start LitecoinDark on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the LitecoinDark 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 LitecoinDark 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 type="unfinished"/>
</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 LitecoinDark.</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 LitecoinDark addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Nuligu</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Apliku</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<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 LitecoinDark.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the LitecoinDark network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Nekonfirmita:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Monujo</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Lastaj transakcioj</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<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 filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start litecoindark: click-to-pay handler</source>
<translation type="unfinished"/>
</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>Etikedo:</translation>
</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 type="unfinished"/>
</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="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</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>Reto</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</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>&Malfermu</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the LitecoinDark-Qt help message to get a list with possible LitecoinDark 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 type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>LitecoinDark - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>LitecoinDark 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 LitecoinDark 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="-30"/>
<source>Welcome to the LitecoinDark 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="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Sendu Monojn</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Sendu samtempe al multaj ricevantoj</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 type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123,456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> al %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Ĉu vi vere volas sendi %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>kaj</translation>
</message>
<message>
<location line="+23"/>
<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 type="unfinished"/>
</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>
</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 type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Etikedo:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Elektu adreson el adresaro</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>Algluu adreson de tondejo</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>Forigu ĉi tiun ricevanton</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a LitecoinDark address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<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. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Algluu adreson de tondejo</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="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<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 LitecoinDark address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<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. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified LitecoinDark address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a LitecoinDark address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</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 LitecoinDark signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</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><|fim▁hole|> <translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The LitecoinDark developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/nekonfirmita</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 konfirmoj</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</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></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Sumo</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ankoraŭ ne elsendita sukcese</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>nekonata</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transakciaj detaloj</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adreso</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Sumo</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Ricevita kun</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Ricevita de</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Sendita al</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pago al vi mem</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Minita</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Transakcia tipo.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Ĉiuj</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Hodiaŭ</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Ricevita kun</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Sendita al</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Al vi mem</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Minita</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopiu adreson</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Redaktu etikedon</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Diskoma dosiero (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Konfirmita</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etikedo</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adreso</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Sumo</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Eraro dum eksportado</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Ne eblis skribi al dosiero %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>LitecoinDark version</source>
<translation>LitecoinDark-a versio</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or litecoindarkd</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Listigu instrukciojn</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Opcioj:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: litecoindark.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: litecoindarkd.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=litecoindarkrpc
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 "LitecoinDark Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<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="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. LitecoinDark is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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="+4"/>
<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="+3"/>
<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>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<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="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong LitecoinDark will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<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="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<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="+2"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the LitecoinDark Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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="+5"/>
<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="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<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="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-26"/>
<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="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Ŝarĝante adresojn...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of LitecoinDark</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart LitecoinDark to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<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>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Ŝarĝante blok-indekson...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. LitecoinDark is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Ŝarĝante monujon...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Ŝarĝado finitas</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Por uzi la opcion %s</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Eraro</translation>
</message>
<message>
<location line="-31"/>
<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|> | <location line="+7"/>
<source>Message verification failed.</source> |
<|file_name|>distributedstorage_fetch_test.go<|end_file_name|><|fim▁begin|>/*
* EliasDB
*
* Copyright 2016 Matthias Ladkau. All rights reserved.
*
* 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/.
*/
package cluster
import (<|fim▁hole|> "math"
"testing"
"time"
"github.com/krotik/eliasdb/cluster/manager"
)
func TestSimpleDataReplicationFetch(t *testing.T) {
// Set a low distribution range
defaultDistributionRange = 5000
defer func() { defaultDistributionRange = math.MaxUint64 }()
// Setup a cluster
manager.FreqHousekeeping = 5
defer func() { manager.FreqHousekeeping = 1000 }()
// Log transfer worker runs
logTransferWorker = true
defer func() { logTransferWorker = false }()
// Create a cluster with 3 members and a replication factor of 2
cluster3, ms := createCluster(3, 2)
// Debug output
// manager.LogDebug = manager.LogInfo
// log.SetOutput(os.Stderr)
// defer func() { log.SetOutput(ioutil.Discard) }()
for i, dd := range cluster3 {
dd.Start()
defer dd.Close()
if i > 0 {
err := dd.MemberManager.JoinCluster(cluster3[0].MemberManager.Name(), cluster3[0].MemberManager.NetAddr())
if err != nil {
t.Error(err)
return
}
}
}
sm := cluster3[1].StorageManager("test", true)
// Insert two strings into the store
if loc, err := sm.Insert("test1"); loc != 1 || err != nil {
t.Error("Unexpected result:", loc, err)
return
}
sm.Flush()
time.Sleep(10 * time.Millisecond)
if loc, err := sm.Insert("test2"); loc != 1666 || err != nil {
t.Error("Unexpected result:", loc, err)
return
}
sm.Flush()
// Ensure the transfer worker is running on all members
for _, m := range ms {
m.transferWorker()
for m.transferRunning {
time.Sleep(time.Millisecond)
}
}
// Check that we have a certain storage layout in the cluster
if res := clusterLayout(ms, "test"); res != `
TestClusterMember-0 MemberStorageManager mgs1/ls_test
Roots: 0=0 1=0 2=0 3=0 4=0 5=0 6=0 7=0 8=0 9=0
cloc: 1 (v:1) - lloc: 1 - "\b\f\x00\x05test1"
TestClusterMember-1 MemberStorageManager mgs2/ls_test
Roots: 0=0 1=0 2=0 3=0 4=0 5=0 6=0 7=0 8=0 9=0
cloc: 1 (v:1) - lloc: 1 - "\b\f\x00\x05test1"
cloc: 1666 (v:1) - lloc: 2 - "\b\f\x00\x05test2"
TestClusterMember-2 MemberStorageManager mgs3/ls_test
Roots: 0=0 1=0 2=0 3=0 4=0 5=0 6=0 7=0 8=0 9=0
cloc: 1666 (v:1) - lloc: 1 - "\b\f\x00\x05test2"
`[1:] && res != `
TestClusterMember-0 MemberStorageManager mgs1/ls_test
Roots: 0=0 1=0 2=0 3=0 4=0 5=0 6=0 7=0 8=0 9=0
cloc: 1 (v:1) - lloc: 1 - "\b\f\x00\x05test1"
TestClusterMember-1 MemberStorageManager mgs2/ls_test
Roots: 0=0 1=0 2=0 3=0 4=0 5=0 6=0 7=0 8=0 9=0
cloc: 1666 (v:1) - lloc: 1 - "\b\f\x00\x05test2"
cloc: 1 (v:1) - lloc: 2 - "\b\f\x00\x05test1"
TestClusterMember-2 MemberStorageManager mgs3/ls_test
Roots: 0=0 1=0 2=0 3=0 4=0 5=0 6=0 7=0 8=0 9=0
cloc: 1666 (v:1) - lloc: 1 - "\b\f\x00\x05test2"
`[1:] {
t.Error("Unexpected cluster storage layout: ", res)
return
}
// Now do a normal fetch
var ret string
if err := sm.Fetch(1, &ret); err != nil || ret != "test1" {
t.Error("Unexpected result:", err, ret)
return
}
if err := sm.Fetch(1666, &ret); err != nil || ret != "test2" {
t.Error("Unexpected result:", err, ret)
return
}
// Simulate an error on member 0
manager.MemberErrors = make(map[string]error)
defer func() { manager.MemberErrors = nil }()
manager.MemberErrors[cluster3[0].MemberManager.Name()] = &testNetError{}
cluster3[0].MemberManager.StopHousekeeping = true
defer func() { cluster3[0].MemberManager.StopHousekeeping = false }()
if err := sm.Fetch(1, &ret); err != nil || ret != "test1" {
t.Error("Unexpected result:", err, ret)
return
}
if err := sm.Fetch(1666, &ret); err != nil || ret != "test2" {
t.Error("Unexpected result:", err, ret)
return
}
sm = cluster3[2].StorageManager("test", false)
if err := sm.Fetch(1, &ret); err != nil || ret != "test1" {
t.Error("Unexpected result:", err, ret)
return
}
if err := sm.Fetch(1666, &ret); err != nil || ret != "test2" {
t.Error("Unexpected result:", err, ret)
return
}
if err := sm.Fetch(1667, &ret); err.Error() !=
"ClusterError: Member error (Cluster slot not found (TestClusterMember-1 - Location: 1667))" {
t.Error("Unexpected result:", err)
return
}
}<|fim▁end|> | |
<|file_name|>fn-custom-6.rs<|end_file_name|><|fim▁begin|>// rustfmt-fn_args_layout: BlockAlways
// rustfmt-where_indent: Inherit
// rustfmt-fn_brace_style: PreferSameLine
// Test different indents.
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 {
bar();
}
fn foo(a: Aaaaaaaaaaaaaa, b: Bbbbbbbbbbbbbb) where T: UUUUUUUUUUU {
foo();
}
fn bar(a: Aaaaaaaaaaaaaa, b: Bbbbbbbbbbbbbb, c: Cccccccccccccccccc, d: Dddddddddddddddd, e: Eeeeeeeeeeeeeee) where T: UUUUUUUUUUU {
bar();
}
fn foo(a: Aaaaaaaaaaaaaa, b: Bbbbbbbbbbbbbb) -> String where T: UUUUUUUUUUU {
foo();
}
fn bar(a: Aaaaaaaaaaaaaa, b: Bbbbbbbbbbbbbb, c: Cccccccccccccccccc, d: Dddddddddddddddd, e: Eeeeeeeeeeeeeee) -> String where T: UUUUUUUUUUU {
bar();<|fim▁hole|>
fn bar(a: u8) -> String {}
}<|fim▁end|> | }
trait Test {
fn foo(a: u8) {} |
<|file_name|>interactive_interface.py<|end_file_name|><|fim▁begin|><|fim▁hole|># DBus interface for the interactive partitioning module
#
# Copyright (C) 2019 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from dasbus.server.interface import dbus_interface
from pyanaconda.modules.common.constants.objects import INTERACTIVE_PARTITIONING
from pyanaconda.modules.storage.partitioning.base_interface import PartitioningInterface
@dbus_interface(INTERACTIVE_PARTITIONING.interface_name)
class InteractivePartitioningInterface(PartitioningInterface):
"""DBus interface for the interactive partitioning module."""<|fim▁end|> | # |
<|file_name|>BindableDouble.java<|end_file_name|><|fim▁begin|>package saberapplications.pawpads.databinding;
import android.databinding.BaseObservable;
import android.databinding.BindingAdapter;
import android.databinding.BindingConversion;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import saberapplications.pawpads.R;
/**
* Created by Stanislav Volnjanskij on 25.08.16.
*/
public class BindableDouble extends BaseObservable {
private Double value;
private String format="%f";
public Double get() {
return value;
}
public void set(double value) {
if (this.value == null || !this.value.equals(value)) {
this.value = value;
notifyChange();
}
}
public void setSilent(double value) {
if (this.value == null || !this.value.equals(value)) {
this.value = value;
}
}
public BindableDouble(double value) {
super();
this.value = value;
}
public BindableDouble() {
super();
}
@BindingConversion<|fim▁hole|> if (value != null && value.get()!=null)
return String.format(value.getFormat(), value.get());
else {
return null;
}
}
@BindingAdapter({"binding2way"})
public static void bindEditText(EditText view,
final BindableDouble bindableDouble) {
if (view.getTag(R.id.BIND_ID) == null) {
view.setTag(R.id.BIND_ID, true);
view.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
try {
bindableDouble.setSilent(Double.parseDouble(s.toString()));
} catch (Exception e) {
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
//initial value
if (bindableDouble == null) return;
Double newValue = bindableDouble.get();
if (newValue == null) return;
String strValue= String.format(bindableDouble.getFormat(),newValue);
if (!view.getText().toString().equals(strValue) ) {
view.setText(strValue);
}
}
/**
* Number format to display in text field
* @return
*/
public String getFormat() {
return format;
}
/**
*Set number format to display in text field
* @param format
*/
public void setFormat(String format) {
this.format = format;
}
}<|fim▁end|> | public static String convertIntegerToString(BindableDouble value) { |
<|file_name|>indentation_subsystem.py<|end_file_name|><|fim▁begin|># coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).<|fim▁hole|># Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
from pants.contrib.python.checks.tasks.checkstyle.plugin_subsystem_base import PluginSubsystemBase
class IndentationSubsystem(PluginSubsystemBase):
options_scope = 'pycheck-indentation'
def get_plugin_type(self):
from pants.contrib.python.checks.tasks.checkstyle.indentation import Indentation
return Indentation<|fim▁end|> | |
<|file_name|>context.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 animation::Animation;
use app_units::Au;
use dom::OpaqueNode;
use error_reporting::ParseErrorReporter;
use euclid::Size2D;
use matching::{ApplicableDeclarationsCache, StyleSharingCandidateCache};
use properties::ComputedValues;
use selector_impl::SelectorImplExt;
use selector_matching::Stylist;
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex, RwLock};
pub struct SharedStyleContext<Impl: SelectorImplExt> {
/// The current viewport size.
pub viewport_size: Size2D<Au>,
/// Screen sized changed?<|fim▁hole|>
/// The CSS selector stylist.
pub stylist: Arc<Stylist<Impl>>,
/// Starts at zero, and increased by one every time a layout completes.
/// This can be used to easily check for invalid stale data.
pub generation: u32,
/// A channel on which new animations that have been triggered by style recalculation can be
/// sent.
pub new_animations_sender: Mutex<Sender<Animation>>,
/// Why is this reflow occurring
pub goal: ReflowGoal,
/// The animations that are currently running.
pub running_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>,
/// The list of animations that have expired since the last style recalculation.
pub expired_animations: Arc<RwLock<HashMap<OpaqueNode, Vec<Animation>>>>,
///The CSS error reporter for all CSS loaded in this layout thread
pub error_reporter: Box<ParseErrorReporter + Sync>,
}
pub struct LocalStyleContext<C: ComputedValues> {
pub applicable_declarations_cache: RefCell<ApplicableDeclarationsCache<C>>,
pub style_sharing_candidate_cache: RefCell<StyleSharingCandidateCache<C>>,
}
pub trait StyleContext<'a, Impl: SelectorImplExt> {
fn shared_context(&self) -> &'a SharedStyleContext<Impl>;
fn local_context(&self) -> &LocalStyleContext<Impl::ComputedValues>;
}
/// Why we're doing reflow.
#[derive(PartialEq, Copy, Clone, Debug)]
pub enum ReflowGoal {
/// We're reflowing in order to send a display list to the screen.
ForDisplay,
/// We're reflowing in order to satisfy a script query. No display list will be created.
ForScriptQuery,
}<|fim▁end|> | pub screen_size_changed: bool, |
<|file_name|>gulpfile.js<|end_file_name|><|fim▁begin|>var gulp = require('gulp');
var Path = require('path');
var compass = require('gulp-compass');
var minifyCss = require('gulp-minify-css');
var del = require('del');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var plumber = require('gulp-plumber');
var replace = require('gulp-replace');
var karma = require('gulp-karma');
var shell = require('gulp-shell');
var zip = require('gulp-zip');
gulp.task('sass', sassCompile);
gulp.task('assets', assetCopy);
gulp.task('scripts', scriptCompile);
gulp.task('flash', flashCompile);
gulp.task('clean', clean);
gulp.task('packageCopy', packageJsonCopy);
gulp.task('devPackageCopy', devPackageCopy);
gulp.task('reloader', ['build'], reload);
gulp.task('reloadFlash', ['flash'], reload);
gulp.task('dev', ['devPackageCopy', 'build', 'flash'], server);
gulp.task('test', ['build', 'flash'], test);
gulp.task('build', ['sass', 'assets', 'scripts']);
gulp.task('nw', ['build', 'flash', 'packageCopy'], packageNodeWebkit);
gulp.task('default', ['nw']);
<|fim▁hole|>
function sassCompile() {
return gulp.src('src/main/scss/style.scss')
.pipe(plumber({
errorHandler : function (error) {
console.log(error.message);
this.emit('end');
}
}))
.pipe(compass({
project : Path.join(__dirname),
css : outDir + '/css',
sass : 'src/main/scss',
image : 'src/main/img'
}))
.pipe(minifyCss())
.pipe(gulp.dest(outDir + '/css'));
}
function scriptCompile() {
return browserify('src/main/js/app.js')
.bundle()
.on('error', function (err) {
console.log('error occured:', err);
this.emit('end');
})
.pipe(source('app.js'))
.pipe(gulp.dest(outDir + '/js'));
}
function flashCompile() {
var flashCompileCommand;
if (process.platform === 'darwin') {
flashCompileCommand = 'osascript -e \'tell application "Adobe Flash CS6" to open posix file "' + __dirname + '/src/flash/compile.jsfl"\'';
} else {
flashCompileCommand = 'flash.exe "src\\flash\\compile.jsfl"';
}
return gulp.src(['src/flash/compile.jsfl'])
.pipe(plumber())
.pipe(shell('echo 1 > src/flash/compile.jsfl.deleteme'))
.pipe(shell(flashCompileCommand))
}
function assetCopy() {
return gulp.src(['src/main/**', '!src/main/js/**', '!src/main/scss', '!src/main/scss/**'])
.pipe(gulp.dest(outDir));
}
function packageJsonCopy() {
return gulp.src(['src/package.json'])
.pipe(gulp.dest(outDir));
}
function devPackageCopy() {
return gulp.src(['src/package.json'])
.pipe(replace(/(\s*)"main"(\s*:\s*)"([^"]*)"(\s*,\s*)/,
'$1"main"$2"http://localhost:3000/$3"$4"node-remote"$2"http://localhost:3000"$4'))
.pipe(gulp.dest(outDir));
}
function test() {
return gulp.src('src/test/**/*Spec.js')
.pipe(karma({
configFile : 'karma.conf.js',
action : 'run'
}))
.on('error', function (err) {
throw err;
});
}
function server() {
browserSync({
server : {
baseDir : outDir
},
open: false
});
gulp.watch(['src/main/**', 'src/main/js/**', 'src/main/scss/**/*.scss'], {}, ['reloader']);
gulp.watch(['src/flash/**'], {}, ['reloadFlash']);
gulp.src('src/test/**/*Spec.js').pipe(karma({
configFile : 'karma.conf.js',
action : 'watch'
}));
}
function packageNodeWebkit() {
return gulp.src(outDir + '/**')
.pipe(zip('xlc_shop.nw'))
.pipe(gulp.dest(packageDir))
}
function clean(cb) {
del([outDir], cb);
}<|fim▁end|> | var outDir = 'out';
var packageDir = '.'; |
<|file_name|>TimerEntry.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from time import localtime, mktime, time, strftime
from datetime import datetime
from enigma import eEPGCache
from Screens.Screen import Screen
import ChannelSelection
from ServiceReference import ServiceReference
from Components.config import config, ConfigSelection, ConfigText, ConfigSubList, ConfigDateTime, ConfigClock, ConfigYesNo, getConfigListEntry
from Components.ActionMap import NumberActionMap, ActionMap
from Components.ConfigList import ConfigListScreen
from Components.MenuList import MenuList
from Components.Button import Button
from Components.Label import Label
from Components.Pixmap import Pixmap
from Components.SystemInfo import SystemInfo
from Components.UsageConfig import defaultMoviePath
from Components.Sources.Boolean import Boolean
from Screens.MovieSelection import getPreferredTagEditor
from Screens.LocationBox import MovieLocationBox
from Screens.ChoiceBox import ChoiceBox
from Screens.MessageBox import MessageBox
from Screens.VirtualKeyBoard import VirtualKeyBoard
from Screens.Setup import SetupSummary
from RecordTimer import AFTEREVENT
class TimerEntry(Screen, ConfigListScreen):
def __init__(self, session, timer):
Screen.__init__(self, session)
self.setup_title = _("Timer entry")
self.timer = timer
self.entryDate = None
self.entryService = None
self["HelpWindow"] = Pixmap()
self["HelpWindow"].hide()
self["VKeyIcon"] = Boolean(False)
self["description"] = Label("")
self["oktext"] = Label(_("OK"))
self["canceltext"] = Label(_("Cancel"))
self["ok"] = Pixmap()
self["cancel"] = Pixmap()
self.createConfig()
self["actions"] = NumberActionMap(["SetupActions", "GlobalActions", "PiPSetupActions", "ColorActions"],
{
"ok": self.keySelect,
"save": self.keyGo,
"cancel": self.keyCancel,
"volumeUp": self.incrementStart,
"volumeDown": self.decrementStart,
"size+": self.incrementEnd,
"size-": self.decrementEnd,
}, -2)
self["VirtualKB"] = ActionMap(["VirtualKeyboardActions"],
{
"showVirtualKeyboard": self.KeyText,
}, -2)
self["VirtualKB"].setEnabled(False)
self.onChangedEntry = [ ]
self.list = []
ConfigListScreen.__init__(self, self.list, session = session)
self.createSetup("config")
self.onLayoutFinish.append(self.layoutFinished)
if not self.selectionChanged in self["config"].onSelectionChanged:
self["config"].onSelectionChanged.append(self.selectionChanged)
self.selectionChanged()
def createConfig(self):
justplay = self.timer.justplay
always_zap = self.timer.always_zap
rename_repeat = self.timer.rename_repeat
afterevent = {
AFTEREVENT.NONE: "nothing",
AFTEREVENT.DEEPSTANDBY: "deepstandby",
AFTEREVENT.STANDBY: "standby",
AFTEREVENT.AUTO: "auto"
}[self.timer.afterEvent]
if self.timer.record_ecm and self.timer.descramble:
recordingtype = "descrambled+ecm"
elif self.timer.record_ecm:
recordingtype = "scrambled+ecm"
elif self.timer.descramble:
recordingtype = "normal"
weekday_table = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
# calculate default values
day = []
weekday = 0
for x in (0, 1, 2, 3, 4, 5, 6):
day.append(0)
if self.timer.repeated: # repeated
type = "repeated"
if self.timer.repeated == 31: # Mon-Fri
repeated = "weekdays"
elif self.timer.repeated == 127: # daily
repeated = "daily"
else:
flags = self.timer.repeated
repeated = "user"
count = 0
for x in (0, 1, 2, 3, 4, 5, 6):
if flags == 1: # weekly
# print "Set to weekday " + str(x)
weekday = x
if flags & 1 == 1: # set user defined flags
day[x] = 1
count += 1
else:
day[x] = 0
flags >>= 1
if count == 1:
repeated = "weekly"
else: # once
type = "once"
repeated = None
weekday = int(strftime("%u", localtime(self.timer.begin))) - 1
day[weekday] = 1
self.timerentry_justplay = ConfigSelection(choices = [
("zap", _("zap")), ("record", _("record")), ("zap+record", _("zap and record"))],
default = {0: "record", 1: "zap", 2: "zap+record"}[justplay + 2*always_zap])
if SystemInfo["DeepstandbySupport"]:
shutdownString = _("go to deep standby")
else:
shutdownString = _("shut down")
self.timerentry_afterevent = ConfigSelection(choices = [("nothing", _("do nothing")), ("standby", _("go to standby")), ("deepstandby", shutdownString), ("auto", _("auto"))], default = afterevent)
self.timerentry_recordingtype = ConfigSelection(choices = [("normal", _("normal")), ("descrambled+ecm", _("descramble and record ecm")), ("scrambled+ecm", _("don't descramble, record ecm"))], default = recordingtype)
self.timerentry_type = ConfigSelection(choices = [("once",_("once")), ("repeated", _("repeated"))], default = type)
self.timerentry_name = ConfigText(default = self.timer.name.replace('\xc2\x86', '').replace('\xc2\x87', '').encode("utf-8"), visible_width = 50, fixed_size = False)
self.timerentry_description = ConfigText(default = self.timer.description, visible_width = 50, fixed_size = False)
self.timerentry_tags = self.timer.tags[:]
# if no tags found, make name of event default tag set.
if not self.timerentry_tags:
tagname = self.timer.name.strip()
if tagname:
tagname = tagname[0].upper() + tagname[1:].replace(" ", "_")
self.timerentry_tags.append(tagname)
self.timerentry_tagsset = ConfigSelection(choices = [not self.timerentry_tags and "None" or " ".join(self.timerentry_tags)])
self.timerentry_repeated = ConfigSelection(default = repeated, choices = [("weekly", _("weekly")), ("daily", _("daily")), ("weekdays", _("Mon-Fri")), ("user", _("user defined"))])
self.timerentry_renamerepeat = ConfigYesNo(default = rename_repeat)
self.timerentry_date = ConfigDateTime(default = self.timer.begin, formatstring = _("%d %B %Y"), increment = 86400)
self.timerentry_starttime = ConfigClock(default = self.timer.begin)
self.timerentry_endtime = ConfigClock(default = self.timer.end)
self.timerentry_showendtime = ConfigSelection(default = False, choices = [(True, _("yes")), (False, _("no"))])
default = self.timer.dirname or defaultMoviePath()
tmp = config.movielist.videodirs.value
if default not in tmp:
tmp.append(default)
self.timerentry_dirname = ConfigSelection(default = default, choices = tmp)
self.timerentry_repeatedbegindate = ConfigDateTime(default = self.timer.repeatedbegindate, formatstring = _("%d.%B %Y"), increment = 86400)
self.timerentry_weekday = ConfigSelection(default = weekday_table[weekday], choices = [("mon",_("Monday")), ("tue", _("Tuesday")), ("wed",_("Wednesday")), ("thu", _("Thursday")), ("fri", _("Friday")), ("sat", _("Saturday")), ("sun", _("Sunday"))])
self.timerentry_day = ConfigSubList()
for x in (0, 1, 2, 3, 4, 5, 6):
self.timerentry_day.append(ConfigYesNo(default = day[x]))
# FIXME some service-chooser needed here
servicename = "N/A"
try: # no current service available?
servicename = str(self.timer.service_ref.getServiceName())
except:
pass
self.timerentry_service_ref = self.timer.service_ref
self.timerentry_service = ConfigSelection([servicename])
def createSetup(self, widget):
self.list = []
self.entryName = getConfigListEntry(_("Name"), self.timerentry_name, _("Set the name the recording will get."))
self.list.append(self.entryName)
self.entryDescription = getConfigListEntry(_("Description"), self.timerentry_description, _("Set the description of the recording."))
self.list.append(self.entryDescription)
self.timerJustplayEntry = getConfigListEntry(_("Timer type"), self.timerentry_justplay, _("Chose between record and ZAP."))
self.list.append(self.timerJustplayEntry)
self.timerTypeEntry = getConfigListEntry(_("Repeat type"), self.timerentry_type, _("A repeating timer or just once?"))
self.list.append(self.timerTypeEntry)
if self.timerentry_type.value == "once":
self.frequencyEntry = None
else: # repeated
self.frequencyEntry = getConfigListEntry(_("Repeats"), self.timerentry_repeated, _("Choose between Daily, Weekly, Weekdays or user defined."))
self.list.append(self.frequencyEntry)
self.repeatedbegindateEntry = getConfigListEntry(_("Starting on"), self.timerentry_repeatedbegindate, _("Set the date the timer must start."))
self.list.append(self.repeatedbegindateEntry)
if self.timerentry_repeated.value == "daily":
pass
if self.timerentry_repeated.value == "weekdays":
pass
if self.timerentry_repeated.value == "weekly":
self.list.append(getConfigListEntry(_("Weekday"), self.timerentry_weekday))
if self.timerentry_repeated.value == "user":
self.list.append(getConfigListEntry(_("Monday"), self.timerentry_day[0]))
self.list.append(getConfigListEntry(_("Tuesday"), self.timerentry_day[1]))
self.list.append(getConfigListEntry(_("Wednesday"), self.timerentry_day[2]))
self.list.append(getConfigListEntry(_("Thursday"), self.timerentry_day[3]))
self.list.append(getConfigListEntry(_("Friday"), self.timerentry_day[4]))
self.list.append(getConfigListEntry(_("Saturday"), self.timerentry_day[5]))
self.list.append(getConfigListEntry(_("Sunday"), self.timerentry_day[6]))
if self.timerentry_justplay.value != "zap":
self.list.append(getConfigListEntry(_("Rename name and description for new events"), self.timerentry_renamerepeat))
self.entryDate = getConfigListEntry(_("Date"), self.timerentry_date, _("Set the date the timer must start."))
if self.timerentry_type.value == "once":
self.list.append(self.entryDate)
self.entryStartTime = getConfigListEntry(_("Start time"), self.timerentry_starttime, _("Set the time the timer must start."))
self.list.append(self.entryStartTime)
self.entryShowEndTime = getConfigListEntry(_("Set end time"), self.timerentry_showendtime, _("Set the time the timer must stop."))
# if self.timerentry_justplay.value == "zap":
# self.list.append(self.entryShowEndTime)
self.entryEndTime = getConfigListEntry(_("End time"), self.timerentry_endtime, _("Set the time the timer must stop."))
if self.timerentry_justplay.value != "zap" or self.timerentry_showendtime.value:
self.list.append(self.entryEndTime)
self.channelEntry = getConfigListEntry(_("Channel"), self.timerentry_service, _("Set the channel for this timer."))
self.list.append(self.channelEntry)
self.dirname = getConfigListEntry(_("Location"), self.timerentry_dirname, _("Where should the recording be saved?"))
self.tagsSet = getConfigListEntry(_("Tags"), self.timerentry_tagsset, _("Choose a tag for easy finding a recording."))
if self.timerentry_justplay.value != "zap":
if config.usage.setup_level.index >= 2: # expert+
self.list.append(self.dirname)
if getPreferredTagEditor():
self.list.append(self.tagsSet)
self.list.append(getConfigListEntry(_("After event"), self.timerentry_afterevent, _("What action is required on complettion of the timer? 'Auto' lets the box return to the state it had when the timer started. 'Do nothing', 'Go to standby' and 'Go to deep standby' do ecaxtly that.")))
self.list.append(getConfigListEntry(_("Recording type"), self.timerentry_recordingtype, _("Descramble & record ECM' gives the option to descramble afterwards if descrambling on recording failed. 'Don't descramble, record ECM' save a scramble recording that can be descrambled on playback. 'Normal' means descramble the recording and don't record ECM.")))
self[widget].list = self.list
self[widget].l.setList(self.list)
def selectionChanged(self):
if self["config"].getCurrent():
if len(self["config"].getCurrent()) > 2 and self["config"].getCurrent()[2]:
self["description"].setText(self["config"].getCurrent()[2])
if isinstance(self["config"].getCurrent()[1], ConfigText):
if self.has_key("VKeyIcon"):
self["VirtualKB"].setEnabled(True)
self["VKeyIcon"].boolean = True
if self.has_key("HelpWindow"):
if self["config"].getCurrent()[1].help_window and self["config"].getCurrent()[1].help_window.instance is not None:
helpwindowpos = self["HelpWindow"].getPosition()
from enigma import ePoint
self["config"].getCurrent()[1].help_window.instance.move(ePoint(helpwindowpos[0],helpwindowpos[1]))
else:
if self.has_key("VKeyIcon"):
self["VirtualKB"].setEnabled(False)
self["VKeyIcon"].boolean = False
else:
if self.has_key("VKeyIcon"):
self["VirtualKB"].setEnabled(False)
self["VKeyIcon"].boolean = False
def layoutFinished(self):
self.setTitle(_(self.setup_title))
def createSummary(self):
return SetupSummary
# for summary:
def changedEntry(self):
for x in self.onChangedEntry:
x()
def getCurrentEntry(self):
return self["config"].getCurrent() and self["config"].getCurrent()[0] or ""
def getCurrentValue(self):
return self["config"].getCurrent() and str(self["config"].getCurrent()[1].getText()) or ""
def newConfig(self):
if self["config"].getCurrent() in (self.timerTypeEntry, self.timerJustplayEntry, self.frequencyEntry, self.entryShowEndTime):
self.createSetup("config")
def KeyText(self):
if self['config'].getCurrent()[0] in (_('Name'), _("Description")):
self.session.openWithCallback(self.renameEntryCallback, VirtualKeyBoard, title=self["config"].getCurrent()[2], text = self["config"].getCurrent()[1].value)
def keyLeft(self):
cur = self["config"].getCurrent()
if cur in (self.channelEntry, self.tagsSet):
self.keySelect()
elif cur in (self.entryName, self.entryDescription):
self.renameEntry()
else:
ConfigListScreen.keyLeft(self)
self.newConfig()
def keyRight(self):
cur = self["config"].getCurrent()
if cur in (self.channelEntry, self.tagsSet):
self.keySelect()
elif cur in (self.entryName, self.entryDescription):
self.renameEntry()
else:
ConfigListScreen.keyRight(self)
self.newConfig()
def renameEntry(self):
cur = self["config"].getCurrent()
if cur == self.entryName:
title_text = _("Please enter new name:")
old_text = self.timerentry_name.value
else:
title_text = _("Please enter new description:")
old_text = self.timerentry_description.value
self.session.openWithCallback(self.renameEntryCallback, VirtualKeyBoard, title=title_text, text=old_text)
def renameEntryCallback(self, answer):
if answer:
if self["config"].getCurrent() == self.entryName:
self.timerentry_name.value = answer
self["config"].invalidate(self.entryName)
else:
self.timerentry_description.value = answer
self["config"].invalidate(self.entryDescription)
<|fim▁hole|> else:
ConfigListScreen.handleKeyFileCallback(self, answer)
self.newConfig()
def keySelect(self):
cur = self["config"].getCurrent()
if cur == self.channelEntry:
self.session.openWithCallback(
self.finishedChannelSelection,
ChannelSelection.SimpleChannelSelection,
_("Select channel to record from"),
currentBouquet=True
)
elif config.usage.setup_level.index >= 2 and cur == self.dirname:
self.session.openWithCallback(
self.pathSelected,
MovieLocationBox,
_("Select target folder"),
self.timerentry_dirname.value,
minFree = 100 # We require at least 100MB free space
)
elif getPreferredTagEditor() and cur == self.tagsSet:
self.session.openWithCallback(
self.tagEditFinished,
getPreferredTagEditor(),
self.timerentry_tags
)
else:
self.keyGo()
def finishedChannelSelection(self, *args):
if args:
self.timerentry_service_ref = ServiceReference(args[0])
self.timerentry_service.setCurrentText(self.timerentry_service_ref.getServiceName())
self["config"].invalidate(self.channelEntry)
def getTimestamp(self, date, mytime):
d = localtime(date)
dt = datetime(d.tm_year, d.tm_mon, d.tm_mday, mytime[0], mytime[1])
return int(mktime(dt.timetuple()))
def getBeginEnd(self):
date = self.timerentry_date.value
endtime = self.timerentry_endtime.value
starttime = self.timerentry_starttime.value
begin = self.getTimestamp(date, starttime)
end = self.getTimestamp(date, endtime)
# if the endtime is less than the starttime, add 1 day.
if end < begin:
end += 86400
# if the timer type is a Zap and no end is set, set duration to 1 second so time is shown in EPG's.
if self.timerentry_justplay.value == "zap":
if not self.timerentry_showendtime.value:
end = begin + (config.recording.margin_before.value*60) + 1
return begin, end
def selectChannelSelector(self, *args):
self.session.openWithCallback(
self.finishedChannelSelectionCorrection,
ChannelSelection.SimpleChannelSelection,
_("Select channel to record from")
)
def finishedChannelSelectionCorrection(self, *args):
if args:
self.finishedChannelSelection(*args)
self.keyGo()
def keyGo(self, result = None):
if not self.timerentry_service_ref.isRecordable():
self.session.openWithCallback(self.selectChannelSelector, MessageBox, _("You didn't select a channel to record from."), MessageBox.TYPE_ERROR)
return
self.timer.name = self.timerentry_name.value
self.timer.description = self.timerentry_description.value
self.timer.justplay = self.timerentry_justplay.value == "zap"
self.timer.always_zap = self.timerentry_justplay.value == "zap+record"
self.timer.rename_repeat = self.timerentry_renamerepeat.value
if self.timerentry_justplay.value == "zap":
if not self.timerentry_showendtime.value:
self.timerentry_endtime.value = self.timerentry_starttime.value
self.timer.resetRepeated()
self.timer.afterEvent = {
"nothing": AFTEREVENT.NONE,
"deepstandby": AFTEREVENT.DEEPSTANDBY,
"standby": AFTEREVENT.STANDBY,
"auto": AFTEREVENT.AUTO
}[self.timerentry_afterevent.value]
self.timer.descramble = {
"normal": True,
"descrambled+ecm": True,
"scrambled+ecm": False,
}[self.timerentry_recordingtype.value]
self.timer.record_ecm = {
"normal": False,
"descrambled+ecm": True,
"scrambled+ecm": True,
}[self.timerentry_recordingtype.value]
self.timer.service_ref = self.timerentry_service_ref
self.timer.tags = self.timerentry_tags
if self.timer.dirname or self.timerentry_dirname.value != defaultMoviePath():
self.timer.dirname = self.timerentry_dirname.value
config.movielist.last_timer_videodir.value = self.timer.dirname
config.movielist.last_timer_videodir.save()
if self.timerentry_type.value == "once":
self.timer.begin, self.timer.end = self.getBeginEnd()
if self.timerentry_type.value == "repeated":
if self.timerentry_repeated.value == "daily":
for x in (0, 1, 2, 3, 4, 5, 6):
self.timer.setRepeated(x)
if self.timerentry_repeated.value == "weekly":
self.timer.setRepeated(self.timerentry_weekday.index)
if self.timerentry_repeated.value == "weekdays":
for x in (0, 1, 2, 3, 4):
self.timer.setRepeated(x)
if self.timerentry_repeated.value == "user":
for x in (0, 1, 2, 3, 4, 5, 6):
if self.timerentry_day[x].value:
self.timer.setRepeated(x)
self.timer.repeatedbegindate = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
if self.timer.repeated:
self.timer.begin = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_starttime.value)
self.timer.end = self.getTimestamp(self.timerentry_repeatedbegindate.value, self.timerentry_endtime.value)
else:
self.timer.begin = self.getTimestamp(time.time(), self.timerentry_starttime.value)
self.timer.end = self.getTimestamp(time.time(), self.timerentry_endtime.value)
# when a timer end is set before the start, add 1 day
if self.timer.end < self.timer.begin:
self.timer.end += 86400
if self.timer.eit is not None:
event = eEPGCache.getInstance().lookupEventId(self.timer.service_ref.ref, self.timer.eit)
if event:
n = event.getNumOfLinkageServices()
if n > 1:
tlist = []
ref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
parent = self.timer.service_ref.ref
selection = 0
for x in range(n):
i = event.getLinkageService(parent, x)
if i.toString() == ref.toString():
selection = x
tlist.append((i.getName(), i))
self.session.openWithCallback(self.subserviceSelected, ChoiceBox, title=_("Please select a subservice to record..."), list = tlist, selection = selection)
return
elif n > 0:
parent = self.timer.service_ref.ref
self.timer.service_ref = ServiceReference(event.getLinkageService(parent, 0))
self.saveTimer()
self.close((True, self.timer))
def changeTimerType(self):
self.timerentry_justplay.selectNext()
self.timerJustplayEntry = getConfigListEntry(_("Timer type"), self.timerentry_justplay)
self["config"].invalidate(self.timerJustplayEntry)
def incrementStart(self):
self.timerentry_starttime.increment()
self["config"].invalidate(self.entryStartTime)
if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [0, 0]:
self.timerentry_date.value += 86400
self["config"].invalidate(self.entryDate)
def decrementStart(self):
self.timerentry_starttime.decrement()
self["config"].invalidate(self.entryStartTime)
if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [23, 59]:
self.timerentry_date.value -= 86400
self["config"].invalidate(self.entryDate)
def incrementEnd(self):
if self.entryEndTime is not None:
self.timerentry_endtime.increment()
self["config"].invalidate(self.entryEndTime)
def decrementEnd(self):
if self.entryEndTime is not None:
self.timerentry_endtime.decrement()
self["config"].invalidate(self.entryEndTime)
def subserviceSelected(self, service):
if not service is None:
self.timer.service_ref = ServiceReference(service[1])
self.saveTimer()
self.close((True, self.timer))
def saveTimer(self):
self.session.nav.RecordTimer.saveTimer()
def keyCancel(self):
self.close((False,))
def pathSelected(self, res):
if res is not None:
if config.movielist.videodirs.value != self.timerentry_dirname.choices:
self.timerentry_dirname.setChoices(config.movielist.videodirs.value, default=res)
self.timerentry_dirname.value = res
def tagEditFinished(self, ret):
if ret is not None:
self.timerentry_tags = ret
self.timerentry_tagsset.setChoices([not ret and "None" or " ".join(ret)])
self["config"].invalidate(self.tagsSet)
class TimerLog(Screen):
def __init__(self, session, timer):
Screen.__init__(self, session)
self.timer = timer
self.log_entries = self.timer.log_entries[:]
self.fillLogList()
self["loglist"] = MenuList(self.list)
self["logentry"] = Label()
self["key_red"] = Button(_("Delete entry"))
self["key_green"] = Button()
self["key_blue"] = Button(_("Clear log"))
self.onShown.append(self.updateText)
self["actions"] = NumberActionMap(["OkCancelActions", "DirectionActions", "ColorActions"],
{
"ok": self.keyClose,
"cancel": self.keyClose,
"up": self.up,
"down": self.down,
"left": self.left,
"right": self.right,
"red": self.deleteEntry,
"blue": self.clearLog
}, -1)
self.setTitle(_("Timer log"))
def deleteEntry(self):
cur = self["loglist"].getCurrent()
if cur is None:
return
self.log_entries.remove(cur[1])
self.fillLogList()
self["loglist"].l.setList(self.list)
self.updateText()
def fillLogList(self):
self.list = [(str(strftime("%Y-%m-%d %H-%M", localtime(x[0])) + " - " + x[2]), x) for x in self.log_entries]
def clearLog(self):
self.log_entries = []
self.fillLogList()
self["loglist"].l.setList(self.list)
self.updateText()
def keyClose(self):
if self.timer.log_entries != self.log_entries:
self.timer.log_entries = self.log_entries
self.close((True, self.timer))
else:
self.close((False,))
def up(self):
self["loglist"].instance.moveSelection(self["loglist"].instance.moveUp)
self.updateText()
def down(self):
self["loglist"].instance.moveSelection(self["loglist"].instance.moveDown)
self.updateText()
def left(self):
self["loglist"].instance.moveSelection(self["loglist"].instance.pageUp)
self.updateText()
def right(self):
self["loglist"].instance.moveSelection(self["loglist"].instance.pageDown)
self.updateText()
def updateText(self):
if self.list:
self["logentry"].setText(str(self["loglist"].getCurrent()[1][2]))
else:
self["logentry"].setText("")
class InstantRecordTimerEntry(TimerEntry):
def __init__(self, session, timer, zap):
Screen.__init__(self, session)
self.setup_title = ""
self.timer = timer
self.timer.justplay = zap
self.entryDate = None
self.entryService = None
self.keyGo()
def keyGo(self, result = None):
if self.timer.justplay:
self.timer.end = self.timer.begin + (config.recording.margin_before.value * 60) + 1
self.timer.resetRepeated()
self.saveTimer()
def retval(self):
return self.timer
def saveTimer(self):
self.session.nav.RecordTimer.saveTimer()<|fim▁end|> | def handleKeyFileCallback(self, answer):
if self["config"].getCurrent() in (self.channelEntry, self.tagsSet):
self.keySelect() |
<|file_name|>debug.py<|end_file_name|><|fim▁begin|># Based on Rapptz's RoboDanny's repl cog
import contextlib
import inspect
import logging
import re
import sys
import textwrap
import traceback
from io import StringIO
from typing import *
from typing import Pattern
import discord
from discord.ext import commands
# i took this from somewhere and i cant remember where
md: Pattern = re.compile(r"^(([ \t]*`{3,4})([^\n]*)(?P<code>[\s\S]+?)(^[ \t]*\2))", re.MULTILINE)
logger = logging.getLogger(__name__)
class BotDebug(object):
def __init__(self, client: commands.Bot):
self.client = client
self.last_eval = None
@commands.command(hidden=True)
async def exec(self, ctx: commands.Context, *, cmd: str):
result, stdout, stderr = await self.run(ctx, cmd, use_exec=True)
await self.send_output(ctx, result, stdout, stderr)
@commands.command(hidden=True)<|fim▁hole|> await self.send_output(ctx, result, stdout, stderr)
async def send_output(self, ctx: commands.Context, result: str, stdout: str, stderr: str):
print(result, stdout, stderr)
if result is not None:
await ctx.send(f"Result: `{result}`")
if stdout:
logger.info(f"exec stdout: \n{stdout}")
await ctx.send("stdout:")
await self.send_split(ctx, stdout)
if stderr:
logger.error(f"exec stderr: \n{stderr}")
await ctx.send("stderr:")
await self.send_split(ctx, stderr)
async def run(self, ctx: commands.Context, cmd: str, use_exec: bool, extra_scope: dict=None) -> Tuple[Any, str, str]:
if not self.client.is_owner(ctx.author):
return None, "", ""
# note: exec/eval inserts __builtins__ if a custom version is not defined (or set to {} or whatever)
scope: Dict[str, Any] = {'bot': self.client, 'ctx': ctx, 'discord': discord}
if extra_scope:
scope.update(extra_scope)
match: Match = md.match(cmd)
code: str = match.group("code").strip() if match else cmd.strip('` \n')
logger.info(f"Executing code '{code}'")
result = None
with std_redirect() as (stdout, stderr):
try:
if use_exec:
# wrap in async function to run in loop and allow await calls
func = f"async def run():\n{textwrap.indent(code, ' ')}"
exec(func, scope)
result = await scope['run']()
else:
result = eval(code, scope)
# eval doesn't allow `await`
if inspect.isawaitable(result):
result = await result
except (SystemExit, KeyboardInterrupt):
raise
except Exception:
await self.on_error(ctx)
else:
await ctx.message.add_reaction('✅')
return result, stdout.getvalue(), stderr.getvalue()
async def on_error(self, ctx: commands.Context):
# prepend a "- " to each line and use ```diff``` syntax highlighting to color the error message red.
# also strip lines 2 and 3 of the traceback which includes full path to the file, irrelevant for repl code.
# yes i know error[:1] is basically error[0] but i want it to stay as a list
logger.exception("Error in exec code")
error = traceback.format_exc().splitlines()
error = textwrap.indent('\n'.join(error[:1] + error[3:]), '- ', lambda x: True)
await ctx.send("Traceback:")
await self.send_split(ctx, error, prefix="```diff\n")
async def send_split(self, ctx: commands.Context, text: str, *, prefix="```\n", postfix="\n```"):
max_len = 2000 - (len(prefix) + len(postfix))
text: List[str] = [text[x:x + max_len] for x in range(0, len(text), max_len)]
print(text)
for message in text:
await ctx.send(f"{prefix}{message}{postfix}")
@contextlib.contextmanager
def std_redirect():
stdout = sys.stdout
stderr = sys.stderr
sys.stdout = StringIO()
sys.stderr = StringIO()
yield sys.stdout, sys.stderr
sys.stdout = stdout
sys.stderr = stderr
def init(bot: commands.Bot, cfg: dict):
bot.add_cog(BotDebug(bot))<|fim▁end|> | async def eval(self, ctx: commands.Context, *, cmd: str):
scope = {"_": self.last_eval, "last": self.last_eval}
result, stdout, stderr = await self.run(ctx, cmd, use_exec=False, extra_scope=scope)
self.last_eval = result |
<|file_name|>_express_route_ports_locations_operations.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse<|fim▁hole|>
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class ExpressRoutePortsLocationsOperations(object):
"""ExpressRoutePortsLocationsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2021_05_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def list(
self,
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.ExpressRoutePortsLocationListResult"]
"""Retrieves all ExpressRoutePort peering locations. Does not return available bandwidths for each
location. Available bandwidths can only be obtained when retrieving a specific peering
location.
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either ExpressRoutePortsLocationListResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2021_05_01.models.ExpressRoutePortsLocationListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRoutePortsLocationListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-05-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('ExpressRoutePortsLocationListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePortsLocations'} # type: ignore
def get(
self,
location_name, # type: str
**kwargs # type: Any
):
# type: (...) -> "_models.ExpressRoutePortsLocation"
"""Retrieves a single ExpressRoutePort peering location, including the list of available
bandwidths available at said peering location.
:param location_name: Name of the requested ExpressRoutePort peering location.
:type location_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: ExpressRoutePortsLocation, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2021_05_01.models.ExpressRoutePortsLocation
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRoutePortsLocation"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-05-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'locationName': self._serialize.url("location_name", location_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('ExpressRoutePortsLocation', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePortsLocations/{locationName}'} # type: ignore<|fim▁end|> | from azure.mgmt.core.exceptions import ARMErrorFormat
from .. import models as _models |
<|file_name|>package.py<|end_file_name|><|fim▁begin|># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyIlmbase(AutotoolsPackage):
"""The PyIlmBase libraries provides python bindings for the IlmBase libraries."""
homepage = "https://github.com/AcademySoftwareFoundation/openexr/tree/v2.3.0/PyIlmBase"
url = "https://github.com/AcademySoftwareFoundation/openexr/releases/download/v2.3.0/pyilmbase-2.3.0.tar.gz"
version('2.3.0', sha256='9c898bb16e7bc916c82bebdf32c343c0f2878fc3eacbafa49937e78f2079a425')
depends_on('ilmbase')
depends_on('boost+python')<|fim▁hole|> parallel = False
def configure_args(self):
spec = self.spec
args = [
'--with-boost-python-libname=boost_python{0}'.format(
spec['python'].version.up_to(2).joined)
]
return args<|fim▁end|> |
# https://github.com/AcademySoftwareFoundation/openexr/issues/336 |
<|file_name|>iscsi.py<|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.
"""Libvirt volume driver for iSCSI"""
from os_brick import exception as os_brick_exception
from os_brick.initiator import connector<|fim▁hole|>
import nova.conf
from nova import utils
from nova.virt.libvirt.volume import volume as libvirt_volume
LOG = logging.getLogger(__name__)
CONF = nova.conf.CONF
class LibvirtISCSIVolumeDriver(libvirt_volume.LibvirtBaseVolumeDriver):
"""Driver to attach Network volumes to libvirt."""
def __init__(self, host):
super(LibvirtISCSIVolumeDriver, self).__init__(host,
is_block_dev=True)
# Call the factory here so we can support
# more than x86 architectures.
self.connector = connector.InitiatorConnector.factory(
'ISCSI', utils.get_root_helper(),
use_multipath=CONF.libvirt.volume_use_multipath,
device_scan_attempts=CONF.libvirt.num_volume_scan_tries,
transport=self._get_transport())
def _get_transport(self):
if CONF.libvirt.iscsi_iface:
transport = CONF.libvirt.iscsi_iface
else:
transport = 'default'
return transport
def get_config(self, connection_info, disk_info):
"""Returns xml for libvirt."""
conf = super(LibvirtISCSIVolumeDriver,
self).get_config(connection_info, disk_info)
conf.source_type = "block"
conf.source_path = connection_info['data']['device_path']
conf.driver_io = "native"
return conf
def connect_volume(self, connection_info, disk_info, instance):
"""Attach the volume to instance_name."""
LOG.debug("Calling os-brick to attach iSCSI Volume")
device_info = self.connector.connect_volume(connection_info['data'])
LOG.debug("Attached iSCSI volume %s", device_info)
connection_info['data']['device_path'] = device_info['path']
def disconnect_volume(self, connection_info, disk_dev, instance):
"""Detach the volume from instance_name."""
LOG.debug("calling os-brick to detach iSCSI Volume")
try:
self.connector.disconnect_volume(connection_info['data'], None)
except os_brick_exception.VolumeDeviceNotFound as exc:
LOG.warning('Ignoring VolumeDeviceNotFound: %s', exc)
return
LOG.debug("Disconnected iSCSI Volume %s", disk_dev)
super(LibvirtISCSIVolumeDriver,
self).disconnect_volume(connection_info, disk_dev, instance)
def extend_volume(self, connection_info, instance):
"""Extend the volume."""
LOG.debug("calling os-brick to extend iSCSI Volume", instance=instance)
new_size = self.connector.extend_volume(connection_info['data'])
LOG.debug("Extend iSCSI Volume %s; new_size=%s",
connection_info['data']['device_path'],
new_size, instance=instance)
return new_size<|fim▁end|> | from oslo_log import log as logging |
<|file_name|>chaingen.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2012-2013 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <vector>
#include <iostream>
#include <sstream>
#include "include_base_utils.h"
#include "console_handler.h"
#include "p2p/net_node.h"
#include "currency_core/currency_basic.h"
#include "currency_core/currency_basic_impl.h"
#include "currency_core/currency_format_utils.h"
#include "currency_core/miner.h"
#include "chaingen.h"
using namespace std;
using namespace epee;
using namespace currency;
#define DIFF_UP_TIMESTAMP_DELTA 90
void test_generator::get_block_chain(std::vector<const block_info*>& blockchain, const crypto::hash& head, size_t n) const
{
crypto::hash curr = head;
while (null_hash != curr && blockchain.size() < n)
{
auto it = m_blocks_info.find(curr);
if (m_blocks_info.end() == it)
{
throw std::runtime_error("block hash wasn't found");
}
blockchain.push_back(&it->second);
curr = it->second.b.prev_id;
}
std::reverse(blockchain.begin(), blockchain.end());
}
void test_generator::get_last_n_block_sizes(std::vector<size_t>& block_sizes, const crypto::hash& head, size_t n) const
{
std::vector<const block_info*> blockchain;
get_block_chain(blockchain, head, n);
BOOST_FOREACH(auto& bi, blockchain)
{
block_sizes.push_back(bi->block_size);
}
}
uint64_t test_generator::get_already_generated_coins(const crypto::hash& blk_id) const
{
auto it = m_blocks_info.find(blk_id);
if (it == m_blocks_info.end())
throw std::runtime_error("block hash wasn't found");
return it->second.already_generated_coins;
}
uint64_t test_generator::get_already_donated_coins(const crypto::hash& blk_id) const
{
auto it = m_blocks_info.find(blk_id);
if (it == m_blocks_info.end())
throw std::runtime_error("block hash wasn't found");
return it->second.already_donated;
}
currency::wide_difficulty_type test_generator::get_block_difficulty(const crypto::hash& blk_id) const
{
auto it = m_blocks_info.find(blk_id);
if (it == m_blocks_info.end())
throw std::runtime_error("block hash wasn't found");
auto it_prev = m_blocks_info.find(it->second.b.prev_id);
if (it_prev == m_blocks_info.end())
throw std::runtime_error("block hash wasn't found");
return it->second.cumul_difficulty - it_prev->second.cumul_difficulty;
}
uint64_t test_generator::get_already_generated_coins(const currency::block& blk) const
{
crypto::hash blk_hash;
get_block_hash(blk, blk_hash);
return get_already_generated_coins(blk_hash);
}
void test_generator::add_block(const currency::block& blk, size_t tsx_size, std::vector<size_t>& block_sizes,
uint64_t already_generated_coins,
uint64_t already_donated_coins,
wide_difficulty_type cum_diff)
{
const size_t block_size = tsx_size + get_object_blobsize(blk.miner_tx);
uint64_t block_reward;
uint64_t max_donation;
get_block_reward(misc_utils::median(block_sizes), block_size, already_generated_coins, already_donated_coins, block_reward, max_donation);
uint64_t donation_for_block = 0;
m_blocks_info[get_block_hash(blk)] = block_info(blk, already_generated_coins + block_reward, already_donated_coins + donation_for_block, block_size, cum_diff);
}
bool test_generator::construct_block(currency::block& blk, uint64_t height, const crypto::hash& prev_id,
const currency::account_base& miner_acc, uint64_t timestamp, uint64_t already_generated_coins, uint64_t already_donated_coins,
std::vector<size_t>& block_sizes, const std::list<currency::transaction>& tx_list, const currency::alias_info& ai)
{
blk.major_version = CURRENT_BLOCK_MAJOR_VERSION;
blk.minor_version = CURRENT_BLOCK_MINOR_VERSION;
blk.flags = BLOCK_FLAGS_SUPPRESS_DONATION;
blk.timestamp = timestamp;
blk.prev_id = prev_id;
blk.tx_hashes.reserve(tx_list.size());
BOOST_FOREACH(const transaction &tx, tx_list)
{
crypto::hash tx_hash;
get_transaction_hash(tx, tx_hash);
blk.tx_hashes.push_back(tx_hash);
}
uint64_t total_fee = 0;
size_t txs_size = 0;
BOOST_FOREACH(auto& tx, tx_list)
{
uint64_t fee = 0;
bool r = get_tx_fee(tx, fee);
CHECK_AND_ASSERT_MES(r, false, "wrong transaction passed to construct_block");
total_fee += fee;
txs_size += get_object_blobsize(tx);
}
account_keys donation_acc = AUTO_VAL_INIT(donation_acc);
account_keys royalty_acc = AUTO_VAL_INIT(royalty_acc);
get_donation_accounts(donation_acc, royalty_acc);
blk.miner_tx = AUTO_VAL_INIT(blk.miner_tx);
size_t target_block_size = txs_size + get_object_blobsize(blk.miner_tx);
while (true)
{
if (!construct_miner_tx(height, misc_utils::median(block_sizes),
already_generated_coins,
already_donated_coins,
target_block_size,
total_fee,
miner_acc.get_keys().m_account_address,
donation_acc.m_account_address,
royalty_acc.m_account_address,
blk.miner_tx,
blobdata(),
10,
0,
ai))
return false;
size_t actual_block_size = txs_size + get_object_blobsize(blk.miner_tx);
if (target_block_size < actual_block_size)
{
target_block_size = actual_block_size;
}
else if (actual_block_size < target_block_size)
{
size_t delta = target_block_size - actual_block_size;
blk.miner_tx.extra.resize(blk.miner_tx.extra.size() + delta, 0);
actual_block_size = txs_size + get_object_blobsize(blk.miner_tx);
if (actual_block_size == target_block_size)
{
break;
}
else
{
CHECK_AND_ASSERT_MES(target_block_size < actual_block_size, false, "Unexpected block size");
delta = actual_block_size - target_block_size;
blk.miner_tx.extra.resize(blk.miner_tx.extra.size() - delta);
actual_block_size = txs_size + get_object_blobsize(blk.miner_tx);
if (actual_block_size == target_block_size)
{
break;
}
else
{
CHECK_AND_ASSERT_MES(actual_block_size < target_block_size, false, "Unexpected block size");
blk.miner_tx.extra.resize(blk.miner_tx.extra.size() + delta, 0);
target_block_size = txs_size + get_object_blobsize(blk.miner_tx);
}
}
}
else
{
break;
}
}
//blk.tree_root_hash = get_tx_tree_hash(blk);
std::vector<const block_info*> blocks;
get_block_chain(blocks, blk.prev_id, std::numeric_limits<size_t>::max());
wide_difficulty_type a_diffic = get_difficulty_for_next_block(blocks);
// Nonce search...
blk.nonce = 0;
while (!find_nounce(blk, blocks, a_diffic, height))
blk.timestamp++;
add_block(blk, txs_size, block_sizes, already_generated_coins, already_donated_coins, blocks.size() ? blocks.back()->cumul_difficulty + a_diffic: a_diffic);
return true;
}
currency::wide_difficulty_type test_generator::get_difficulty_for_next_block(const crypto::hash& head_id)
{
std::vector<const block_info*> blocks;
get_block_chain(blocks, head_id, std::numeric_limits<size_t>::max());
return get_difficulty_for_next_block(blocks);
}
currency::wide_difficulty_type test_generator::get_difficulty_for_next_block(const std::vector<const block_info*>& blocks)
{
std::vector<uint64_t> timestamps;
std::vector<wide_difficulty_type> commulative_difficulties;
size_t offset = blocks.size() - std::min(blocks.size(), static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT));
if(!offset)
++offset;//skip genesis block
for(; offset < blocks.size(); offset++)
{
timestamps.push_back(blocks[offset]->b.timestamp);
commulative_difficulties.push_back(blocks[offset]->cumul_difficulty);
}
return next_difficulty(timestamps, commulative_difficulties);
}
bool test_generator::find_nounce(block& blk, std::vector<const block_info*>& blocks, wide_difficulty_type dif, uint64_t height)
{
if(height != blocks.size())
throw std::runtime_error("wrong height in find_nounce");
std::vector<crypto::hash> scratchpad_local;
size_t count = 1;
for(auto& i: blocks)
{
push_block_scratchpad_data(i->b, scratchpad_local);
#ifdef ENABLE_HASHING_DEBUG
LOG_PRINT2("block_generation.log", "SCRATCHPAD_SHOT FOR H=" << count << ENDL << dump_scratchpad(scratchpad_local), LOG_LEVEL_3);
#endif
++count;
}
bool r = miner::find_nonce_for_given_block(blk, dif, height, [&](uint64_t index) -> crypto::hash&
{
return scratchpad_local[index%scratchpad_local.size()];
});
#ifdef ENABLE_HASHING_DEBUG
size_t call_no = 0;
std::stringstream ss;
crypto::hash pow = get_block_longhash(blk, height, [&](uint64_t index) -> crypto::hash&
{
ss << "[" << call_no << "][" << index << "%" << scratchpad_local.size() <<"(" << index%scratchpad_local.size() << ")]" << scratchpad_local[index%scratchpad_local.size()] << ENDL;
++call_no;
return scratchpad_local[index%scratchpad_local.size()];
});
LOG_PRINT2("block_generation.log", "ID: " << get_block_hash(blk) << "[" << height << "]" << ENDL << "POW:" << pow << ENDL << ss.str(), LOG_LEVEL_3);
#endif
return r;
}
bool test_generator::construct_block(currency::block& blk, const currency::account_base& miner_acc, uint64_t timestamp, const currency::alias_info& ai)
{
std::vector<size_t> block_sizes;
std::list<currency::transaction> tx_list;
return construct_block(blk, 0, null_hash, miner_acc, timestamp, 0, 0, block_sizes, tx_list, ai);
}
bool test_generator::construct_block(currency::block& blk, const currency::block& blk_prev,
const currency::account_base& miner_acc,
const std::list<currency::transaction>& tx_list, const currency::alias_info& ai)
{
uint64_t height = boost::get<txin_gen>(blk_prev.miner_tx.vin.front()).height + 1;
crypto::hash prev_id = get_block_hash(blk_prev);
// Keep push difficulty little up to be sure about PoW hash success
uint64_t timestamp = height > 10 ? blk_prev.timestamp + DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN: blk_prev.timestamp + DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN - DIFF_UP_TIMESTAMP_DELTA;
uint64_t already_generated_coins = get_already_generated_coins(prev_id);
uint64_t already_donated_coins = get_already_donated_coins(prev_id);
std::vector<size_t> block_sizes;
get_last_n_block_sizes(block_sizes, prev_id, CURRENCY_REWARD_BLOCKS_WINDOW);
return construct_block(blk, height, prev_id, miner_acc, timestamp, already_generated_coins, already_donated_coins, block_sizes, tx_list, ai);
}
bool test_generator::construct_block_manually(block& blk, const block& prev_block, const account_base& miner_acc,
int actual_params/* = bf_none*/, uint8_t major_ver/* = 0*/,
uint8_t minor_ver/* = 0*/, uint64_t timestamp/* = 0*/,
const crypto::hash& prev_id/* = crypto::hash()*/, const wide_difficulty_type& diffic/* = 1*/,
const transaction& miner_tx/* = transaction()*/,
const std::vector<crypto::hash>& tx_hashes/* = std::vector<crypto::hash>()*/,
size_t txs_sizes/* = 0*/)
{
size_t height = get_block_height(prev_block) + 1;
blk.flags = BLOCK_FLAGS_SUPPRESS_DONATION;
blk.major_version = actual_params & bf_major_ver ? major_ver : CURRENT_BLOCK_MAJOR_VERSION;
blk.minor_version = actual_params & bf_minor_ver ? minor_ver : CURRENT_BLOCK_MINOR_VERSION;
blk.timestamp = actual_params & bf_timestamp ? timestamp : (height > 10 ? prev_block.timestamp + DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN: prev_block.timestamp + DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN-DIFF_UP_TIMESTAMP_DELTA); // Keep difficulty unchanged
blk.prev_id = actual_params & bf_prev_id ? prev_id : get_block_hash(prev_block);
blk.tx_hashes = actual_params & bf_tx_hashes ? tx_hashes : std::vector<crypto::hash>();
uint64_t already_generated_coins = get_already_generated_coins(prev_block);
uint64_t already_donated_coins = get_already_donated_coins(get_block_hash(prev_block));
std::vector<size_t> block_sizes;
get_last_n_block_sizes(block_sizes, get_block_hash(prev_block), CURRENCY_REWARD_BLOCKS_WINDOW);
if (actual_params & bf_miner_tx)
{
blk.miner_tx = miner_tx;
}
else
{
size_t current_block_size = txs_sizes + get_object_blobsize(blk.miner_tx);
// TODO: This will work, until size of constructed block is less then CURRENCY_BLOCK_GRANTED_FULL_REWARD_ZONE
if (!construct_miner_tx(height, misc_utils::median(block_sizes), already_generated_coins, current_block_size, 0, miner_acc.get_keys().m_account_address, blk.miner_tx, blobdata(), 1))
return false;
}
//blk.tree_root_hash = get_tx_tree_hash(blk);
std::vector<const block_info*> blocks;
get_block_chain(blocks, blk.prev_id, std::numeric_limits<size_t>::max());
wide_difficulty_type a_diffic = actual_params & bf_diffic ? diffic : get_difficulty_for_next_block(blocks);
find_nounce(blk, blocks, a_diffic, height);
add_block(blk, txs_sizes, block_sizes, already_generated_coins, already_donated_coins, blocks.size() ? blocks.back()->cumul_difficulty + a_diffic: a_diffic);
return true;
}
bool test_generator::construct_block_manually_tx(currency::block& blk, const currency::block& prev_block,
const currency::account_base& miner_acc,
const std::vector<crypto::hash>& tx_hashes, size_t txs_size)
{
return construct_block_manually(blk, prev_block, miner_acc, bf_tx_hashes, 0, 0, 0, crypto::hash(), 0, transaction(), tx_hashes, txs_size);
}
struct output_index {
const currency::txout_target_v out;
uint64_t amount;
size_t blk_height; // block height
size_t tx_no; // index of transaction in block
size_t out_no; // index of out in transaction
size_t idx;
bool spent;
const currency::block *p_blk;
const currency::transaction *p_tx;
output_index(const currency::txout_target_v &_out, uint64_t _a, size_t _h, size_t tno, size_t ono, const currency::block *_pb, const currency::transaction *_pt)
: out(_out), amount(_a), blk_height(_h), tx_no(tno), out_no(ono), idx(0), spent(false), p_blk(_pb), p_tx(_pt) { }
output_index(const output_index &other)
: out(other.out), amount(other.amount), blk_height(other.blk_height), tx_no(other.tx_no), out_no(other.out_no), idx(other.idx), spent(other.spent), p_blk(other.p_blk), p_tx(other.p_tx) { }
const std::string toString() const {
std::stringstream ss;
ss << "output_index{blk_height=" << blk_height
<< " tx_no=" << tx_no
<< " out_no=" << out_no
<< " amount=" << amount
<< " idx=" << idx
<< " spent=" << spent
<< "}";
return ss.str();
}
output_index& operator=(const output_index& other)
{
new(this) output_index(other);
return *this;
}
};
typedef std::map<uint64_t, std::vector<size_t> > map_output_t;
typedef std::map<uint64_t, std::vector<output_index> > map_output_idx_t;
typedef pair<uint64_t, size_t> outloc_t;
namespace
{
uint64_t get_inputs_amount(const vector<tx_source_entry> &s)
{
uint64_t r = 0;
BOOST_FOREACH(const tx_source_entry &e, s)
{
r += e.amount;
}
return r;
}
}
bool init_output_indices(map_output_idx_t& outs, std::map<uint64_t, std::vector<size_t> >& outs_mine, const std::vector<currency::block>& blockchain, const map_hash2tx_t& mtx, const currency::account_base& from) {
BOOST_FOREACH (const block& blk, blockchain) {
vector<const transaction*> vtx;
vtx.push_back(&blk.miner_tx);
BOOST_FOREACH(const crypto::hash &h, blk.tx_hashes) {
const map_hash2tx_t::const_iterator cit = mtx.find(h);
if (mtx.end() == cit)
throw std::runtime_error("block contains an unknown tx hash");
vtx.push_back(cit->second);
}
//vtx.insert(vtx.end(), blk.);
// TODO: add all other txes
for (size_t i = 0; i < vtx.size(); i++) {
const transaction &tx = *vtx[i];
for (size_t j = 0; j < tx.vout.size(); ++j) {
const tx_out &out = tx.vout[j];
output_index oi(out.target, out.amount, boost::get<txin_gen>(*blk.miner_tx.vin.begin()).height, i, j, &blk, vtx[i]);
if (2 == out.target.which()) { // out_to_key
outs[out.amount].push_back(oi);
size_t tx_global_idx = outs[out.amount].size() - 1;
outs[out.amount][tx_global_idx].idx = tx_global_idx;
// Is out to me?
if (is_out_to_acc(from.get_keys(), boost::get<txout_to_key>(out.target), get_tx_pub_key_from_extra(tx), j)) {
outs_mine[out.amount].push_back(tx_global_idx);
}
}
}
}
}
return true;
}
bool init_spent_output_indices(map_output_idx_t& outs, map_output_t& outs_mine, const std::vector<currency::block>& blockchain, const map_hash2tx_t& mtx, const currency::account_base& from) {
BOOST_FOREACH (const map_output_t::value_type &o, outs_mine) {
for (size_t i = 0; i < o.second.size(); ++i) {
output_index &oi = outs[o.first][o.second[i]];
// construct key image for this output
crypto::key_image img;
keypair in_ephemeral;
generate_key_image_helper(from.get_keys(), get_tx_pub_key_from_extra(*oi.p_tx), oi.out_no, in_ephemeral, img);
// lookup for this key image in the events vector
BOOST_FOREACH(auto& tx_pair, mtx) {
const transaction& tx = *tx_pair.second;
BOOST_FOREACH(const txin_v &in, tx.vin) {
if (typeid(txin_to_key) == in.type()) {
const txin_to_key &itk = boost::get<txin_to_key>(in);
if (itk.k_image == img) {
oi.spent = true;
}
}
}
}
}
}
return true;
}
bool fill_output_entries(std::vector<output_index>& out_indices,
size_t sender_out, size_t nmix, uint64_t& real_entry_idx,
std::vector<tx_source_entry::output_entry>& output_entries)
{
if (out_indices.size() <= nmix)
return false;
bool sender_out_found = false;
size_t rest = nmix;
for (size_t i = 0; i < out_indices.size() && (0 < rest || !sender_out_found); ++i)
{
const output_index& oi = out_indices[i];
if (oi.spent)
continue;
bool append = false;
if (i == sender_out)
{
append = true;
sender_out_found = true;
real_entry_idx = output_entries.size();
}
else if (0 < rest)
{
if(boost::get<txout_to_key>(oi.out).mix_attr == CURRENCY_TO_KEY_OUT_FORCED_NO_MIX || boost::get<txout_to_key>(oi.out).mix_attr > nmix+1)
continue;
--rest;
append = true;
}
if (append)
{
const txout_to_key& otk = boost::get<txout_to_key>(oi.out);
output_entries.push_back(tx_source_entry::output_entry(oi.idx, otk.key));
}
}
return 0 == rest && sender_out_found;
}
bool fill_tx_sources(std::vector<tx_source_entry>& sources, const std::vector<test_event_entry>& events,
const block& blk_head, const currency::account_base& from, uint64_t amount, size_t nmix, bool check_for_spends = true)
{
map_output_idx_t outs;
map_output_t outs_mine;
std::vector<currency::block> blockchain;
map_hash2tx_t mtx;
if (!find_block_chain(events, blockchain, mtx, get_block_hash(blk_head)))
return false;
if (!init_output_indices(outs, outs_mine, blockchain, mtx, from))
return false;
if(check_for_spends)
{
if (!init_spent_output_indices(outs, outs_mine, blockchain, mtx, from))
return false;
}
// Iterate in reverse is more efficiency
uint64_t sources_amount = 0;
bool sources_found = false;
BOOST_REVERSE_FOREACH(const map_output_t::value_type o, outs_mine)
{
for (size_t i = 0; i < o.second.size() && !sources_found; ++i)
{
size_t sender_out = o.second[i];
const output_index& oi = outs[o.first][sender_out];
if (oi.spent)
continue;
currency::tx_source_entry ts;
ts.amount = oi.amount;
ts.real_output_in_tx_index = oi.out_no;
ts.real_out_tx_key = get_tx_pub_key_from_extra(*oi.p_tx); // incoming tx public key
if (!fill_output_entries(outs[o.first], sender_out, nmix, ts.real_output, ts.outputs))
continue;
sources.push_back(ts);
sources_amount += ts.amount;
sources_found = amount <= sources_amount;
}
if (sources_found)
break;
}
return sources_found;
}
bool fill_tx_destination(tx_destination_entry &de, const currency::account_base &to, uint64_t amount) {
de.addr = to.get_keys().m_account_address;
de.amount = amount;
return true;
}
void fill_tx_sources_and_destinations(const std::vector<test_event_entry>& events, const block& blk_head,
const currency::account_base& from, const currency::account_base& to,
uint64_t amount, uint64_t fee, size_t nmix, std::vector<tx_source_entry>& sources,
std::vector<tx_destination_entry>& destinations,
bool check_for_spends)
{
sources.clear();
destinations.clear();
if (!fill_tx_sources(sources, events, blk_head, from, amount + fee, nmix, check_for_spends))
throw std::runtime_error("couldn't fill transaction sources");
tx_destination_entry de;
if (!fill_tx_destination(de, to, amount))
throw std::runtime_error("couldn't fill transaction destination");
destinations.push_back(de);
tx_destination_entry de_change;
uint64_t cache_back = get_inputs_amount(sources) - (amount + fee);
if (0 < cache_back)
{
if (!fill_tx_destination(de_change, from, cache_back))
throw std::runtime_error("couldn't fill transaction cache back destination");
destinations.push_back(de_change);
}
}
/*
void fill_nonce(currency::block& blk, const wide_difficulty_type& diffic, uint64_t height)
{
blk.nonce = 0;
while (!miner::find_nonce_for_given_block(blk, diffic, height))
blk.timestamp++;
}*/
bool construct_miner_tx_manually(size_t height, uint64_t already_generated_coins,
const account_public_address& miner_address, transaction& tx, uint64_t fee,
keypair* p_txkey/* = 0*/)
{
keypair txkey;
txkey = keypair::generate();
add_tx_pub_key_to_extra(tx, txkey.pub);
if (0 != p_txkey)
*p_txkey = txkey;
txin_gen in;
in.height = height;
tx.vin.push_back(in);
// This will work, until size of constructed block is less then CURRENCY_BLOCK_GRANTED_FULL_REWARD_ZONE
uint64_t block_reward;
uint64_t max_donation;
if (!get_block_reward(0, 0, already_generated_coins, 0, block_reward, max_donation))
{
LOG_PRINT_L0("Block is too big");
return false;
}
block_reward += fee;
crypto::key_derivation derivation;
crypto::public_key out_eph_public_key;
crypto::generate_key_derivation(miner_address.m_view_public_key, txkey.sec, derivation);
crypto::derive_public_key(derivation, 0, miner_address.m_spend_public_key, out_eph_public_key);
tx_out out;
out.amount = block_reward;
out.target = txout_to_key(out_eph_public_key);
tx.vout.push_back(out);
tx.version = CURRENT_TRANSACTION_VERSION;
tx.unlock_time = height + CURRENCY_MINED_MONEY_UNLOCK_WINDOW;
return true;
}
bool construct_tx_to_key(const std::vector<test_event_entry>& events, currency::transaction& tx, const block& blk_head,
const currency::account_base& from, const currency::account_base& to, uint64_t amount,
uint64_t fee, size_t nmix, uint8_t mix_attr, bool check_for_spends)
{
vector<tx_source_entry> sources;
vector<tx_destination_entry> destinations;
fill_tx_sources_and_destinations(events, blk_head, from, to, amount, fee, nmix, sources, destinations, check_for_spends);
return construct_tx(from.get_keys(), sources, destinations, tx, 0, mix_attr);<|fim▁hole|>
transaction construct_tx_with_fee(std::vector<test_event_entry>& events, const block& blk_head,
const account_base& acc_from, const account_base& acc_to, uint64_t amount, uint64_t fee)
{
transaction tx;
construct_tx_to_key(events, tx, blk_head, acc_from, acc_to, amount, fee, 0);
events.push_back(tx);
return tx;
}
uint64_t get_balance(const currency::account_base& addr, const std::vector<currency::block>& blockchain, const map_hash2tx_t& mtx) {
uint64_t res = 0;
std::map<uint64_t, std::vector<output_index> > outs;
std::map<uint64_t, std::vector<size_t> > outs_mine;
map_hash2tx_t confirmed_txs;
get_confirmed_txs(blockchain, mtx, confirmed_txs);
if (!init_output_indices(outs, outs_mine, blockchain, confirmed_txs, addr))
return false;
if (!init_spent_output_indices(outs, outs_mine, blockchain, confirmed_txs, addr))
return false;
BOOST_FOREACH (const map_output_t::value_type &o, outs_mine) {
for (size_t i = 0; i < o.second.size(); ++i) {
if (outs[o.first][o.second[i]].spent)
continue;
res += outs[o.first][o.second[i]].amount;
}
}
return res;
}
void get_confirmed_txs(const std::vector<currency::block>& blockchain, const map_hash2tx_t& mtx, map_hash2tx_t& confirmed_txs)
{
std::unordered_set<crypto::hash> confirmed_hashes;
BOOST_FOREACH(const block& blk, blockchain)
{
BOOST_FOREACH(const crypto::hash& tx_hash, blk.tx_hashes)
{
confirmed_hashes.insert(tx_hash);
}
}
BOOST_FOREACH(const auto& tx_pair, mtx)
{
if (0 != confirmed_hashes.count(tx_pair.first))
{
confirmed_txs.insert(tx_pair);
}
}
}
bool find_block_chain(const std::vector<test_event_entry>& events, std::vector<currency::block>& blockchain, map_hash2tx_t& mtx, const crypto::hash& head) {
std::unordered_map<crypto::hash, const block*> block_index;
BOOST_FOREACH(const test_event_entry& ev, events)
{
if (typeid(block) == ev.type())
{
const block* blk = &boost::get<block>(ev);
block_index[get_block_hash(*blk)] = blk;
}
else if (typeid(transaction) == ev.type())
{
const transaction& tx = boost::get<transaction>(ev);
mtx[get_transaction_hash(tx)] = &tx;
}
}
bool b_success = false;
crypto::hash id = head;
for (auto it = block_index.find(id); block_index.end() != it; it = block_index.find(id))
{
blockchain.push_back(*it->second);
id = it->second->prev_id;
if (null_hash == id)
{
b_success = true;
break;
}
}
reverse(blockchain.begin(), blockchain.end());
return b_success;
}
void test_chain_unit_base::register_callback(const std::string& cb_name, verify_callback cb)
{
m_callbacks[cb_name] = cb;
}
bool test_chain_unit_base::verify(const std::string& cb_name, currency::core& c, size_t ev_index, const std::vector<test_event_entry> &events)
{
auto cb_it = m_callbacks.find(cb_name);
if(cb_it == m_callbacks.end())
{
LOG_ERROR("Failed to find callback " << cb_name);
return false;
}
return cb_it->second(c, ev_index, events);
}<|fim▁end|> | } |
<|file_name|>test_redis.py<|end_file_name|><|fim▁begin|>from funtests import transport
class test_redis(transport.TransportCase):
transport = "redis"
prefix = "redis"
<|fim▁hole|> client = connection.channel().client
client.info()
def test_cant_connect_raises_connection_error(self):
conn = self.get_connection(port=65534)
self.assertRaises(conn.connection_errors, conn.connect)<|fim▁end|> | def after_connect(self, connection): |
<|file_name|>build.spec.ts<|end_file_name|><|fim▁begin|>import assert from 'assert';
import { describe, it } from 'mocha';
import { itsa, itsaField, ItsaSchema, itsaSchema } from "./itsa";
@itsaSchema()
class IDog extends ItsaSchema {
@itsaField(itsa.number().default(4))
legs:number;
}
@itsaSchema()
class IUser extends ItsaSchema {
@itsaField(itsa.string().default('Sunny'))
name:string;
@itsaField(IDog.schema)
dog:IDog;
}
describe('itsa', function() {
describe('build', function() {
it('creates an object using defaulted values', function() {
const schema = itsa.object({
a: itsa.number().above(4).default(10),
b: itsa.array(),
c: itsa.string().default('foo'),
d: itsa.any(null, itsa.default(99)),
});
assert.strictEqual(schema.build().a, 10);
assert.strictEqual(JSON.stringify(schema.build().b), '[]');
assert.strictEqual(schema.build().c, 'foo');
assert.strictEqual(schema.build().d, undefined);
});
it('applies defaults for attributed constructors', function() {
const user = new IUser();
assert.strictEqual(user.name, 'Sunny');
});
it('creates nested schemas too', function() {
const user = new IUser();
assert.strictEqual(user.name, 'Sunny');
assert.strictEqual(user.dog.legs, 4);
assert.strictEqual(JSON.stringify(user), `{"name":"Sunny","dog":{"legs":4}}`);
});
it('initializes sub objects', function() {
const schema = itsa.object({<|fim▁hole|> assert.strictEqual(JSON.stringify(schema.build()), `{"foo":{}}`);
});
it('initializes sub arrays', function() {
const schema = itsa.object({
foo: itsa.array(),
});
assert.strictEqual(JSON.stringify(schema.build()), `{"foo":[]}`);
});
it('does not use defaults inside of an `any` clause', function() {
const schema = itsa.object({
foo: itsa.any(itsa.object()),
});
assert.strictEqual(JSON.stringify(schema.build()), `{}`);
});
it('assigns overrides', function() {
const schema = itsa.object({
a: itsa.object(),
b: itsa.array(),
c: itsa.default('foo'),
});
const obj = schema.build({
b:[1],
c: 'bar',
d: 'z',
});
assert.strictEqual(JSON.stringify(obj), `{"a":{},"b":[1],"c":"bar","d":"z"}`);
});
});
});<|fim▁end|> | foo: itsa.object(),
}); |
<|file_name|>client_test.go<|end_file_name|><|fim▁begin|>// Copyright 2016 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package metricsdebug_test
import (
"errors"
"time"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
basetesting "github.com/juju/juju/api/base/testing"
"github.com/juju/juju/api/metricsdebug"
"github.com/juju/juju/apiserver/common"
"github.com/juju/juju/apiserver/params"
jujutesting "github.com/juju/juju/juju/testing"
"github.com/juju/juju/state"
"github.com/juju/juju/testing"
"github.com/juju/juju/testing/factory"
)
type metricsdebugSuiteMock struct {
testing.BaseSuite
manager *metricsdebug.Client
}
var _ = gc.Suite(&metricsdebugSuiteMock{})
func (s *metricsdebugSuiteMock) TestGetMetrics(c *gc.C) {
var called bool
now := time.Now()
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
a, response interface{},
) error {
c.Assert(request, gc.Equals, "GetMetrics")
result := response.(*params.MetricResults)
result.Results = []params.EntityMetrics{{
Metrics: []params.MetricResult{{
Key: "pings",
Value: "5",
Time: now,
}},
Error: nil,
}}
called = true
return nil
})
client := metricsdebug.NewClient(apiCaller)
metrics, err := client.GetMetrics("unit-wordpress/0")
c.Assert(err, jc.ErrorIsNil)
c.Assert(called, jc.IsTrue)
c.Assert(metrics, gc.HasLen, 1)
c.Assert(metrics[0].Key, gc.Equals, "pings")
c.Assert(metrics[0].Value, gc.Equals, "5")
c.Assert(metrics[0].Time, gc.Equals, now)
}
func (s *metricsdebugSuiteMock) TestGetMetricsFails(c *gc.C) {
var called bool
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
a, response interface{},
) error {
c.Assert(request, gc.Equals, "GetMetrics")
result := response.(*params.MetricResults)
result.Results = []params.EntityMetrics{{
Error: common.ServerError(errors.New("an error")),
}}
called = true
return nil
})
client := metricsdebug.NewClient(apiCaller)
metrics, err := client.GetMetrics("unit-wordpress/0")
c.Assert(err, gc.ErrorMatches, "an error")
c.Assert(metrics, gc.IsNil)
c.Assert(called, jc.IsTrue)
}
func (s *metricsdebugSuiteMock) TestGetMetricsFacadeCallError(c *gc.C) {
var called bool
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
a, result interface{},
) error {
called = true
return errors.New("an error")
})
client := metricsdebug.NewClient(apiCaller)
metrics, err := client.GetMetrics("unit-wordpress/0")
c.Assert(err, gc.ErrorMatches, "an error")
c.Assert(metrics, gc.IsNil)
c.Assert(called, jc.IsTrue)
}
func (s *metricsdebugSuiteMock) TestGetMetricsForModel(c *gc.C) {
var called bool
now := time.Now()
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
requestParam, response interface{},
) error {
c.Assert(request, gc.Equals, "GetMetrics")
entities := requestParam.(params.Entities)
c.Assert(entities, gc.DeepEquals, params.Entities{Entities: []params.Entity{}})
result := response.(*params.MetricResults)
result.Results = []params.EntityMetrics{{
Metrics: []params.MetricResult{{
Key: "pings",
Value: "5",
Time: now,
}},
Error: nil,
}}
called = true
return nil
})
client := metricsdebug.NewClient(apiCaller)
metrics, err := client.GetMetrics()
c.Assert(err, jc.ErrorIsNil)
c.Assert(called, jc.IsTrue)
c.Assert(metrics, gc.HasLen, 1)
c.Assert(metrics[0].Key, gc.Equals, "pings")
c.Assert(metrics[0].Value, gc.Equals, "5")
c.Assert(metrics[0].Time, gc.Equals, now)
}
func (s *metricsdebugSuiteMock) TestGetMetricsForModelFails(c *gc.C) {
var called bool
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
requestParam, response interface{},
) error {
called = true
return errors.New("an error")
})
client := metricsdebug.NewClient(apiCaller)
metrics, err := client.GetMetrics()
c.Assert(called, jc.IsTrue)
c.Assert(metrics, gc.IsNil)
c.Assert(err, gc.ErrorMatches, "an error")
}
func (s *metricsdebugSuiteMock) TestSetMeterStatus(c *gc.C) {
var called bool
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
a, response interface{},
) error {
c.Assert(request, gc.Equals, "SetMeterStatus")
c.Assert(a, gc.DeepEquals, params.MeterStatusParams{
Statuses: []params.MeterStatusParam{{
Tag: "unit-metered/0",
Code: "RED",
Info: "test"},
},
})
result := response.(*params.ErrorResults)
result.Results = []params.ErrorResult{{
Error: nil,
}}
called = true
return nil
})
client := metricsdebug.NewClient(apiCaller)
err := client.SetMeterStatus("unit-metered/0", "RED", "test")
c.Assert(err, jc.ErrorIsNil)
c.Assert(called, jc.IsTrue)
}
func (s *metricsdebugSuiteMock) TestSetMeterStatusAPIServerError(c *gc.C) {
var called bool
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
a, response interface{},
) error {
c.Assert(request, gc.Equals, "SetMeterStatus")
c.Assert(a, gc.DeepEquals, params.MeterStatusParams{
Statuses: []params.MeterStatusParam{{
Tag: "unit-metered/0",
Code: "RED",
Info: "test"},
},
})
result := response.(*params.ErrorResults)
result.Results = []params.ErrorResult{{
Error: common.ServerError(errors.New("an error")),
}}
called = true
return nil
})
client := metricsdebug.NewClient(apiCaller)
err := client.SetMeterStatus("unit-metered/0", "RED", "test")
c.Assert(err, gc.ErrorMatches, "an error")
c.Assert(called, jc.IsTrue)
}
func (s *metricsdebugSuiteMock) TestSetMeterStatusFacadeCallError(c *gc.C) {
var called bool
apiCaller := basetesting.APICallerFunc(
func(objType string,
version int,
id, request string,
a, response interface{},
) error {
called = true
return errors.New("an error")
})
client := metricsdebug.NewClient(apiCaller)
err := client.SetMeterStatus("unit-metered/0", "RED", "test")
c.Assert(err, gc.ErrorMatches, "an error")
c.Assert(called, jc.IsTrue)
}
type metricsdebugSuite struct {
jujutesting.JujuConnSuite
manager *metricsdebug.Client
}
var _ = gc.Suite(&metricsdebugSuite{})
func (s *metricsdebugSuite) SetUpTest(c *gc.C) {
s.JujuConnSuite.SetUpTest(c)
s.manager = metricsdebug.NewClient(s.APIState)
c.Assert(s.manager, gc.NotNil)
}
func assertSameMetric(c *gc.C, a params.MetricResult, b *state.MetricBatch) {
c.Assert(a.Key, gc.Equals, b.Metrics()[0].Key)
c.Assert(a.Value, gc.Equals, b.Metrics()[0].Value)
c.Assert(a.Time, jc.TimeBetween(b.Metrics()[0].Time, b.Metrics()[0].Time))
}
func (s *metricsdebugSuite) TestFeatureGetMetrics(c *gc.C) {
meteredCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "local:quantal/metered-1"})
meteredService := s.Factory.MakeApplication(c, &factory.ApplicationParams{Charm: meteredCharm})
unit := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
metric := s.Factory.MakeMetric(c, &factory.MetricParams{Unit: unit})
metrics, err := s.manager.GetMetrics("unit-metered/0")
c.Assert(err, jc.ErrorIsNil)
c.Assert(metrics, gc.HasLen, 1)
assertSameMetric(c, metrics[0], metric)
}
func (s *metricsdebugSuite) TestFeatureGetMultipleMetrics(c *gc.C) {
meteredCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "local:quantal/metered-1"})
meteredService := s.Factory.MakeApplication(c, &factory.ApplicationParams{
Charm: meteredCharm,
})
unit0 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
unit1 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
metricUnit0 := s.Factory.MakeMetric(c, &factory.MetricParams{
Unit: unit0,
})
metricUnit1 := s.Factory.MakeMetric(c, &factory.MetricParams{
Unit: unit1,
})
metrics0, err := s.manager.GetMetrics("unit-metered/0")
c.Assert(err, jc.ErrorIsNil)
c.Assert(metrics0, gc.HasLen, 1)
assertSameMetric(c, metrics0[0], metricUnit0)
metrics1, err := s.manager.GetMetrics("unit-metered/1")
c.Assert(err, jc.ErrorIsNil)
c.Assert(metrics1, gc.HasLen, 1)
assertSameMetric(c, metrics1[0], metricUnit1)
metrics2, err := s.manager.GetMetrics("unit-metered/0", "unit-metered/1")
c.Assert(err, jc.ErrorIsNil)
c.Assert(metrics2, gc.HasLen, 2)<|fim▁hole|>
func (s *metricsdebugSuite) TestFeatureGetMetricsForModel(c *gc.C) {
meteredCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "local:quantal/metered-1"})
meteredService := s.Factory.MakeApplication(c, &factory.ApplicationParams{
Charm: meteredCharm,
})
unit0 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
unit1 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
metricUnit0 := s.Factory.MakeMetric(c, &factory.MetricParams{
Unit: unit0,
})
metricUnit1 := s.Factory.MakeMetric(c, &factory.MetricParams{
Unit: unit1,
})
metrics, err := s.manager.GetMetrics()
c.Assert(err, jc.ErrorIsNil)
c.Assert(metrics, gc.HasLen, 2)
assertSameMetric(c, metrics[0], metricUnit0)
assertSameMetric(c, metrics[1], metricUnit1)
}
func (s *metricsdebugSuite) TestFeatureGetMultipleMetricsWithService(c *gc.C) {
meteredCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "local:quantal/metered-1"})
meteredService := s.Factory.MakeApplication(c, &factory.ApplicationParams{
Charm: meteredCharm,
})
unit0 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
unit1 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: meteredService, SetCharmURL: true})
metricUnit0 := s.Factory.MakeMetric(c, &factory.MetricParams{
Unit: unit0,
})
metricUnit1 := s.Factory.MakeMetric(c, &factory.MetricParams{
Unit: unit1,
})
metrics, err := s.manager.GetMetrics("application-metered")
c.Assert(err, jc.ErrorIsNil)
c.Assert(metrics, gc.HasLen, 2)
assertSameMetric(c, metrics[0], metricUnit0)
assertSameMetric(c, metrics[1], metricUnit1)
}
func (s *metricsdebugSuite) TestSetMeterStatus(c *gc.C) {
testCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "local:quantal/metered-1"})
testService := s.Factory.MakeApplication(c, &factory.ApplicationParams{Charm: testCharm})
testUnit1 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: testService, SetCharmURL: true})
testUnit2 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: testService, SetCharmURL: true})
csCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "cs:quantal/metered-1"})
csService := s.Factory.MakeApplication(c, &factory.ApplicationParams{Name: "cs-service", Charm: csCharm})
csUnit1 := s.Factory.MakeUnit(c, &factory.UnitParams{Application: csService, SetCharmURL: true})
tests := []struct {
about string
tag string
code string
info string
err string
assert func(*gc.C)
}{{
about: "set service meter status",
tag: testService.Tag().String(),
code: "RED",
info: "test",
assert: func(c *gc.C) {
ms1, err := testUnit1.GetMeterStatus()
c.Assert(err, jc.ErrorIsNil)
c.Assert(ms1, gc.DeepEquals, state.MeterStatus{
Code: state.MeterRed,
Info: "test",
})
ms2, err := testUnit2.GetMeterStatus()
c.Assert(err, jc.ErrorIsNil)
c.Assert(ms2, gc.DeepEquals, state.MeterStatus{
Code: state.MeterRed,
Info: "test",
})
},
}, {
about: "set unit meter status",
tag: testUnit1.Tag().String(),
code: "AMBER",
info: "test",
assert: func(c *gc.C) {
ms1, err := testUnit1.GetMeterStatus()
c.Assert(err, jc.ErrorIsNil)
c.Assert(ms1, gc.DeepEquals, state.MeterStatus{
Code: state.MeterAmber,
Info: "test",
})
},
}, {
about: "not a local charm - service",
tag: csService.Tag().String(),
code: "AMBER",
info: "test",
err: "not a local charm",
}, {
about: "not a local charm - unit",
tag: csUnit1.Tag().String(),
code: "AMBER",
info: "test",
err: "not a local charm",
}, {
about: "invalid meter status",
tag: testUnit1.Tag().String(),
code: "WRONG",
info: "test",
err: "invalid meter status \"NOT AVAILABLE\"",
}, {
about: "not such service",
tag: "application-missing",
code: "AMBER",
info: "test",
err: "application \"missing\" not found",
},
}
for i, test := range tests {
c.Logf("running test %d: %v", i, test.about)
err := s.manager.SetMeterStatus(test.tag, test.code, test.info)
if test.err == "" {
c.Assert(err, jc.ErrorIsNil)
test.assert(c)
} else {
c.Assert(err, gc.ErrorMatches, test.err)
}
}
}<|fim▁end|> | } |
<|file_name|>s3table.py<|end_file_name|><|fim▁begin|>from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import *
import boto.exception
import io
import json
import wizzat.kvtable
from boto.s3.key import Key, compute_md5
__all__ = [
'S3Table',
]
class S3Table(wizzat.kvtable.KVTable):
"""
This is a micro-ORM for working with S3.
Relevant options (on top of KVTable options):
- bucket: The S3 bucket name to store this table in
- json_encoder: func, the json encoder (typically, staticmethod(json.dumps))
- json_encoder: func, the json decoder (typically, staticmethod(json.loads))
- reduced_redundancy: bool, Whether or not to store the key with S3 reduced redundancy
- encrypt_key: bool, Use S3 encryption
- policy: CannedACLStrings, The S3 policy to apply to new objects in S3
"""
memoize = False
table_name = ''
key_fields = []
fields = []
bucket = None
policy = None
encrypt_key = False
reduced_redundancy = False
json_encoder = staticmethod(json.dumps)
json_decoder = staticmethod(json.loads)
@classmethod
def _remote_bucket(cls):
return cls.conn.get_bucket(cls.bucket)
@classmethod
def delete_key(cls, kv_key):
cls._remote_bucket().delete_key(kv_key)
@classmethod
def _remote_key(cls, kv_key):
return Key(cls._remote_bucket(), kv_key)
@classmethod
def _find_by_key(cls, kv_key):
try:
content_str = cls._remote_key(kv_key).get_contents_as_string()
if not isinstance(content_str, str):
content_str = content_str.decode()
return True, cls.json_decoder(content_str)
except boto.exception.S3ResponseError:
return None, None
def _insert(self, force=False):
content_str = self.json_encoder(self._data)
if not isinstance(content_str, str):<|fim▁hole|> content_str = content_str.decode()
md5, b64, file_size = compute_md5(io.StringIO(content_str))
self._remote_key(self._key).set_contents_from_string(content_str,
md5 = (md5, b64, file_size),
policy = self.policy,
encrypt_key = self.encrypt_key,
reduced_redundancy = self.reduced_redundancy,
)
return True
_update = _insert
def _delete(self, force=False):
self.delete_key(self._key)
return False<|fim▁end|> | |
<|file_name|>htmldatalistelement.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 dom::bindings::codegen::Bindings::HTMLDataListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods;
use dom::bindings::codegen::InheritTypes::{HTMLDataListElementDerived, HTMLOptionElementDerived};
use dom::bindings::codegen::InheritTypes::NodeCast;
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::element::Element;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlcollection::{HTMLCollection, CollectionFilter};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId, window_from_node};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLDataListElement {
htmlelement: HTMLElement
}
impl HTMLDataListElementDerived for EventTarget {
fn is_htmldatalistelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLDataListElement)))<|fim▁hole|> fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLDataListElement {
HTMLDataListElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLDataListElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLDataListElement> {
let element = HTMLDataListElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLDataListElementBinding::Wrap)
}
}
impl<'a> HTMLDataListElementMethods for JSRef<'a, HTMLDataListElement> {
fn Options(self) -> Temporary<HTMLCollection> {
#[jstraceable]
struct HTMLDataListOptionsFilter;
impl CollectionFilter for HTMLDataListOptionsFilter {
fn filter(&self, elem: JSRef<Element>, _root: JSRef<Node>) -> bool {
elem.is_htmloptionelement()
}
}
let node: JSRef<Node> = NodeCast::from_ref(self);
let filter = box HTMLDataListOptionsFilter;
let window = window_from_node(node).root();
HTMLCollection::create(window.r(), node, filter)
}
}<|fim▁end|> | }
}
impl HTMLDataListElement { |
<|file_name|>CubeBsqHandler.cpp<|end_file_name|><|fim▁begin|>/**
* @file
* $Revision: 1.6 $
* $Date: 2008/09/03 16:21:02 $
*
* Unless noted otherwise, the portions of Isis written by the USGS are
* public domain. See individual third-party library and package descriptions
* for intellectual property information, user agreements, and related
* information.
*
* Although Isis has been used by the USGS, no warranty, expressed or
* implied, is made by the USGS as to the accuracy and functioning of such
* software and related material nor shall the fact of distribution
* constitute any such warranty, and no responsibility is assumed by the
* USGS in connection therewith.
*
* For additional information, launch
* $ISISROOT/doc//documents/Disclaimers/Disclaimers.html
* in a browser or see the Privacy & Disclaimers page on the Isis website,
* http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on
* http://www.usgs.gov/privacy.html.
*/
#include "CubeBsqHandler.h"
#include <iostream>
#include <QFile>
#include "IException.h"
#include "Pvl.h"
#include "PvlKeyword.h"
#include "PvlObject.h"
#include "RawCubeChunk.h"
using namespace std;
namespace Isis {
/**
* Construct a BSQ IO handler. This will determine a good chunk size to use
* that does not result in the cube being enlarged or misordered.
*
* @param dataFile The file with cube DN data in it
* @param virtualBandList The mapping from virtual band to physical band, see
* CubeIoHandler's description.
* @param labels The Pvl labels for the cube
* @param alreadyOnDisk True if the cube is allocated on the disk, false
* otherwise
*/
CubeBsqHandler::CubeBsqHandler(QFile * dataFile,
const QList<int> *virtualBandList, const Pvl &labels, bool alreadyOnDisk)
: CubeIoHandler(dataFile, virtualBandList, labels, alreadyOnDisk) {
int numSamplesInChunk = sampleCount();
int numLinesInChunk = 1;
// The chunk size must evenly divide into the cube size...
if(lineCount() < 1024)
numLinesInChunk = lineCount();
else {
int attemptedSize = 1024;
while(numLinesInChunk == 1 && attemptedSize > 1) {
if(lineCount() % attemptedSize == 0)
numLinesInChunk = attemptedSize;
else
attemptedSize /= 2;
}
}
setChunkSizes(numSamplesInChunk, numLinesInChunk, 1);
}
/**
* The destructor writes all cached data to disk.
*/
CubeBsqHandler::~CubeBsqHandler() {
clearCache();
}
void CubeBsqHandler::updateLabels(Pvl &label) {
PvlObject &core = label.findObject("IsisCube").findObject("Core");
core.addKeyword(PvlKeyword("Format", "BandSequential"),
PvlContainer::Replace);
}
void CubeBsqHandler::readRaw(RawCubeChunk &chunkToFill) {
BigInt startByte = getChunkStartByte(chunkToFill);
bool success = false;
QFile * dataFile = getDataFile();
if(dataFile->seek(startByte)) {
QByteArray binaryData = dataFile->read(chunkToFill.getByteCount());
if(binaryData.size() == chunkToFill.getByteCount()) {
chunkToFill.setRawData(binaryData);
success = true;
}
}
if(!success) {
IString msg = "Reading from the file [" + dataFile->fileName() + "] "
"failed with reading [" +
QString::number(chunkToFill.getByteCount()) +
"] bytes at position [" + QString::number(startByte) + "]";
throw IException(IException::Io, msg, _FILEINFO_);
}
}
<|fim▁hole|> void CubeBsqHandler::writeRaw(const RawCubeChunk &chunkToWrite) {
BigInt startByte = getChunkStartByte(chunkToWrite);
bool success = false;
QFile * dataFile = getDataFile();
if(dataFile->seek(startByte)) {
BigInt dataWritten = dataFile->write(chunkToWrite.getRawData());
if(dataWritten == chunkToWrite.getByteCount()) {
success = true;
}
}
if(!success) {
IString msg = "Writing to the file [" + dataFile->fileName() + "] "
"failed with writing [" +
QString::number(chunkToWrite.getByteCount()) +
"] bytes at position [" + QString::number(startByte) + "]";
throw IException(IException::Io, msg, _FILEINFO_);
}
}
/**
* This is a helper method that goes from chunk to file position.
*
* @param chunk The chunk to locate in the file.
* @return The file position to start reading or writing at
*/
BigInt CubeBsqHandler::getChunkStartByte(const RawCubeChunk &chunk) const {
return getDataStartByte() + getChunkIndex(chunk) * getBytesPerChunk();
}
}<|fim▁end|> | |
<|file_name|>AvroParser.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2009 Swedish Institute of Computer Science (SICS) Copyright (C)
* 2009 Royal Institute of Technology (KTH)
*
* KompicsToolbox is free software; you can redistribute it and/or<|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 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.
*/
package se.sics.nstream.hops.kafka.avro;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.buffer.Unpooled;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.generic.GenericRecordBuilder;
import org.apache.avro.io.BinaryDecoder;
import org.apache.avro.io.BinaryEncoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.EncoderFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Alex Ormenisan <[email protected]>
*/
public class AvroParser {
private static final Logger LOG = LoggerFactory.getLogger(AvroParser.class);
public static GenericRecord blobToAvro(Schema schema, ByteBuf data) {
int readPos = data.readerIndex();
GenericDatumReader<GenericRecord> reader = new GenericDatumReader<>(schema);
try (InputStream in = new ByteBufInputStream(data)) {
BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(in, null);
try {
GenericRecord record = reader.read(null, decoder);
readPos = data.readerIndex() - decoder.inputStream().available();
data.readerIndex(readPos);
return record;
} catch (EOFException ex) {
data.readerIndex(readPos);
return null;
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static List<GenericRecord> blobToAvroList(Schema schema, InputStream in) {
List<GenericRecord> records = new ArrayList<>();
GenericDatumReader<GenericRecord> reader = new GenericDatumReader<>(schema);
BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(in, null);
try {
while (true) {
GenericRecord record = reader.read(null, decoder);
records.add(record);
}
} catch (EOFException ex) {
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return records;
}
public static byte[] avroToBlob(Schema schema, GenericRecord record) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema);
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
try {
writer.write(record, encoder);
encoder.flush();
} catch (Exception ex) {
throw new RuntimeException("hmmm", ex);
}
byte[] bData = out.toByteArray();
return bData;
}
public static byte[] nAvroToBlob(Schema schema, int nrMsgs, Random rand) {
ByteBuf buf = Unpooled.buffer();
OutputStream out = new ByteBufOutputStream(buf);
GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema);
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
GenericRecordBuilder grb;
for (int i = 0; i < nrMsgs; i++) {
grb = new GenericRecordBuilder(schema);
for (Schema.Field field : schema.getFields()) {
//TODO Alex - I assume each field is a string
grb.set(field, "val" + (1000 + rand.nextInt(1000)));
}
try {
writer.write(grb.build(), encoder);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
try {
encoder.flush();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
byte[] result = new byte[buf.writerIndex()];
buf.readBytes(result);
return result;
}
}<|fim▁end|> | * 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. |
<|file_name|>lib.ts<|end_file_name|><|fim▁begin|>import * as Q from 'q'
<|fim▁hole|><|fim▁end|> | export {Q} |
<|file_name|>OrTest.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2005 JBoss 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 org.drools.modelcompiler;
import java.util.ArrayList;
import java.util.List;
import org.assertj.core.api.Assertions;
import org.drools.modelcompiler.domain.Address;
import org.drools.modelcompiler.domain.Employee;
import org.drools.modelcompiler.domain.Person;
import org.junit.Test;
import org.kie.api.builder.Results;
import org.kie.api.runtime.KieSession;
import static org.drools.modelcompiler.domain.Employee.createEmployee;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class OrTest extends BaseModelTest {
public OrTest( RUN_TYPE testRunType ) {
super( testRunType );
}
@Test
public void testOr() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"rule R when\n" +
" $p : Person(name == \"Mark\") or\n" +
" ( $mark : Person(name == \"Mark\")\n" +
" and\n" +
" $p : Person(age > $mark.age) )\n" +
" $s: String(this == $p.name)\n" +
"then\n" +
" System.out.println(\"Found: \" + $s);\n" +
"end";
KieSession ksession = getKieSession( str );
ksession.insert( "Mario" );
ksession.insert( new Person( "Mark", 37 ) );
ksession.insert( new Person( "Edson", 35 ) );
ksession.insert( new Person( "Mario", 40 ) );
assertEquals(1, ksession.fireAllRules());
}
@Test
public void testOrWhenStringFirst() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"import " + Address.class.getCanonicalName() + ";" +
"rule R when\n" +
" $s : String(this == \"Go\")\n" +
" ( Person(name == \"Mark\") or \n" +
" (\n" +
" Person(name == \"Mario\") and\n" +
" Address(city == \"London\") ) )\n" +
"then\n" +
" System.out.println(\"Found: \" + $s.getClass());\n" +
"end";
KieSession ksession = getKieSession( str );
ksession.insert( "Go" );
ksession.insert( new Person( "Mark", 37 ) );
ksession.insert( new Person( "Mario", 100 ) );
ksession.insert( new Address( "London" ) );
assertEquals(2, ksession.fireAllRules());
}
@Test
public void testOrWithBetaIndex() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"rule R when\n" +
" $p : Person(name == \"Mark\") or\n" +
" ( $mark : Person(name == \"Mark\")\n" +
" and\n" +
" $p : Person(age == $mark.age) )\n" +
" $s: String(this == $p.name)\n" +
"then\n" +
" System.out.println(\"Found: \" + $s);\n" +
"end";
KieSession ksession = getKieSession(str);
ksession.insert("Mario");
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 37));
assertEquals(1, ksession.fireAllRules());
}
@Test
public void testOrWithBetaIndexOffset() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"rule R when\n" +
" $e : Person(name == \"Edson\")\n" +
" $p : Person(name == \"Mark\") or\n" +
" ( $mark : Person(name == \"Mark\")\n" +
" and\n" +
" $p : Person(age == $mark.age) )\n" +
" $s: String(this == $p.name)\n" +
"then\n" +
" System.out.println(\"Found: \" + $s);\n" +
"end";
KieSession ksession = getKieSession(str);
ksession.insert("Mario");
ksession.insert(new Person("Mark", 37));
ksession.insert(new Person("Edson", 35));
ksession.insert(new Person("Mario", 37));
assertEquals(1, ksession.fireAllRules());
}
@Test
public void testOrConditional() {
final String drl =
"import " + Employee.class.getCanonicalName() + ";" +
"import " + Address.class.getCanonicalName() + ";" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Employee( $address: address, address.city == 'Big City' )\n" +
" or " +
" Employee( $address: address, address.city == 'Small City' )\n" +
"then\n" +
" list.add( $address.getCity() );\n" +
"end\n";
KieSession kieSession = getKieSession(drl);
List<String> results = new ArrayList<>();
kieSession.setGlobal("list", results);
final Employee bruno = createEmployee("Bruno", new Address("Elm", 10, "Small City"));
kieSession.insert(bruno);
final Employee alice = createEmployee("Alice", new Address("Elm", 10, "Big City"));
kieSession.insert(alice);
kieSession.fireAllRules();
Assertions.assertThat(results).containsExactlyInAnyOrder("Big City", "Small City");
}
@Test
public void testOrConstraint() {
final String drl =
"import " + Employee.class.getCanonicalName() + ";" +
"import " + Address.class.getCanonicalName() + ";" +
"global java.util.List list\n" +
"\n" +
"rule R when\n" +
" Employee( $address: address, ( address.city == 'Big City' || address.city == 'Small City' ) )\n" +
"then\n" +
" list.add( $address.getCity() );\n" +
"end\n";
KieSession kieSession = getKieSession(drl);
List<String> results = new ArrayList<>();
kieSession.setGlobal("list", results);
final Employee bruno = createEmployee("Bruno", new Address("Elm", 10, "Small City"));
kieSession.insert(bruno);
final Employee alice = createEmployee("Alice", new Address("Elm", 10, "Big City"));
kieSession.insert(alice);
kieSession.fireAllRules();
Assertions.assertThat(results).containsExactlyInAnyOrder("Big City", "Small City");
}
@Test
public void testOrWithDuplicatedVariables() {
String str =
"import " + Person.class.getCanonicalName() + ";" +
"global java.util.List list\n" +
"\n" +
"rule R1 when\n" +
" Person( $name: name == \"Mark\", $age: age ) or\n" +
" Person( $name: name == \"Mario\", $age : age )\n" +
"then\n" +
" list.add( $name + \" is \" + $age);\n" +
"end\n" +
"rule R2 when\n" +
" $p: Person( name == \"Mark\", $age: age ) or\n" +
" $p: Person( name == \"Mario\", $age : age )\n" +
"then\n" +
" list.add( $p + \" has \" + $age + \" years\");\n" +
"end\n";
KieSession ksession = getKieSession( str );
List<String> results = new ArrayList<>();<|fim▁hole|> ksession.insert( new Person( "Mark", 37 ) );
ksession.insert( new Person( "Edson", 35 ) );
ksession.insert( new Person( "Mario", 40 ) );
ksession.fireAllRules();
assertEquals(4, results.size());
assertTrue(results.contains("Mark is 37"));
assertTrue(results.contains("Mark has 37 years"));
assertTrue(results.contains("Mario is 40"));
assertTrue(results.contains("Mario has 40 years"));
}
@Test
public void generateErrorForEveryFieldInRHSNotDefinedInLHS() {
// JBRULES-3390
final String drl1 = "package org.drools.compiler.integrationtests.operators; \n" +
"declare B\n" +
" field : int\n" +
"end\n" +
"declare C\n" +
" field : int\n" +
"end\n" +
"rule R when\n" +
"( " +
" ( B( $bField : field ) or C( $cField : field ) ) " +
")\n" +
"then\n" +
" System.out.println($bField);\n" +
"end\n";
Results results = getCompilationResults(drl1);
assertFalse(results.getMessages().isEmpty());
}
private Results getCompilationResults( String drl ) {
return createKieBuilder( drl ).getResults();
}
}<|fim▁end|> | ksession.setGlobal("list", results);
|
<|file_name|>test_aggregate_image_properties_isolation.py<|end_file_name|><|fim▁begin|># Copyright (c) 2014 Cisco Systems, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
from nova.scheduler import solvers
from nova.scheduler.solvers.constraints import \
aggregate_image_properties_isolation
from nova import test
from nova.tests.scheduler import solver_scheduler_fakes as fakes
class TestAggregateImagePropertiesIsolationConstraint(test.NoDBTestCase):
def setUp(self):
super(TestAggregateImagePropertiesIsolationConstraint, self).setUp()<|fim▁hole|> self.constraint_cls = aggregate_image_properties_isolation.\
AggregateImagePropertiesIsolationConstraint
self._generate_fake_constraint_input()
def _generate_fake_constraint_input(self):
self.fake_variables = solvers.BaseVariables()
self.fake_variables.host_instance_matrix = [
['h0i0', 'h0i1', 'h0i2'],
['h1i0', 'h1i1', 'h1i2']]
self.fake_filter_properties = {
'instance_uuids': ['fake_uuid_%s' % x for x in range(3)],
'num_instances': 3}
host1 = fakes.FakeSolverSchedulerHostState('host1', 'node1', {})
host2 = fakes.FakeSolverSchedulerHostState('host2', 'node1', {})
self.fake_hosts = [host1, host2]
@mock.patch('nova.scheduler.solvers.constraints.'
'aggregate_image_properties_isolation.'
'AggregateImagePropertiesIsolationConstraint.host_filter_cls')
def test_aggregate_image_properties_isolation_get_components(
self, mock_filter_cls):
expected_cons_vars = [['h1i0'], ['h1i1'], ['h1i2']]
expected_cons_coeffs = [[1], [1], [1]]
expected_cons_consts = [0, 0, 0]
expected_cons_ops = ['==', '==', '==']
mock_filter = mock_filter_cls.return_value
mock_filter.host_passes.side_effect = [True, False]
cons_vars, cons_coeffs, cons_consts, cons_ops = (
self.constraint_cls().get_components(self.fake_variables,
self.fake_hosts, self.fake_filter_properties))
self.assertEqual(expected_cons_vars, cons_vars)
self.assertEqual(expected_cons_coeffs, cons_coeffs)
self.assertEqual(expected_cons_consts, cons_consts)
self.assertEqual(expected_cons_ops, cons_ops)<|fim▁end|> | |
<|file_name|>insert_usage_mysql.rs<|end_file_name|><|fim▁begin|>use chrono::{offset::Utc, DateTime};
use rustorm::{pool, DbError, FromDao, Pool, ToColumnNames, ToDao, ToTableName};
/// Run using:
/// ```sh
/// cargo run --example insert_usage_mysql --features "with-mysql"
/// ```
fn main() {
mod for_insert {
use super::*;
#[derive(Debug, PartialEq, ToDao, ToColumnNames, ToTableName)]
pub struct Actor {
pub first_name: String,
pub last_name: String,
}
}
mod for_retrieve {
use super::*;
#[derive(Debug, FromDao, ToColumnNames, ToTableName)]
pub struct Actor {
pub actor_id: i32,
pub first_name: String,
pub last_name: String,
pub last_update: DateTime<Utc>,
}
}
let db_url = "mysql://root:r00tpwdh3r3@localhost/sakila";
let mut pool = Pool::new();
pool.ensure(db_url);
let mut em = pool.em(db_url).expect("Can not connect");
let tom_cruise = for_insert::Actor {
first_name: "TOM".into(),
last_name: "CRUISE".to_string(),
};<|fim▁hole|> first_name: "TOM".into(),
last_name: "HANKS".to_string(),
};
println!("tom_cruise: {:#?}", tom_cruise);
println!("tom_hanks: {:#?}", tom_hanks);
let actors: Result<Vec<for_retrieve::Actor>, DbError> = em.insert(&[&tom_cruise, &tom_hanks]);
println!("Actor: {:#?}", actors);
assert!(actors.is_ok());
let actors = actors.unwrap();
let today = Utc::now().date();
assert_eq!(tom_cruise.first_name, actors[0].first_name);
assert_eq!(tom_cruise.last_name, actors[0].last_name);
assert_eq!(today, actors[0].last_update.date());
assert_eq!(tom_hanks.first_name, actors[1].first_name);
assert_eq!(tom_hanks.last_name, actors[1].last_name);
assert_eq!(today, actors[1].last_update.date());
}<|fim▁end|> | let tom_hanks = for_insert::Actor { |
<|file_name|>get_custom_fields_for_line_items.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all custom fields that can be applied to line items.
"""
# Import appropriate modules from the client library.
from googleads import ad_manager
def main(client):
# Initialize appropriate service.
custom_field_service = client.GetService(<|fim▁hole|> .Where('entityType = :entityType')
.WithBindVariable('entityType', 'LINE_ITEM'))
# Retrieve a small amount of custom fields at a time, paging
# through until all custom fields have been retrieved.
while True:
response = custom_field_service.getCustomFieldsByStatement(
statement.ToStatement())
if 'results' in response and len(response['results']):
for custom_field in response['results']:
# Print out some information for each custom field.
print('Custom field with ID "%d" and name "%s" was found.\n' %
(custom_field['id'], custom_field['name']))
statement.offset += statement.limit
else:
break
print '\nNumber of results found: %s' % response['totalResultSetSize']
if __name__ == '__main__':
# Initialize client object.
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
main(ad_manager_client)<|fim▁end|> | 'CustomFieldService', version='v201808')
# Create a statement to select custom fields.
statement = (ad_manager.StatementBuilder(version='v201808') |
<|file_name|>lunacy.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from time import gmtime, strftime
import ephem
import wx.calendar
# Test
# here = ephem.Observer()
# here.lat = '-17.576166667'
# here.lon = '-149.618575000'
class App(wx.App):
def OnInit(self):
self.frame = MyFrame("Lunacy", (50, 60), (640, 220))
self.frame.Show()
self.SetTopWindow(self.frame)
return True
##########################################################################
## Class MyFrame
###########################################################################
class MyFrame(wx.Frame):
def __init__(self, title, pos, size):
wx.Frame.__init__(self, None, -1, title, pos, size)
path = "/usr/share/pixmaps/pidgin/emotes/default/moon.png"
icon = wx.Icon(path, wx.BITMAP_TYPE_PNG)
self.SetIcon(icon)
self.SetSizeHintsSz(wx.Size(640, 220), wx.DefaultSize)
gSizer1 = wx.GridSizer(1, 2, 0, 0)
fgSizer1 = wx.FlexGridSizer(1, 1, 0, 0)
fgSizer1.SetFlexibleDirection(wx.BOTH)
fgSizer1.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
cal = wx.calendar.CalendarCtrl(self, wx.ID_ANY, wx.DefaultDateTime, wx.DefaultPosition, wx.DefaultSize,
wx.calendar.CAL_SHOW_HOLIDAYS |
wx.calendar.CAL_SHOW_SURROUNDING_WEEKS |
wx.calendar.CAL_SUNDAY_FIRST |
wx.SUNKEN_BORDER, u"Date of Lunacy")
self.cal = cal
self.cal.SetFont(wx.Font(12, 74, 90, 90, False, "Sans"))
self.cal.SetToolTipString(u"Date for Next Event")
self.cal.SetHelpText(u"Renders Lunar/Solar events for the date.")
self.Bind(wx.calendar.EVT_CALENDAR_SEL_CHANGED, self.OnDateSelect, id=cal.GetId())
fgSizer1.Add(self.cal, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.ALL, 5)
fgSizer1.AddSpacer(( 0, 5), 1, wx.EXPAND, 5)
gSizer1.Add(fgSizer1, 1, 0, 0)
fgSizer2 = wx.FlexGridSizer(8, 3, 3, 0)
fgSizer2.SetFlexibleDirection(wx.HORIZONTAL)
fgSizer2.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)
fgSizer2.SetMinSize(wx.Size(-1, 220))
self.staticText_Moonrise = wx.StaticText(self, wx.ID_ANY, u"Moonrise", wx.DefaultPosition, wx.DefaultSize, 0)
self.staticText_Moonrise.Wrap(-1)
self.staticText_Moonrise.SetFont(wx.Font(12, 74, 90, 90, False, "Sans"))
fgSizer2.Add(self.staticText_Moonrise, 0, 0, 5)
self.mrtime = wx.StaticText(self, wx.ID_ANY, u"next rise", wx.DefaultPosition, wx.DefaultSize, 0)
self.mrtime.Wrap(-1)
fgSizer2.Add(self.mrtime, 0, 0, 5)
self.mraz = wx.StaticText(self, wx.ID_ANY, u"azimuth", wx.DefaultPosition, wx.DefaultSize, 0)
self.mraz.Wrap(-1)
fgSizer2.Add(self.mraz, 0, 0, 5)
self.staticText_Moonset = wx.StaticText(self, wx.ID_ANY, u"Moonset", wx.DefaultPosition, wx.DefaultSize, 0)
self.staticText_Moonset.Wrap(-1)
self.staticText_Moonset.SetFont(wx.Font(12, 74, 90, 90, False, "Sans"))
fgSizer2.Add(self.staticText_Moonset, 0, 0, 10)
self.mstime = wx.StaticText(self, wx.ID_ANY, u"next set", wx.DefaultPosition, wx.DefaultSize, 0)
self.mstime.Wrap(-1)
fgSizer2.Add(self.mstime, 0, 0, 5)
self.msaz = wx.StaticText(self, wx.ID_ANY, u"azimuth", wx.DefaultPosition, wx.DefaultSize, 0)
self.msaz.Wrap(-1)
fgSizer2.Add(self.msaz, 0, 0, 5)
self.staticText_Phase = wx.StaticText(self, wx.ID_ANY, u"Phase", wx.DefaultPosition, wx.DefaultSize, 0)
self.staticText_Phase.Wrap(-1)
self.staticText_Phase.SetFont(wx.Font(12, 74, 90, 90, False, "Sans"))
fgSizer2.Add(self.staticText_Phase, 0, 0, 10)
self.moonphase = wx.StaticText(self, wx.ID_ANY, u"moonphase", wx.DefaultPosition, wx.DefaultSize, 0)
self.moonphase.Wrap(-1)
fgSizer2.Add(self.moonphase, 0, 0, 5)
self.phasepercent = wx.StaticText(self, wx.ID_ANY, u"% illuminated", wx.DefaultPosition, wx.DefaultSize, 0)
self.phasepercent.Wrap(-1)
fgSizer2.Add(self.phasepercent, 0, 0, 5)
self.staticText_NewMoon = wx.StaticText(self, wx.ID_ANY, u"New Moon ", wx.DefaultPosition, wx.DefaultSize,
wx.ST_NO_AUTORESIZE)
self.staticText_NewMoon.Wrap(-1)
self.staticText_NewMoon.SetFont(wx.Font(12, 74, 90, 90, False, "Sans"))
fgSizer2.Add(self.staticText_NewMoon, 0, 0, 10)
self.newmoondate = wx.StaticText(self, wx.ID_ANY, u"next new moon", wx.DefaultPosition, wx.DefaultSize, 0)
self.newmoondate.Wrap(-1)
fgSizer2.Add(self.newmoondate, 0, 0, 10)
self.newmoonhour = wx.StaticText(self, wx.ID_ANY, u"hour", wx.DefaultPosition, wx.DefaultSize, 0)
self.newmoonhour.Wrap(-1)
fgSizer2.Add(self.newmoonhour, 0, 0, 10)
self.staticText_FullMoon = wx.StaticText(self, wx.ID_ANY, u"Full Moon", wx.DefaultPosition, wx.DefaultSize, 0)
self.staticText_FullMoon.Wrap(-1)
self.staticText_FullMoon.SetFont(wx.Font(12, 74, 90, 90, False, "Sans"))
fgSizer2.Add(self.staticText_FullMoon, 0, 0, 10)
self.fullmoondate = wx.StaticText(self, wx.ID_ANY, u"next full moon", wx.DefaultPosition, wx.DefaultSize, 0)
self.fullmoondate.Wrap(-1)
fgSizer2.Add(self.fullmoondate, 0, 0, 5)
self.fullmoonhour = wx.StaticText(self, wx.ID_ANY, u"hour", wx.DefaultPosition, wx.DefaultSize, 0)
self.fullmoonhour.Wrap(-1)
fgSizer2.Add(self.fullmoonhour, 0, 0, 5)
self.staticText_Sunrise = wx.StaticText(self, wx.ID_ANY, u"Sunrise", wx.DefaultPosition, wx.DefaultSize, 0)
self.staticText_Sunrise.Wrap(-1)
self.staticText_Sunrise.SetFont(wx.Font(12, 74, 90, 90, False, "Sans"))
fgSizer2.Add(self.staticText_Sunrise, 0, 0, 10)
self.srtime = wx.StaticText(self, wx.ID_ANY, u"next rise", wx.DefaultPosition, wx.DefaultSize, 0)
self.srtime.Wrap(-1)
fgSizer2.Add(self.srtime, 0, 0, 5)
self.sraz = wx.StaticText(self, wx.ID_ANY, u"azimuth", wx.DefaultPosition, wx.DefaultSize, 0)
self.sraz.Wrap(-1)
fgSizer2.Add(self.sraz, 0, 0, 5)
self.staticText_SolarNoon = wx.StaticText(self, wx.ID_ANY, u"High Noon", wx.DefaultPosition, wx.DefaultSize, 0)
self.staticText_SolarNoon.Wrap(-1)
self.staticText_SolarNoon.SetFont(wx.Font(12, 74, 90, 90, False, "Sans"))
fgSizer2.Add(self.staticText_SolarNoon, 0, 0, 10)
self.sntime = wx.StaticText(self, wx.ID_ANY, u"solar noon", wx.DefaultPosition, wx.DefaultSize, 0)
self.sntime.Wrap(-1)
fgSizer2.Add(self.sntime, 0, 0, 5)
self.snaltitude = wx.StaticText(self, wx.ID_ANY, u"altitude", wx.DefaultPosition, wx.DefaultSize, 0)
self.snaltitude.Wrap(-1)
fgSizer2.Add(self.snaltitude, 0, 0, 5)
self.staticText_Sunset = wx.StaticText(self, wx.ID_ANY, u"Sunset", wx.DefaultPosition, wx.DefaultSize, 0)
self.staticText_Sunset.Wrap(-1)
self.staticText_Sunset.SetFont(wx.Font(12, 74, 90, 90, False, "Sans"))
fgSizer2.Add(self.staticText_Sunset, 0, 0, 10)
self.sstime = wx.StaticText(self, wx.ID_ANY, u"next set", wx.DefaultPosition, wx.DefaultSize, 0)
self.sstime.Wrap(-1)
fgSizer2.Add(self.sstime, 0, 0, 5)
self.ssaz = wx.StaticText(self, wx.ID_ANY, u"azimuth", wx.DefaultPosition, wx.DefaultSize, 0)
self.ssaz.Wrap(-1)
fgSizer2.Add(self.ssaz, 0, 0, 5)
gSizer1.Add(fgSizer2, 1, wx.TOP, 5)
self.SetSizer(gSizer1)
self.Layout()
self.Centre(wx.BOTH)
def __del__(self):
pass
def OnDateSelect(self, evt):
f = open(r'/etc/nx.lat') # Lat/lon files for Navigatrix<|fim▁hole|> f.close()
f = open(r'/etc/nx.lon')
lon = f.readline(12)
f.close()
lat = float(lat)
lon = float(lon)
degrees = int(lat)
mnn = (lat - degrees) * 60
minutes = int(mnn)
seconds = round(((mnn - minutes) * 60), 3)
lat = str(degrees) + str(minutes) + str(seconds)
degrees = int(lon)
mnn = (lon - degrees) * 60
minutes = int(mnn)
seconds = round(((mnn - minutes) * 60), 3)
lon = str(degrees) + str(minutes) + str(seconds)
here = ephem.Observer()
here.lat = lat
here.lon = lon
here.pressure = 0 # barometric pressure not factored
here.horizon = '-0:34' # fudge factor from the US Navel Observatory
here.elevation = 2.0 # 2 Meters elevation
here.temp = 25.0 # and a balmy 25 degrees
cal = evt.GetEventObject()
year = (str(self.cal.GetDate().GetYear()))
month = (str(self.cal.GetDate().GetMonth() + 1))
day = (str(self.cal.GetDate().GetDay()))
hour = strftime("%H:%M:%S", gmtime())
datefig = year + '/' + month + '/' + day + ' ' + hour
here.date = datefig
sun = ephem.Sun(here)
moon = ephem.Moon(here)
moon.compute(here)
#
# Moon Rise
#
# mrtime = str(here.next_rising(moon))
mrtime = here.next_rising(moon)
lt = ephem.localtime(mrtime)
mrtime = str(lt).split()
mrtime = mrtime[1].split(".")
self.mrtime.SetLabel(str(mrtime[0]))
mraz = str(moon.az).partition(':')
self.mraz.SetLabel(str(mraz[0]) + u'\u00B0 from North')
#
# Moonset moon.compute(here)
#
#
mstime = here.next_setting(moon)
lt = ephem.localtime(mstime)
mstime = str(lt).split()
mstime = mstime[1].split(".")
self.mstime.SetLabel(mstime[0])
msaz = str(moon.az).partition(':')
self.msaz.SetLabel(str(msaz[0]) + u'\u00B0 from North')
#
# Moon Phase
# TODO Clearly these numbers are pulled out of a hat.
# they are a very rough approximation of the phases and
# do not account for waxing and waning
phasepercent = int(moon.moon_phase * 100)
self.phasepercent.SetLabel(str(phasepercent) + " %")
if phasepercent <= 2.0:
moonphase = "New Moon"
if 2.1 < phasepercent <= 20.0:
moonphase = "Crescent"
if 20.1 < phasepercent <= 60.0:
moonphase = "Quarter Moon"
if 60.1 < phasepercent <= 95.0:
moonphase = "Gibbous"
if phasepercent > 95.1:
moonphase = "Full Moon"
self.moonphase.SetLabel(moonphase)
#
# New Moon Date
#
newmoondate = ephem.next_new_moon(datefig)
lt = ephem.localtime(newmoondate)
newmoondate = str(lt).split()
newmoonhour = newmoondate[1].split(".")
self.newmoondate.SetLabel(str(newmoondate[0]))
self.newmoonhour.SetLabel(str(newmoonhour[0]))
#
# Full Moon Date
#
fullmoondate = ephem.next_full_moon(datefig)
lt = ephem.localtime(fullmoondate)
fullmoondate = str(lt).split()
fullmoonhour = fullmoondate[1].split(".")
self.fullmoondate.SetLabel(str(fullmoondate[0]))
self.fullmoonhour.SetLabel(str(fullmoonhour[0]))
#
# Sun Rise
#
sun.compute(here)
srtime = here.next_rising(sun)
lt = ephem.localtime(srtime)
srtime = str(lt).split()
srtime = srtime[1].split(".")
self.srtime.SetLabel(srtime[0])
sraz = str(sun.az).partition(':')
self.sraz.SetLabel(str(sraz[0]) + u'\u00B0 from North')
#
# High Noon
#
sntime = here.next_transit(sun)
lt = ephem.localtime(sntime)
sntime = str(lt).split()
sntime = sntime[1].split(".")
self.sntime.SetLabel(sntime[0])
snaltitude = str(sun.alt).partition(':')
self.snaltitude.SetLabel(str(snaltitude[0]) + u'\u00B0 above Horizon')
#
# Sun Set
#
sstime = here.next_setting(sun)
lt = ephem.localtime(sstime)
sstime = str(lt).split()
sstime = sstime[1].split(".")
self.sstime.SetLabel(sstime[0])
ssaz = str(sun.az).partition(':')
self.ssaz.SetLabel(str(ssaz[0]) + u'\u00B0 from North')
if __name__ == '__main__':
app = App()
app.MainLoop()<|fim▁end|> | lat = f.readline(12) |
<|file_name|>vtable_recursive_sig.rs<|end_file_name|><|fim▁begin|>#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
pub struct Base__bindgen_vtable {
pub Base_AsDerived: unsafe extern "C" fn(this: *mut Base) -> *mut Derived,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct Base {
pub vtable_: *const Base__bindgen_vtable,
}
#[test]
fn bindgen_test_layout_Base() {
assert_eq!(
::std::mem::size_of::<Base>(),
8usize,
concat!("Size of: ", stringify!(Base))
);
assert_eq!(
::std::mem::align_of::<Base>(),
8usize,
concat!("Alignment of ", stringify!(Base))
);
}
impl Default for Base {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
extern "C" {
#[link_name = "\u{1}_ZN4Base9AsDerivedEv"]
pub fn Base_AsDerived(this: *mut ::std::os::raw::c_void) -> *mut Derived;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct Derived {
pub _base: Base,
}
#[test]
fn bindgen_test_layout_Derived() {
assert_eq!(
::std::mem::size_of::<Derived>(),
8usize,
concat!("Size of: ", stringify!(Derived))
);
assert_eq!(
::std::mem::align_of::<Derived>(),
8usize,
concat!("Alignment of ", stringify!(Derived))
);
}<|fim▁hole|> fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}<|fim▁end|> | impl Default for Derived { |
<|file_name|>repository.sage.ts<|end_file_name|><|fim▁begin|>/// <reference path="../_references.d.ts" />
interface sage {
id: number;
name: string;
username: string;
email: string;
dateOfBirth: Date;
sayings?: saying[];
}
interface repositorySage {
getAll: () => ng.IPromise<sage[]>;
getById: (id: number, forceRemote?: boolean) => ng.IPromise<sage>;
remove: (id: number) => ng.IPromise<void>;
save: (sage: sage) => ng.IPromise<void>;
}
(function () {
"use strict";
var serviceId = "repository.sage";
angular.module("app").factory(serviceId, ["$http", "common", "config", repositorySage]);
function repositorySage($http: ng.IHttpService, common: common, config: config) {
var $q = common.$q;
var log = common.logger.getLogFn(serviceId);
var rootUrl = config.remoteServiceRoot + "sage";
var cache: { [id: number]: sage } = {};
var service: repositorySage = {
getAll: getAll,
getById: getById,
remove: remove,
save: save
};
return service;
function getAll() {
return $http.get<sage[]>(rootUrl).then(response => {
var sages = response.data;
log(sages.length + " Sages loaded");
return sages;
});
}
function getById(id: number, forceRemote?: boolean) {
<|fim▁hole|> if (!forceRemote) {
sage = cache[id];
if (sage) {
log("Sage " + sage.name + " [id: " + sage.id + "] loaded from cache");
return $q.when(sage);
}
}
return $http.get<sage>(rootUrl + "/" + id).then(response => {
sage = response.data;
cache[sage.id] = sage;
log("Sage " + sage.name + " [id: " + sage.id + "] loaded");
return sage;
});
}
function remove(id: number) {
return $http.delete<void>(rootUrl + "/" + id).then(response => {
log("Sage [id: " + id + "] removed");
return response.data;
}, errorReason => $q.reject(errorReason.data));
}
function save(sage: sage) {
return $http.post<void>(rootUrl, sage).then(response => {
log("Sage " + sage.name + " [id: " + sage.id + "] saved");
return response.data;
}, errorReason => $q.reject(errorReason.data));
}
}
})();<|fim▁end|> | var sage: sage; |
<|file_name|>TagentEvent.js<|end_file_name|><|fim▁begin|>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Tevent_1 = require("../../../events/Tevent");
class TagentEvent extends Tevent_1.Tevent {
<|fim▁hole|> constructor(type, eventData = null, cancelable = true) {
super(type, eventData, cancelable);
}
}
TagentEvent.FAILURE = "FAILURE";
exports.TagentEvent = TagentEvent;
//# sourceMappingURL=TagentEvent.js.map<|fim▁end|> | |
<|file_name|>RKTwu.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3
# -*- coding: utf-8 -*-
r"""Pychemqt, Chemical Engineering Process simulator
Copyright (C) 2009-2017, Juan José Gómez Romera <[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 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/>."""
from math import exp
from scipy.constants import R
from lib.EoS.Cubic.RK import RK<|fim▁hole|>
class RKTwu(RK):
r"""Equation of state of Redlich-Kwong with a modified alpha temperature
dependence by Twu, (1995) [1]_.
.. math::
\begin{array}[t]{l}
P = \frac{RT}{V-b}-\frac{a}{V\left(V+b\right)}\\
a = 0.427480263354\frac{R^2T_c^2}{P_c}\alpha\\
b = 0.086640349965\frac{RT_c}{P_c}\\
\alpha = alpha^{(0)} + \omega\left(\alpha^{(1)}-\alpha^{(0)}\right)\\
\alpha^{(0)} = T_r^{-0.201158} \exp{0.141599\left(1-T_r^{2.29528}
\right)}\\
\alpha^{(1)} = T_r^{-0.660145} \exp{0.500315\left(1-T_r^{2.63165}
\right)}\\
\end{array}
"""
__title__ = "Twu-Redlich-Kwong (1995)"
__status__ = "RKTwu"
__doi__ = {
"autor": "Twu, C.H., Coon, J.E., Cunningham, J.R.",
"title": "A New Generalized Alpha Function for a Cubic Equation of "
"State Part 2. Redlich-Kwong equation",
"ref": "Fluid Phase Equilibria 105 (1995) 61-69",
"doi": "10.1016/0378-3812(94)02602-w"},
def _lib(self, cmp, T):
"""Modified parameteres correlations"""
a = 0.42748023354*R**2*cmp.Tc**2/cmp.Pc
alfa = self._alpha(cmp, T)
b = 0.086640349965*R*cmp.Tc/cmp.Pc
return a*alfa, b
def _alpha(self, cmp, T):
"""Modified α expression"""
Tr = T/cmp.Tc
if Tr <= 1:
alpha0 = Tr**(-0.201158)*exp(0.141599*(1-Tr**2.29528)) # Eq 17
alpha1 = Tr**(-0.660145)*exp(0.500315*(1-Tr**2.63165)) # Eq 18
else:
alpha0 = Tr**(-1.10)*exp(0.441411*(1-Tr**(-1.30))) # Eq 19
alpha1 = Tr**(-2.31278)*exp(0.03258*(1-Tr**(-10.3128))) # Eq 20
# Eq 15
alpha = alpha0 + cmp.f_acent*(alpha1-alpha0)
return alpha
if __name__ == "__main__":
from lib.mezcla import Mezcla
mix = Mezcla(5, ids=[4], caudalMolar=1, fraccionMolar=[1])
eq = RKTwu(300, 9.9742e5, mix)
print('%0.0f %0.1f' % (eq.Vg.ccmol, eq.Vl.ccmol))
eq = RKTwu(300, 42.477e5, mix)
print('%0.1f' % (eq.Vl.ccmol))<|fim▁end|> | |
<|file_name|>parser.py<|end_file_name|><|fim▁begin|><|fim▁hole|>
from HTMLParser import *<|fim▁end|> | from __future__ import absolute_import |
<|file_name|>accretion.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -----------------------------------------------------------------------------
# VORONOI.ACCRETION
# Laura L Watkins [[email protected]]
# - converted from IDL code by Michele Cappellari (bin2d_accretion)
# -----------------------------------------------------------------------------
from numpy import *
from .bin_roundness import bin_roundness
def accretion(x, y, signal, noise, targetsn, pixelsize=False, quiet=False):
"""
Initial binning -- steps i-v of eq 5.1 of Cappellari & Copin (2003)
INPUTS:
x : x coordinates of pixels to bin
y : y coordinates of pixels to bin
signal : signal associated with each pixel
noise : noise (1-sigma error) associated with each pixel
targetsn : desired signal-to-noise ration in final 2d-binned data
OPTIONS:
pixelsize : pixel scale of the input data
quiet : if set, suppress printed outputs
"""
n = x.size
clas = zeros(x.size, dtype="<i8") # bin number of each pixel
good = zeros(x.size, dtype="<i8") # =1 if bin accepted as good
# for each point, find distance to all other points and select minimum
# (robust but slow way of determining the pixel size of unbinned data)
if not pixelsize:
dx = 1.e30
for j in range(x.size-1):
d = (x[j] - x[j+1:])**2 + (y[j] - y[j+1:])**2
dx = min(d.min(), dx)
pixelsize = sqrt(dx)
# start from the pixel with highest S/N
sn = (signal/noise).max()
currentbin = (signal/noise).argmax()
# rough estimate of the expected final bin number
# This value is only used to have a feeling of the expected
# remaining computation time when binning very big dataset.
wh = where(signal/noise<targetsn)
npass = size(where(signal/noise >= targetsn))
maxnum = int(round( (signal[wh]**2/noise[wh]**2).sum()/targetsn**2 ))+npass
# first bin assigned CLAS = 1 -- with N pixels, get at most N bins
for ind in range(1, n+1):
if not quiet:
print(" bin: {:} / {:}".format(ind, maxnum))
# to start the current bin is only one pixel
clas[currentbin] = ind
# centroid of bin
xbar = x[currentbin]
ybar = y[currentbin]
while True:
# stop if all pixels are binned
unbinned = where(clas == 0)[0]
if unbinned.size == 0: break
# find unbinned pixel closest to centroid of current bin
dist = (x[unbinned]-xbar)**2 + (y[unbinned]-ybar)**2
mindist = dist.min()
k = dist.argmin()
# find the distance from the closest pixel to the current bin
mindist = ((x[currentbin]-x[unbinned[k]])**2 \
+ (y[currentbin]-y[unbinned[k]])**2).min()
# estimate roundness of bin with candidate pixel added
nextbin = append(currentbin, unbinned[k])
roundness = bin_roundness(x[nextbin], y[nextbin], pixelsize)
# compute sn of bin with candidate pixel added
snold = sn
sn = signal[nextbin].sum()/sqrt((noise[nextbin]**2).sum())
# Test whether the CANDIDATE pixel is connected to the
# current bin, whether the POSSIBLE new bin is round enough<|fim▁hole|> or abs(sn-targetsn) > abs(snold-targetsn):
if (snold > 0.8*targetsn):
good[currentbin] = 1
break
# if all the above tests are negative then accept the CANDIDATE
# pixel, add it to the current bin, and continue accreting pixels
clas[unbinned[k]] = ind
currentbin = nextbin
# update the centroid of the current bin
xbar = x[currentbin].mean()
ybar = y[currentbin].mean()
# get the centroid of all the binned pixels
binned = where(clas != 0)[0]
unbinned = where(clas == 0)[0]
# stop if all pixels are binned
if unbinned.size == 0: break
xbar = x[binned].mean()
ybar = y[binned].mean()
# find the closest unbinned pixel to the centroid of all
# the binned pixels, and start a new bin from that pixel
k = ((x[unbinned]-xbar)**2 + (y[unbinned]-ybar)**2).argmin()
currentbin = unbinned[k] # the bin is initially made of one pixel
sn = signal[currentbin] / noise[currentbin]
# set to zero all bins that did not reach the target S/N
clas = clas*good
return clas<|fim▁end|> | # and whether the resulting S/N would get closer to targetsn
if sqrt(mindist) > 1.2*pixelsize or roundness > 0.3 \ |
<|file_name|>ctaFollow.js<|end_file_name|><|fim▁begin|>"use strict";
var userUtils = require("../../lib/user-utils.js");
module.exports = function(core, config, store) {
core.on("setstate", function(changes) {
var future = store.with(changes),
userId = future.get("user"),
roomId = future.get("nav", "room"),
mode = future.get("nav", "mode"),
cta = future.get("app", "cta"),
role = future.get("entities", roomId + "_" + userId, "role"),
roomObj = future.getRoom(roomId);
<|fim▁hole|>
if (roomObj === "missing") {
changes.app.cta = null;
} else if (userId && !userUtils.isGuest(userId) && ((/(visitor|none)/).test(role) || !role) && (/(chat|room)/).test(mode) &&
!(roomObj && roomObj.guides && roomObj.guides.authorizer && roomObj.guides.authorizer.openRoom === false)) {
changes.app.cta = "follow";
} else if (cta === "follow") {
changes.app.cta = null;
}
}, 400);
};<|fim▁end|> | changes.app = changes.app || {}; |
<|file_name|>UsagePrinterJANI.java<|end_file_name|><|fim▁begin|>/****************************************************************************
ePMC - an extensible probabilistic model checker
Copyright (C) 2017
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/>.
*****************************************************************************/
package epmc.command;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import epmc.util.Util;
import epmc.jani.interaction.commandline.CommandLineCategory;
import epmc.jani.interaction.commandline.CommandLineCommand;
import epmc.jani.interaction.commandline.CommandLineOption;
import epmc.jani.interaction.commandline.CommandLineOptions;
/**
* Class to print usage information about options set.
* The usage information consists of a description of the parameters of the
* options and commands of the options set, and how to use them.
*
* @author Ernst Moritz Hahn
*/
public final class UsagePrinterJANI {
/** String containing "[program-options]". */
private final static String PROGRAM_OPTIONS_STRING = "[program-options]";
/** String containing "command". */
private final static String COMMAND_STRING = "command";
/** String containing dot. */
private final static String DOT = ".";
/** String containing new line*/
private final static String NEWLINE = "\n";
/** Key in the resource file to read "Usage". */
private final static String COLON = ":";
/** String containing \0 */
private final static String NULL_STRING = "\0";
/** Empty string. */
private final static String EMPTY = "";
/** String containing single space character. */
private final static String SPACE = " ";
/** String containing a single pipe character. */
private final static String PIPE = "|";
/** String containing smaller than character. */
private final static String SMALLER_THAN = "<";
/** String containing larger than character. */
private final static String LARGER_THAN = ">";
/** Prefix used for the options. */
private final static String OPTION_PREFIX = "--";
/** Maximal line length of the program options description */
private final static int MAX_LINE_LENGTH = 72;
/**
* First part of regular expression to split line into parts of given
* length. To complete the sequence, this string shall be followed by a
* number and then {@link #ALIGN_CHARS_REGEXP_SECOND}.
* */
private static final String ALIGN_CHARS_REGEXP_FIRST = "(?<=\\G.{";
/**
* Second part of regular expression to split line into parts of given
* length, see {@link #ALIGN_CHARS_REGEXP_FIRST}.
*/
private static final String ALIGN_CHARS_REGEXP_SECOND = "})";
/**
* Get usage information of the given options set.
* The options parameter may not be {@code null}.
*
* @param options options to get usage information of
* @return usage information of the given options set
*/
public static String getUsage(CommandLineOptions options) {
assert options != null;
StringBuilder builder = new StringBuilder();
appendCommands(builder, options);
appendOptions(builder, options);
return builder.toString();
}
/**
* Append information about the options commands to given string builder.
* None of the parameters may be {@code null}.
*
* @param builder string builder to append information to
* @param options options the command information shall be appended
*/
private static void appendCommands(StringBuilder builder, CommandLineOptions options) {
assert builder != null;
assert options != null;
Locale locale = Locale.getDefault();
MessageFormat formatter = new MessageFormat(EMPTY);
formatter.setLocale(locale);
builder.append(options.getToolName() + COLON + SPACE);
builder.append(options.getToolDescription() + NEWLINE + NEWLINE);
String revision = Util.getManifestEntry(Util.SCM_REVISION);
if (revision != null) {
revision = revision.trim();
}
if (revision != null && !revision.equals(EMPTY)) {
formatter.applyPattern(options.getRunningToolRevisionPatter());
builder.append(formatter.format(new Object[]{options.getToolName(), revision}) + NEWLINE);
}
builder.append(options.getUsagePattern());
String usageString = COLON + SPACE + SMALLER_THAN + options.getToolCmdPattern() + LARGER_THAN + SPACE + SMALLER_THAN + COMMAND_STRING + LARGER_THAN + SPACE + PROGRAM_OPTIONS_STRING + NEWLINE + NEWLINE;
builder.append(usageString);
builder.append(options.getAvailableCommandsPattern() + COLON + NEWLINE);
List<String> cmdStrings = new ArrayList<>();
int maxCmdStringSize = 0;
for (String commandString : options.getCommands().keySet()) {
String cmdStr = SPACE + SPACE + commandString + SPACE;
maxCmdStringSize = Math.max(maxCmdStringSize, cmdStr.length());
cmdStrings.add(cmdStr);
}
maxCmdStringSize += 2;
Iterator<CommandLineCommand> cmdIter = options.getCommands().values().iterator();
for (String formattedCommandStr : cmdStrings) {
CommandLineCommand command = cmdIter.next();
String dots = dots(maxCmdStringSize - formattedCommandStr.length());
formattedCommandStr += dots + SPACE;
formattedCommandStr += command.getShortDescription();
formattedCommandStr += NEWLINE;
builder.append(formattedCommandStr);
}
builder.append(NEWLINE);
}
/**
* Append information about the options of the given options set to builder.
* None of the parameters may be {@code null}.
*
* @param builder string builder to append information to
* @param options options the command information shall be appended
*/
private static void appendOptions(StringBuilder builder, CommandLineOptions options) {
assert builder != null;
assert options != null;
Map<CommandLineCategory,Set<CommandLineOption>> optionsByCategory = buildOptionsByCategory(options);
Map<CommandLineCategory,Set<CommandLineCategory>> hierarchy = buildHierarchy(options);
builder.append(options.getAvailableProgramOptionsPattern() + COLON + NEWLINE);
Collection<CommandLineOption> nonCategorisedOptions = optionsByCategory.get(null);
for (CommandLineOption option : nonCategorisedOptions) {
appendOption(builder, option, options, 0);
}
for (CommandLineCategory category : optionsByCategory.keySet()) {
if (category == null || category.getParent() != null) {
continue;
}
appendCategorisedOptions(builder, category, hierarchy,
optionsByCategory, options, 0);
}
}
private static void appendCategorisedOptions(StringBuilder builder, CommandLineCategory category,
Map<CommandLineCategory, Set<CommandLineCategory>> hierarchy,
Map<CommandLineCategory, Set<CommandLineOption>> optionsByCategory, CommandLineOptions options, int level) {
assert hierarchy != null;
Set<CommandLineOption> categorisedOptions = optionsByCategory.get(category);
builder.append(spacify(category.getShortDescription() + COLON, 2 + 2 * level));
for (CommandLineOption option : categorisedOptions) {
appendOption(builder, option, options, level + 1);
}
for (CommandLineCategory child : hierarchy.get(category)) {
appendCategorisedOptions(builder, child, hierarchy,
optionsByCategory, options, level + 1);
}
}
private static void appendOption(StringBuilder builder, CommandLineOption option, CommandLineOptions options, int level) {
assert builder != null;
assert option != null;
String topLine = buildOptionTopLine(option);
builder.append(spacify(topLine, 2 + level * 2));
String description = alignWords(option.getShortDescription(), MAX_LINE_LENGTH - (6 + level * 2));
description = spacify(description, 6 + level * 2);
builder.append(description);
String typeLines = buildOptionTypeLines(options, option);
typeLines = alignPiped(typeLines, MAX_LINE_LENGTH - (6 + level * 2));
typeLines = spacify(typeLines, 6 + level * 2);
builder.append(typeLines);
String defaultLines = buildOptionDefaultLines(options, option);
if (defaultLines != null) {
defaultLines = alignCharacters(defaultLines, MAX_LINE_LENGTH - (6 + level * 2));
defaultLines = spacify(defaultLines, 6 + level * 2);
builder.append(defaultLines);
}
}
private static Map<CommandLineCategory,Set<CommandLineCategory>> buildHierarchy(CommandLineOptions options) {
assert options != null;
Map<CommandLineCategory,Set<CommandLineCategory>> result = new LinkedHashMap<>();<|fim▁hole|> for (CommandLineCategory category : options.getAllCategories().values()) {
result.put(category, new LinkedHashSet<>());
}
for (CommandLineCategory category : options.getAllCategories().values()) {
CommandLineCategory parent = category.getParent();
if (parent == null) {
continue;
}
result.get(parent).add(category);
}
return result;
}
private static Map<CommandLineCategory, Set<CommandLineOption>> buildOptionsByCategory(
CommandLineOptions options) {
assert options != null;
Map<CommandLineCategory, Set<CommandLineOption>> result = new LinkedHashMap<>();
for (CommandLineOption option : options.getAllOptions().values()) {
CommandLineCategory category = option.getCategory();
Set<CommandLineOption> catSet = result.get(category);
if (catSet == null) {
catSet = new LinkedHashSet<>();
result.put(category, catSet);
}
catSet.add(option);
}
return result;
}
/**
* Create a string describing the type of a given option.
* The internationalization information will read from resource bundle with
* the given base name. The returned string is of the format
* "<word-type-in-language>: <type-info><newline>.
* None of the parameters may be {@code null}.
*
* @param resourceBundle base name of resource bundle
* @param option option to get type info description of
* @return string describing the type of a given option
*/
private static String buildOptionTypeLines(CommandLineOptions options, CommandLineOption option) {
assert options != null;
assert option != null;
String typeInfo = options.getTypePattern() + COLON + SPACE + option.getTypeInfo() + NEWLINE;
return typeInfo;
}
/**
* Build string describing default value of given option.
* The internationalization information will read from resource bundle with
* the given base name. The returned string is of the format
* "<word-default-in-language>: <default><newline>.
* If the option does not have a default value, the method will return
* {@code null}.
* None of the parameters may be {@code null}.
*
* @param resourceBundle base name of resource bundle
* @param option option to get default value description of
* @return describing the default value of a given option or {@code null}
*/
private static String buildOptionDefaultLines(CommandLineOptions options,
CommandLineOption option) {
assert options != null;
assert option != null;
String defaultValue = option.getDefault();
String result = null;
if (defaultValue != null && !defaultValue.equals(EMPTY)) {
result = options.getDefaultPattern() + COLON + SPACE + defaultValue + SPACE + NEWLINE;
}
return result;
}
private static String buildOptionTopLine(CommandLineOption option) {
String poStr = OPTION_PREFIX + option.getIdentifier() + SPACE;
return poStr;
}
/**
* Obtain a sequence of a give number of dots (".").
* The number of dots must be nonnegative.
*
* @param numDots length of sequence
* @return sequence of a give number of dots (".")
*/
private static String dots(int numDots) {
assert numDots >= 0;
return new String(new char[numDots]).replace(NULL_STRING, DOT);
}
/**
* Obtain a sequence of a give number of spaces (" ").
* The number of spaces must be nonnegative.
*
* @param numSpaces length of sequence
* @return sequence of a give number of spaces (" ")
*/
private static String spaces(int numSpaces) {
assert numSpaces >= 0;
return new String(new char[numSpaces]).replace(NULL_STRING, SPACE);
}
/**
* Align lines by prefixing them by the given number of spaces.
* The input string parameter may not be {@code null}, and the number of
* spaces must be nonnegative.
*
* @param lines lines to align
* @param numSpaces number of spaces to prefix lines with
* @return aligned string
*/
private static String spacify(String lines, int numSpaces) {
assert lines != null;
assert numSpaces >= 0;
String[] linesArray = lines.split(NEWLINE);
StringBuilder result = new StringBuilder();
for (int lineNr = 0; lineNr < linesArray.length; lineNr++) {
result.append(spaces(numSpaces) + linesArray[lineNr] + NEWLINE);
}
return result.toString();
}
/**
* Split string by words into lines not exceeding length limit.
* The line length may be exceeded if there is a single word larger than
* the given line length. The method only splits along word limits; it is
* not able to perform hyphenation etc.
* The string to split must not be {@code null}, and the maximal line length
* must be positive.
*
* @param string string to split
* @param maxLineLength maximal line length
* @return split string
*/
private static String alignWords(String string, int maxLineLength) {
return alignSplit(string, maxLineLength, SPACE);
}
private static String alignPiped(String string, int maxLineLength) {
return alignSplit(string, maxLineLength, PIPE);
}
private static String alignSplit(String string, int maxLineLength, String split) {
assert string != null;
assert maxLineLength >= 1;
String[] words = string.split(Pattern.quote(split));
StringBuilder result = new StringBuilder();
int lineLength = 0;
for (String word : words) {
lineLength += word.length() + 1;
if (lineLength > maxLineLength) {
result.append(NEWLINE);
lineLength = word.length() + 1;
}
result.append(word + split);
}
result.delete(result.length() - 1, result.length());
return result.toString();
}
/**
* Split string into lines of given length along characters.
* The string to split may not be {@code null}, and the maximal line length
* must be positive.
*
* @param string string to split
* @param maxLineLength maximal line length
* @return split string
*/
private static String alignCharacters(String string, int maxLineLength) {
assert string != null;
assert maxLineLength >= 1;
String[] lines = string.split(ALIGN_CHARS_REGEXP_FIRST + maxLineLength + ALIGN_CHARS_REGEXP_SECOND);
StringBuilder result = new StringBuilder();
for (String line : lines) {
result.append(line + NEWLINE);
}
return result.toString();
}
/**
* Private constructor to prevent instantiation.
*/
private UsagePrinterJANI() {
}
}<|fim▁end|> | |
<|file_name|>convert_from_tensorflow.py<|end_file_name|><|fim▁begin|># Copyright (c) 2019 Guo Yejun
#
# This file is part of FFmpeg.
#
# FFmpeg 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 2.1 of the License, or (at your option) any later version.
#
# FFmpeg 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 FFmpeg; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# ==============================================================================
import tensorflow as tf
import numpy as np
import sys, struct
import convert_header as header
__all__ = ['convert_from_tensorflow']
class Operand(object):
IOTYPE_INPUT = 1
IOTYPE_OUTPUT = 2
IOTYPE_INTERMEDIATE = IOTYPE_INPUT | IOTYPE_OUTPUT
DTYPE_FLOAT = 1
DTYPE_UINT8 = 4
index = 0
def __init__(self, name, dtype, dims):
self.name = name
self.dtype = dtype
self.dims = dims
self.iotype = 0
self.used_count = 0
self.index = Operand.index
Operand.index = Operand.index + 1
self.iotype2str = {Operand.IOTYPE_INPUT: 'in', Operand.IOTYPE_OUTPUT: 'out', Operand.IOTYPE_INTERMEDIATE: 'inout'}
self.dtype2str = {Operand.DTYPE_FLOAT: 'DT_FLOAT', Operand.DTYPE_UINT8: 'DT_UINT8'}
def add_iotype(self, iotype):
self.iotype = self.iotype | iotype
if iotype == Operand.IOTYPE_INPUT:
self.used_count = self.used_count + 1
def __str__(self):
return "{}: (name: {}, iotype: {}, dtype: {}, dims: ({},{},{},{}) used_count: {})".format(self.index,
self.name, self.iotype2str[self.iotype], self.dtype2str[self.dtype],
self.dims[0], self.dims[1], self.dims[2], self.dims[3], self.used_count)
def __lt__(self, other):
return self.index < other.index
class TFConverter:
def __init__(self, graph_def, nodes, outfile, dump4tb):
self.graph_def = graph_def
self.nodes = nodes
self.outfile = outfile
self.dump4tb = dump4tb
self.layer_number = 0
self.output_names = []
self.name_node_dict = {}
self.edges = {}
self.conv_activations = {'Relu':0, 'Tanh':1, 'Sigmoid':2, 'None':3, 'LeakyRelu':4}
self.conv_paddings = {'VALID':0, 'SAME':1}
self.converted_nodes = set()
self.conv2d_scope_names = set()
self.conv2d_scopename_inputname_dict = {}
self.op2code = {'Conv2D':1, 'DepthToSpace':2, 'MirrorPad':3, 'Maximum':4, 'MathBinary':5}
self.mathbin2code = {'Sub':0, 'Add':1, 'Mul':2, 'RealDiv':3}
self.mirrorpad_mode = {'CONSTANT':0, 'REFLECT':1, 'SYMMETRIC':2}
self.name_operand_dict = {}
def add_operand(self, name, type):
node = self.name_node_dict[name]
if name not in self.name_operand_dict:
dtype = node.attr['dtype'].type
if dtype == 0:
dtype = node.attr['T'].type
dims = [-1,-1,-1,-1]
if 'shape' in node.attr:
dims[0] = node.attr['shape'].shape.dim[0].size
dims[1] = node.attr['shape'].shape.dim[1].size
dims[2] = node.attr['shape'].shape.dim[2].size
dims[3] = node.attr['shape'].shape.dim[3].size
operand = Operand(name, dtype, dims)
self.name_operand_dict[name] = operand;
self.name_operand_dict[name].add_iotype(type)
return self.name_operand_dict[name].index
def dump_for_tensorboard(self):
graph = tf.get_default_graph()
tf.import_graph_def(self.graph_def, name="")
tf.summary.FileWriter('/tmp/graph', graph)
print('graph saved, run "tensorboard --logdir=/tmp/graph" to see it')
def get_conv2d_params(self, conv2d_scope_name):
knode = self.name_node_dict[conv2d_scope_name + '/kernel']
bnode = self.name_node_dict[conv2d_scope_name + '/bias']
if conv2d_scope_name + '/dilation_rate' in self.name_node_dict:
dnode = self.name_node_dict[conv2d_scope_name + '/dilation_rate']
else:
dnode = None
# the BiasAdd name is possible be changed into the output name,
# if activation is None, and BiasAdd.next is the last op which is Identity
if conv2d_scope_name + '/BiasAdd' in self.edges:
anode = self.edges[conv2d_scope_name + '/BiasAdd'][0]
if anode.op not in self.conv_activations:
anode = None
else:
anode = None
return knode, bnode, dnode, anode
def dump_complex_conv2d_to_file(self, node, f):
assert(node.op == 'Conv2D')
self.layer_number = self.layer_number + 1
self.converted_nodes.add(node.name)
scope_name = TFConverter.get_scope_name(node.name)
#knode for kernel, bnode for bias, dnode for dilation, anode for activation
knode, bnode, dnode, anode = self.get_conv2d_params(scope_name)
if dnode is not None:
dilation = struct.unpack('i', dnode.attr['value'].tensor.tensor_content[0:4])[0]
else:
dilation = 1
if anode is not None:
activation = anode.op
else:
activation = 'None'
padding = node.attr['padding'].s.decode("utf-8")
# conv2d with dilation > 1 generates tens of nodes, not easy to parse them, so use this tricky method.
if dilation > 1 and scope_name + '/stack' in self.name_node_dict:
if self.name_node_dict[scope_name + '/stack'].op == "Const":
padding = 'SAME'
padding = self.conv_paddings[padding]
ktensor = knode.attr['value'].tensor
filter_height = ktensor.tensor_shape.dim[0].size
filter_width = ktensor.tensor_shape.dim[1].size
in_channels = ktensor.tensor_shape.dim[2].size
out_channels = ktensor.tensor_shape.dim[3].size
kernel = np.frombuffer(ktensor.tensor_content, dtype=np.float32)
kernel = kernel.reshape(filter_height, filter_width, in_channels, out_channels)
kernel = np.transpose(kernel, [3, 0, 1, 2])
has_bias = 1
np.array([self.op2code[node.op], dilation, padding, self.conv_activations[activation], in_channels, out_channels, filter_height, has_bias], dtype=np.uint32).tofile(f)
kernel.tofile(f)
btensor = bnode.attr['value'].tensor
if btensor.tensor_shape.dim[0].size == 1:
bias = struct.pack("f", btensor.float_val[0])
else:
bias = btensor.tensor_content
f.write(bias)
input_name = self.conv2d_scopename_inputname_dict[scope_name]
input_operand_index = self.add_operand(input_name, Operand.IOTYPE_INPUT)
if anode is not None:
output_operand_index = self.add_operand(anode.name, Operand.IOTYPE_OUTPUT)
else:
output_operand_index = self.add_operand(self.edges[bnode.name][0].name, Operand.IOTYPE_OUTPUT)
np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
def dump_simple_conv2d_to_file(self, node, f):
assert(node.op == 'Conv2D')
self.layer_number = self.layer_number + 1
self.converted_nodes.add(node.name)
node0 = self.name_node_dict[node.input[0]]
node1 = self.name_node_dict[node.input[1]]
if node0.op == 'Const':
knode = node0
input_name = node.input[1]
else:
knode = node1
input_name = node.input[0]
ktensor = knode.attr['value'].tensor
filter_height = ktensor.tensor_shape.dim[0].size
filter_width = ktensor.tensor_shape.dim[1].size
in_channels = ktensor.tensor_shape.dim[2].size
out_channels = ktensor.tensor_shape.dim[3].size<|fim▁hole|> if filter_height * filter_width * in_channels * out_channels == 1:
kernel = np.float32(ktensor.float_val[0])
else:
kernel = np.frombuffer(ktensor.tensor_content, dtype=np.float32)
kernel = kernel.reshape(filter_height, filter_width, in_channels, out_channels)
kernel = np.transpose(kernel, [3, 0, 1, 2])
has_bias = 0
dilation = 1
padding = node.attr['padding'].s.decode("utf-8")
np.array([self.op2code[node.op], dilation, self.conv_paddings[padding], self.conv_activations['None'],
in_channels, out_channels, filter_height, has_bias], dtype=np.uint32).tofile(f)
kernel.tofile(f)
input_operand_index = self.add_operand(input_name, Operand.IOTYPE_INPUT)
output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
def dump_depth2space_to_file(self, node, f):
assert(node.op == 'DepthToSpace')
self.layer_number = self.layer_number + 1
block_size = node.attr['block_size'].i
np.array([self.op2code[node.op], block_size], dtype=np.uint32).tofile(f)
self.converted_nodes.add(node.name)
input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
def dump_mirrorpad_to_file(self, node, f):
assert(node.op == 'MirrorPad')
self.layer_number = self.layer_number + 1
mode = node.attr['mode'].s
mode = self.mirrorpad_mode[mode.decode("utf-8")]
np.array([self.op2code[node.op], mode], dtype=np.uint32).tofile(f)
pnode = self.name_node_dict[node.input[1]]
self.converted_nodes.add(pnode.name)
paddings = pnode.attr['value'].tensor.tensor_content
f.write(paddings)
self.converted_nodes.add(node.name)
input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
def dump_maximum_to_file(self, node, f):
assert(node.op == 'Maximum')
self.layer_number = self.layer_number + 1
ynode = self.name_node_dict[node.input[1]]
y = ynode.attr['value'].tensor.float_val[0]
np.array([self.op2code[node.op]], dtype=np.uint32).tofile(f)
np.array([y], dtype=np.float32).tofile(f)
self.converted_nodes.add(node.name)
input_operand_index = self.add_operand(node.input[0], Operand.IOTYPE_INPUT)
output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
np.array([input_operand_index, output_operand_index], dtype=np.uint32).tofile(f)
def dump_mathbinary_to_file(self, node, f):
self.layer_number = self.layer_number + 1
self.converted_nodes.add(node.name)
i0_node = self.name_node_dict[node.input[0]]
i1_node = self.name_node_dict[node.input[1]]
np.array([self.op2code['MathBinary'], self.mathbin2code[node.op]], dtype=np.uint32).tofile(f)
if i0_node.op == 'Const':
scalar = i0_node.attr['value'].tensor.float_val[0]
np.array([1], dtype=np.uint32).tofile(f) # broadcast: 1
np.array([scalar], dtype=np.float32).tofile(f)
np.array([0], dtype=np.uint32).tofile(f) # broadcast: 0
input_operand_index = self.add_operand(i1_node.name, Operand.IOTYPE_INPUT)
np.array([input_operand_index], dtype=np.uint32).tofile(f)
elif i1_node.op == 'Const':
scalar = i1_node.attr['value'].tensor.float_val[0]
np.array([0], dtype=np.uint32).tofile(f)
input_operand_index = self.add_operand(i0_node.name, Operand.IOTYPE_INPUT)
np.array([input_operand_index], dtype=np.uint32).tofile(f)
np.array([1], dtype=np.uint32).tofile(f)
np.array([scalar], dtype=np.float32).tofile(f)
else:
np.array([0], dtype=np.uint32).tofile(f)
input_operand_index = self.add_operand(i0_node.name, Operand.IOTYPE_INPUT)
np.array([input_operand_index], dtype=np.uint32).tofile(f)
np.array([0], dtype=np.uint32).tofile(f)
input_operand_index = self.add_operand(i1_node.name, Operand.IOTYPE_INPUT)
np.array([input_operand_index], dtype=np.uint32).tofile(f)
output_operand_index = self.add_operand(node.name, Operand.IOTYPE_OUTPUT)
np.array([output_operand_index], dtype=np.uint32).tofile(f)
def dump_layers_to_file(self, f):
for node in self.nodes:
if node.name in self.converted_nodes:
continue
# conv2d with dilation generates very complex nodes, so handle it in special
if self.in_conv2d_scope(node.name):
if node.op == 'Conv2D':
self.dump_complex_conv2d_to_file(node, f)
continue
if node.op == 'Conv2D':
self.dump_simple_conv2d_to_file(node, f)
elif node.op == 'DepthToSpace':
self.dump_depth2space_to_file(node, f)
elif node.op == 'MirrorPad':
self.dump_mirrorpad_to_file(node, f)
elif node.op == 'Maximum':
self.dump_maximum_to_file(node, f)
elif node.op == 'Sub':
self.dump_mathbinary_to_file(node, f)
elif node.op == 'Add':
self.dump_mathbinary_to_file(node, f)
elif node.op == 'Mul':
self.dump_mathbinary_to_file(node, f)
elif node.op == 'RealDiv':
self.dump_mathbinary_to_file(node, f)
def dump_operands_to_file(self, f):
operands = sorted(self.name_operand_dict.values())
for operand in operands:
#print('{}'.format(operand))
np.array([operand.index, len(operand.name)], dtype=np.uint32).tofile(f)
f.write(operand.name.encode('utf-8'))
np.array([operand.iotype, operand.dtype], dtype=np.uint32).tofile(f)
np.array([operand.dims[0], operand.dims[1], operand.dims[2], operand.dims[3]], dtype=np.uint32).tofile(f)
def dump_to_file(self):
with open(self.outfile, 'wb') as f:
f.write(header.str.encode('utf-8'))
np.array([header.major, header.minor], dtype=np.uint32).tofile(f)
self.dump_layers_to_file(f)
self.dump_operands_to_file(f)
np.array([self.layer_number, len(self.name_operand_dict)], dtype=np.uint32).tofile(f)
def generate_name_node_dict(self):
for node in self.nodes:
self.name_node_dict[node.name] = node
def generate_output_names(self):
used_names = []
for node in self.nodes:
for input in node.input:
used_names.append(input)
for node in self.nodes:
if node.name not in used_names:
self.output_names.append(node.name)
def remove_identity(self):
id_nodes = []
id_dict = {}
for node in self.nodes:
if node.op == 'Identity':
name = node.name
input = node.input[0]
id_nodes.append(node)
# do not change the output name
if name in self.output_names:
self.name_node_dict[input].name = name
self.name_node_dict[name] = self.name_node_dict[input]
del self.name_node_dict[input]
else:
id_dict[name] = input
for idnode in id_nodes:
self.nodes.remove(idnode)
for node in self.nodes:
for i in range(len(node.input)):
input = node.input[i]
if input in id_dict:
node.input[i] = id_dict[input]
def generate_edges(self):
for node in self.nodes:
for input in node.input:
if input in self.edges:
self.edges[input].append(node)
else:
self.edges[input] = [node]
@staticmethod
def get_scope_name(name):
index = name.rfind('/')
if index == -1:
return ""
return name[0:index]
def in_conv2d_scope(self, name):
inner_scope = TFConverter.get_scope_name(name)
if inner_scope == "":
return False;
for scope in self.conv2d_scope_names:
index = inner_scope.find(scope)
if index == 0:
return True
return False
def generate_conv2d_scope_info(self):
# mostly, conv2d is a sub block in graph, get the scope name
for node in self.nodes:
if node.op == 'Conv2D':
scope = TFConverter.get_scope_name(node.name)
# for the case tf.nn.conv2d is called directly
if scope == '':
continue
# for the case tf.nn.conv2d is called within a scope
if scope + '/kernel' not in self.name_node_dict:
continue
self.conv2d_scope_names.add(scope)
# get the input name to the conv2d sub block
for node in self.nodes:
scope = TFConverter.get_scope_name(node.name)
if scope in self.conv2d_scope_names:
if node.op == 'Conv2D' or node.op == 'Shape':
for inp in node.input:
if TFConverter.get_scope_name(inp) != scope:
self.conv2d_scopename_inputname_dict[scope] = inp
def run(self):
self.generate_name_node_dict()
self.generate_output_names()
self.remove_identity()
self.generate_edges()
self.generate_conv2d_scope_info()
if self.dump4tb:
self.dump_for_tensorboard()
self.dump_to_file()
def convert_from_tensorflow(infile, outfile, dump4tb):
with open(infile, 'rb') as f:
# read the file in .proto format
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
nodes = graph_def.node
converter = TFConverter(graph_def, nodes, outfile, dump4tb)
converter.run()<|fim▁end|> | |
<|file_name|>test_base_polling_async.py<|end_file_name|><|fim▁begin|>#--------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#--------------------------------------------------------------------------
import base64
import json
import pickle
import re
from utils import HTTP_REQUESTS
from azure.core.pipeline._tools import is_rest
import types
import unittest
try:
from unittest import mock
except ImportError:
import mock
import pytest
from requests import Request, Response
from msrest import Deserializer
from azure.core.polling import async_poller, AsyncLROPoller
from azure.core.exceptions import DecodeError, HttpResponseError
from azure.core import AsyncPipelineClient
from azure.core.pipeline import PipelineResponse, AsyncPipeline, PipelineContext
from azure.core.pipeline.transport import AsyncioRequestsTransportResponse, AsyncHttpTransport
from azure.core.polling.async_base_polling import (
AsyncLROBasePolling,
)
from utils import ASYNCIO_REQUESTS_TRANSPORT_RESPONSES, request_and_responses_product, create_transport_response
from rest_client_async import AsyncTestRestClient
class SimpleResource:
"""An implementation of Python 3 SimpleNamespace.
Used to deserialize resource objects from response bodies where
no particular object type has been specified.
"""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __repr__(self):
keys = sorted(self.__dict__)
items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
return "{}({})".format(type(self).__name__, ", ".join(items))
def __eq__(self, other):
return self.__dict__ == other.__dict__
class BadEndpointError(Exception):
pass
TEST_NAME = 'foo'
RESPONSE_BODY = {'properties':{'provisioningState': 'InProgress'}}
ASYNC_BODY = json.dumps({ 'status': 'Succeeded' })
ASYNC_URL = 'http://dummyurlFromAzureAsyncOPHeader_Return200'
LOCATION_BODY = json.dumps({ 'name': TEST_NAME })
LOCATION_URL = 'http://dummyurlurlFromLocationHeader_Return200'
RESOURCE_BODY = json.dumps({ 'name': TEST_NAME })
RESOURCE_URL = 'http://subscriptions/sub1/resourcegroups/g1/resourcetype1/resource1'
ERROR = 'http://dummyurl_ReturnError'
POLLING_STATUS = 200
CLIENT = AsyncPipelineClient("http://example.org")
CLIENT.http_request_type = None
CLIENT.http_response_type = None
async def mock_run(client_self, request, **kwargs):
return TestBasePolling.mock_update(client_self.http_request_type, client_self.http_response_type, request.url)
CLIENT._pipeline.run = types.MethodType(mock_run, CLIENT)
@pytest.fixture
def client():
# The poller itself don't use it, so we don't need something functionnal
return AsyncPipelineClient("https://baseurl")
@pytest.fixture
def async_pipeline_client_builder():
"""Build a client that use the "send" callback as final transport layer
send will receive "request" and kwargs as any transport layer
"""
def create_client(send_cb):
class TestHttpTransport(AsyncHttpTransport):
async def open(self): pass
async def close(self): pass
async def __aexit__(self, *args, **kwargs): pass
async def send(self, request, **kwargs):
return await send_cb(request, **kwargs)
return AsyncPipelineClient(
'http://example.org/',
pipeline=AsyncPipeline(
transport=TestHttpTransport()
)
)
return create_client
@pytest.fixture
def deserialization_cb():
def cb(pipeline_response):
return json.loads(pipeline_response.http_response.text())
return cb
@pytest.fixture
def polling_response():
polling = AsyncLROBasePolling()
headers = {}
response = Response()
response.headers = headers
response.status_code = 200
polling._pipeline_response = PipelineResponse(
None,
AsyncioRequestsTransportResponse(
None,
response,
),
PipelineContext(None)
)
polling._initial_response = polling._pipeline_response
return polling, headers
def test_base_polling_continuation_token(client, polling_response):
polling, _ = polling_response
continuation_token = polling.get_continuation_token()
assert isinstance(continuation_token, str)
polling_args = AsyncLROBasePolling.from_continuation_token(
continuation_token,
deserialization_callback="deserialization_callback",
client=client,
)
new_polling = AsyncLROBasePolling()
new_polling.initialize(*polling_args)
@pytest.mark.asyncio
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(ASYNCIO_REQUESTS_TRANSPORT_RESPONSES))
async def test_post(async_pipeline_client_builder, deserialization_cb, http_request, http_response):
# Test POST LRO with both Location and Operation-Location
# The initial response contains both Location and Operation-Location, a 202 and no Body
initial_response = TestBasePolling.mock_send(
http_request,
http_response,
'POST',
202,
{
'location': 'http://example.org/location',
'operation-location': 'http://example.org/async_monitor',
},
''
)
async def send(request, **kwargs):
assert request.method == 'GET'
if request.url == 'http://example.org/location':
return TestBasePolling.mock_send(
http_request,
http_response,
'GET',
200,
body={'location_result': True}
).http_response
elif request.url == 'http://example.org/async_monitor':
return TestBasePolling.mock_send(
http_request,
http_response,
'GET',
200,
body={'status': 'Succeeded'}
).http_response
else:
pytest.fail("No other query allowed")
client = async_pipeline_client_builder(send)
# LRO options with Location final state
poll = async_poller(
client,
initial_response,
deserialization_cb,
AsyncLROBasePolling(0))
result = await poll
assert result['location_result'] == True
# Location has no body
async def send(request, **kwargs):
assert request.method == 'GET'
if request.url == 'http://example.org/location':
return TestBasePolling.mock_send(
http_request,
http_response,
'GET',
200,
body=None
).http_response
elif request.url == 'http://example.org/async_monitor':
return TestBasePolling.mock_send(
http_request,
http_response,
'GET',
200,
body={'status': 'Succeeded'}
).http_response
else:
pytest.fail("No other query allowed")
client = async_pipeline_client_builder(send)
poll = async_poller(
client,
initial_response,
deserialization_cb,
AsyncLROBasePolling(0))
result = await poll
assert result is None
@pytest.mark.asyncio
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(ASYNCIO_REQUESTS_TRANSPORT_RESPONSES))
async def test_post_resource_location(async_pipeline_client_builder, deserialization_cb, http_request, http_response):
# ResourceLocation
# The initial response contains both Location and Operation-Location, a 202 and no Body
initial_response = TestBasePolling.mock_send(
http_request,
http_response,
'POST',
202,
{
'operation-location': 'http://example.org/async_monitor',
},
''
)
async def send(request, **kwargs):
assert request.method == 'GET'
if request.url == 'http://example.org/resource_location':
return TestBasePolling.mock_send(
http_request,
http_response,
'GET',
200,
body={'location_result': True}
).http_response
elif request.url == 'http://example.org/async_monitor':
return TestBasePolling.mock_send(
http_request,
http_response,
'GET',
200,
body={'status': 'Succeeded', 'resourceLocation': 'http://example.org/resource_location'}
).http_response
else:
pytest.fail("No other query allowed")
client = async_pipeline_client_builder(send)
poll = async_poller(
client,
initial_response,
deserialization_cb,
AsyncLROBasePolling(0))
result = await poll
assert result['location_result'] == True
class TestBasePolling(object):
convert = re.compile('([a-z0-9])([A-Z])')
@staticmethod
def mock_send(http_request, http_response, method, status, headers=None, body=RESPONSE_BODY):
if headers is None:
headers = {}
response = Response()
response._content_consumed = True
response._content = json.dumps(body).encode('ascii') if body is not None else None
response.request = Request()
response.request.method = method
response.request.url = RESOURCE_URL
response.request.headers = {
'x-ms-client-request-id': '67f4dd4e-6262-45e1-8bed-5c45cf23b6d9'
}
response.status_code = status
response.headers = headers
response.headers.update({"content-type": "application/json; charset=utf8"})
response.reason = "OK"
if is_rest(http_request):
request = http_request(
response.request.method,
response.request.url,
headers=response.request.headers,
content=body,
)
else:
request = CLIENT._request(
response.request.method,
response.request.url,
None, # params
response.request.headers,
body,
None, # form_content
None # stream_content
)
response = create_transport_response(http_response, request, response)
if is_rest(http_response):
response.body()
return PipelineResponse(
request,
response,
None # context
)
@staticmethod
def mock_update(http_request, http_response, url, headers=None):
response = Response()
response._content_consumed = True
response.request = mock.create_autospec(Request)
response.request.method = 'GET'
response.headers = headers or {}
response.headers.update({"content-type": "application/json; charset=utf8"})
response.reason = "OK"
if url == ASYNC_URL:
response.request.url = url
response.status_code = POLLING_STATUS
response._content = ASYNC_BODY.encode('ascii')
response.randomFieldFromPollAsyncOpHeader = None
elif url == LOCATION_URL:
response.request.url = url
response.status_code = POLLING_STATUS
response._content = LOCATION_BODY.encode('ascii')
response.randomFieldFromPollLocationHeader = None
elif url == ERROR:
raise BadEndpointError("boom")
elif url == RESOURCE_URL:
response.request.url = url
response.status_code = POLLING_STATUS
response._content = RESOURCE_BODY.encode('ascii')
else:
raise Exception('URL does not match')
request = http_request(
response.request.method,
response.request.url,
)
response = create_transport_response(http_response, request, response)
if is_rest(http_response):
response.body()
return PipelineResponse(
request,
response,
None # context
)
@staticmethod
def mock_outputs(pipeline_response):
response = pipeline_response.http_response
try:
body = json.loads(response.text())
except ValueError:
raise DecodeError("Impossible to deserialize")
body = {TestBasePolling.convert.sub(r'\1_\2', k).lower(): v
for k, v in body.items()}
properties = body.setdefault('properties', {})
if 'name' in body:
properties['name'] = body['name']
if properties:
properties = {TestBasePolling.convert.sub(r'\1_\2', k).lower(): v
for k, v in properties.items()}
del body['properties']
body.update(properties)
resource = SimpleResource(**body)
else:
raise DecodeError("Impossible to deserialize")
resource = SimpleResource(**body)
return resource
@staticmethod
def mock_deserialization_no_body(pipeline_response):
"""Use this mock when you don't expect a return (last body irrelevant)
"""
return None
@pytest.mark.asyncio
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(ASYNCIO_REQUESTS_TRANSPORT_RESPONSES))
async def test_long_running_put(http_request, http_response):
#TODO: Test custom header field
CLIENT.http_request_type = http_request
CLIENT.http_response_type = http_response
# Test throw on non LRO related status code
response = TestBasePolling.mock_send(
http_request, http_response, 'PUT', 1000, {}
)
with pytest.raises(HttpResponseError):
await async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
AsyncLROBasePolling(0))
# Test with no polling necessary
response_body = {
'properties':{'provisioningState': 'Succeeded'},
'name': TEST_NAME
}
response = TestBasePolling.mock_send(
http_request,
http_response,
'PUT', 201,
{}, response_body
)
def no_update_allowed(url, headers=None):
raise ValueError("Should not try to update")
polling_method = AsyncLROBasePolling(0)
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
polling_method
)
assert poll.name == TEST_NAME
assert not hasattr(polling_method._pipeline_response, 'randomFieldFromPollAsyncOpHeader')
# Test polling from operation-location header
response = TestBasePolling.mock_send(
http_request,
http_response,
'PUT', 201,
{'operation-location': ASYNC_URL})
polling_method = AsyncLROBasePolling(0)
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
polling_method)
assert poll.name == TEST_NAME
assert not hasattr(polling_method._pipeline_response, 'randomFieldFromPollAsyncOpHeader')
# Test polling location header
response = TestBasePolling.mock_send(
http_request,
http_response,
'PUT', 201,
{'location': LOCATION_URL})
polling_method = AsyncLROBasePolling(0)
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
polling_method)
assert poll.name == TEST_NAME
assert polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollLocationHeader is None
# Test polling initial payload invalid (SQLDb)
response_body = {} # Empty will raise
response = TestBasePolling.mock_send(
http_request,
http_response,
'PUT', 201,
{'location': LOCATION_URL}, response_body)
polling_method = AsyncLROBasePolling(0)
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
polling_method)
assert poll.name == TEST_NAME
assert polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollLocationHeader is None
# Test fail to poll from operation-location header
response = TestBasePolling.mock_send(
http_request,
http_response,
'PUT', 201,
{'operation-location': ERROR})
with pytest.raises(BadEndpointError):
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
AsyncLROBasePolling(0))
# Test fail to poll from location header
response = TestBasePolling.mock_send(
http_request,
http_response,
'PUT', 201,
{'location': ERROR})
with pytest.raises(BadEndpointError):
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
AsyncLROBasePolling(0))
@pytest.mark.asyncio
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(ASYNCIO_REQUESTS_TRANSPORT_RESPONSES))
async def test_long_running_patch(http_request, http_response):
CLIENT.http_request_type = http_request
CLIENT.http_response_type = http_response
# Test polling from location header
response = TestBasePolling.mock_send(
http_request,
http_response,
'PATCH', 202,
{'location': LOCATION_URL},
body={'properties':{'provisioningState': 'Succeeded'}})<|fim▁hole|> polling_method)
assert poll.name == TEST_NAME
assert polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollLocationHeader is None
# Test polling from operation-location header
response = TestBasePolling.mock_send(
http_request,
http_response,
'PATCH', 202,
{'operation-location': ASYNC_URL},
body={'properties':{'provisioningState': 'Succeeded'}})
polling_method = AsyncLROBasePolling(0)
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
polling_method)
assert poll.name == TEST_NAME
assert not hasattr(polling_method._pipeline_response, 'randomFieldFromPollAsyncOpHeader')
# Test polling from location header
response = TestBasePolling.mock_send(
http_request,
http_response,
'PATCH', 200,
{'location': LOCATION_URL},
body={'properties':{'provisioningState': 'Succeeded'}})
polling_method = AsyncLROBasePolling(0)
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
polling_method)
assert poll.name == TEST_NAME
assert polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollLocationHeader is None
# Test polling from operation-location header
response = TestBasePolling.mock_send(
http_request,
http_response,
'PATCH', 200,
{'operation-location': ASYNC_URL},
body={'properties':{'provisioningState': 'Succeeded'}})
polling_method = AsyncLROBasePolling(0)
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
polling_method)
assert poll.name == TEST_NAME
assert not hasattr(polling_method._pipeline_response, 'randomFieldFromPollAsyncOpHeader')
# Test fail to poll from operation-location header
response = TestBasePolling.mock_send(
http_request,
http_response,
'PATCH', 202,
{'operation-location': ERROR})
with pytest.raises(BadEndpointError):
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
AsyncLROBasePolling(0))
# Test fail to poll from location header
response = TestBasePolling.mock_send(
http_request,
http_response,
'PATCH', 202,
{'location': ERROR})
with pytest.raises(BadEndpointError):
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
AsyncLROBasePolling(0))
@pytest.mark.asyncio
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(ASYNCIO_REQUESTS_TRANSPORT_RESPONSES))
async def test_long_running_delete(http_request, http_response):
# Test polling from operation-location header
CLIENT.http_request_type = http_request
CLIENT.http_response_type = http_response
response = TestBasePolling.mock_send(
http_request,
http_response,
'DELETE', 202,
{'operation-location': ASYNC_URL},
body=""
)
polling_method = AsyncLROBasePolling(0)
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_deserialization_no_body,
polling_method)
assert poll is None
assert polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollAsyncOpHeader is None
@pytest.mark.asyncio
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(ASYNCIO_REQUESTS_TRANSPORT_RESPONSES))
async def test_long_running_post(http_request, http_response):
CLIENT.http_request_type = http_request
CLIENT.http_response_type = http_response
# Test polling from operation-location header
response = TestBasePolling.mock_send(
http_request,
http_response,
'POST', 201,
{'operation-location': ASYNC_URL},
body={'properties':{'provisioningState': 'Succeeded'}})
polling_method = AsyncLROBasePolling(0)
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_deserialization_no_body,
polling_method)
assert polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollAsyncOpHeader is None
# Test polling from operation-location header
response = TestBasePolling.mock_send(
http_request,
http_response,
'POST', 202,
{'operation-location': ASYNC_URL},
body={'properties':{'provisioningState': 'Succeeded'}})
polling_method = AsyncLROBasePolling(0)
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_deserialization_no_body,
polling_method)
assert polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollAsyncOpHeader is None
# Test polling from location header
response = TestBasePolling.mock_send(
http_request,
http_response,
'POST', 202,
{'location': LOCATION_URL},
body={'properties':{'provisioningState': 'Succeeded'}})
polling_method = AsyncLROBasePolling(0)
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
polling_method)
assert poll.name == TEST_NAME
assert polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollLocationHeader is None
# Test fail to poll from operation-location header
response = TestBasePolling.mock_send(
http_request,
http_response,
'POST', 202,
{'operation-location': ERROR})
with pytest.raises(BadEndpointError):
await async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
AsyncLROBasePolling(0))
# Test fail to poll from location header
response = TestBasePolling.mock_send(
http_request,
http_response,
'POST', 202,
{'location': ERROR})
with pytest.raises(BadEndpointError):
await async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
AsyncLROBasePolling(0))
@pytest.mark.asyncio
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(ASYNCIO_REQUESTS_TRANSPORT_RESPONSES))
async def test_long_running_negative(http_request, http_response):
global LOCATION_BODY
global POLLING_STATUS
CLIENT.http_request_type = http_request
CLIENT.http_response_type = http_response
# Test LRO PUT throws for invalid json
LOCATION_BODY = '{'
response = TestBasePolling.mock_send(
http_request,
http_response,
'POST', 202,
{'location': LOCATION_URL})
poll = async_poller(
CLIENT,
response,
TestBasePolling.mock_outputs,
AsyncLROBasePolling(0)
)
with pytest.raises(DecodeError):
await poll
LOCATION_BODY = '{\'"}'
response = TestBasePolling.mock_send(
http_request,
http_response,
'POST', 202,
{'location': LOCATION_URL})
poll = async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
AsyncLROBasePolling(0))
with pytest.raises(DecodeError):
await poll
LOCATION_BODY = '{'
POLLING_STATUS = 203
response = TestBasePolling.mock_send(
http_request,
http_response,
'POST', 202,
{'location': LOCATION_URL})
poll = async_poller(CLIENT, response,
TestBasePolling.mock_outputs,
AsyncLROBasePolling(0))
with pytest.raises(HttpResponseError) as error: # TODO: Node.js raises on deserialization
await poll
assert error.value.continuation_token == base64.b64encode(pickle.dumps(response)).decode('ascii')
LOCATION_BODY = json.dumps({ 'name': TEST_NAME })
POLLING_STATUS = 200
@pytest.mark.asyncio
@pytest.mark.parametrize("http_request,http_response", request_and_responses_product(ASYNCIO_REQUESTS_TRANSPORT_RESPONSES))
async def test_post_final_state_via(async_pipeline_client_builder, deserialization_cb, http_request, http_response):
# Test POST LRO with both Location and Operation-Location
CLIENT.http_request_type = http_request
CLIENT.http_response_type = http_response
# The initial response contains both Location and Operation-Location, a 202 and no Body
initial_response = TestBasePolling.mock_send(
http_request,
http_response,
'POST',
202,
{
'location': 'http://example.org/location',
'operation-location': 'http://example.org/async_monitor',
},
''
)
async def send(request, **kwargs):
assert request.method == 'GET'
if request.url == 'http://example.org/location':
return TestBasePolling.mock_send(
http_request,
http_response,
'GET',
200,
body={'location_result': True}
).http_response
elif request.url == 'http://example.org/async_monitor':
return TestBasePolling.mock_send(
http_request,
http_response,
'GET',
200,
body={'status': 'Succeeded'}
).http_response
else:
pytest.fail("No other query allowed")
client = async_pipeline_client_builder(send)
# Test 1, LRO options with Location final state
poll = async_poller(
client,
initial_response,
deserialization_cb,
AsyncLROBasePolling(0, lro_options={"final-state-via": "location"}))
result = await poll
assert result['location_result'] == True
# Test 2, LRO options with Operation-Location final state
poll = async_poller(
client,
initial_response,
deserialization_cb,
AsyncLROBasePolling(0, lro_options={"final-state-via": "operation-location"}))
result = await poll
assert result['status'] == 'Succeeded'
# Test 3, "do the right thing" and use Location by default
poll = async_poller(
client,
initial_response,
deserialization_cb,
AsyncLROBasePolling(0))
result = await poll
assert result['location_result'] == True
# Test 4, location has no body
async def send(request, **kwargs):
assert request.method == 'GET'
if request.url == 'http://example.org/location':
return TestBasePolling.mock_send(
http_request,
http_response,
'GET',
200,
body=None
).http_response
elif request.url == 'http://example.org/async_monitor':
return TestBasePolling.mock_send(
http_request,
http_response,
'GET',
200,
body={'status': 'Succeeded'}
).http_response
else:
pytest.fail("No other query allowed")
client = async_pipeline_client_builder(send)
poll = async_poller(
client,
initial_response,
deserialization_cb,
AsyncLROBasePolling(0, lro_options={"final-state-via": "location"}))
result = await poll
assert result is None
@pytest.mark.asyncio
@pytest.mark.parametrize("http_request", HTTP_REQUESTS)
async def test_final_get_via_location(port, http_request, deserialization_cb):
client = AsyncTestRestClient(port)
request = http_request(
"PUT",
"http://localhost:{}/polling/polling-with-options".format(port),
)
request.set_json_body({"hello": "world!"})
initial_response = await client._client._pipeline.run(request)
poller = AsyncLROPoller(
client._client,
initial_response,
deserialization_cb,
AsyncLROBasePolling(0, lro_options={"final-state-via": "location"}),
)
result = await poller.result()
assert result == {"returnedFrom": "locationHeaderUrl"}<|fim▁end|> | polling_method = AsyncLROBasePolling(0)
poll = await async_poller(CLIENT, response,
TestBasePolling.mock_outputs, |
<|file_name|>app_originate.py<|end_file_name|><|fim▁begin|># AsteriskLint -- an Asterisk PBX config syntax checker
# Copyright (C) 2018 Walter Doekes, OSSO B.V.
#
# 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.
#<|fim▁hole|>
class AppOrExten(AppArg):
def validate(self, arg, where):
if arg not in ('app', 'exten'):
E_APP_ARG_BADOPT(
where, argno=self.argno, app=self.app, opts=arg)
class Originate(App):
def __init__(self):
super().__init__(
# arg1 means Application-name or Context
args=[AppArg('tech_data'), AppOrExten('type'), AppArg('arg1'),
AppArg('arg2'), AppArg('arg3'), AppArg('timeout')],
min_args=3)
def register(app_loader):
app_loader.register(Originate())<|fim▁end|> | # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from ..base import E_APP_ARG_BADOPT, App, AppArg
|
<|file_name|>areEqual.js<|end_file_name|><|fim▁begin|>/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var aStackPool = [];
var bStackPool = [];
/**
* Checks if two values are equal. Values may be primitives, arrays, or objects.
* Returns true if both arguments have the same keys and values.
*
* @see http://underscorejs.org
* @copyright 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
* @license MIT
*/
function areEqual(a, b) {
var aStack = aStackPool.length ? aStackPool.pop() : [];
var bStack = bStackPool.length ? bStackPool.pop() : [];
var result = eq(a, b, aStack, bStack);
aStack.length = 0;
bStack.length = 0;
aStackPool.push(aStack);
bStackPool.push(bStack);
return result;
}
function eq(a, b, aStack, bStack) {
if (a === b) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
return a !== 0 || 1 / a == 1 / b;
}
if (a == null || b == null) {
// a or b can be `null` or `undefined`
return false;
}
if (typeof a != 'object' || typeof b != 'object') {
return false;
}
var objToStr = Object.prototype.toString;
var className = objToStr.call(a);
if (className != objToStr.call(b)) {
return false;
}
switch (className) {
case '[object String]':
return a == String(b);
case '[object Number]':
return isNaN(a) || isNaN(b) ? false : a == Number(b);
case '[object Date]':
case '[object Boolean]':
return +a == +b;
case '[object RegExp]':
return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase;
}
// Assume equality for cyclic structures.
var length = aStack.length;
while (length--) {
if (aStack[length] == a) {
return bStack[length] == b;
}
}
aStack.push(a);
bStack.push(b);
var size = 0;
// Recursively compare objects and arrays.
if (className === '[object Array]') {
size = a.length;
if (size !== b.length) {
return false;
}
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!eq(a[size], b[size], aStack, bStack)) {
return false;<|fim▁hole|> if (a.constructor !== b.constructor) {
return false;
}
if (a.hasOwnProperty('valueOf') && b.hasOwnProperty('valueOf')) {
return a.valueOf() == b.valueOf();
}
var keys = Object.keys(a);
if (keys.length != Object.keys(b).length) {
return false;
}
for (var i = 0; i < keys.length; i++) {
if (!eq(a[keys[i]], b[keys[i]], aStack, bStack)) {
return false;
}
}
}
aStack.pop();
bStack.pop();
return true;
}
module.exports = areEqual;<|fim▁end|> | }
}
} else { |
<|file_name|>EBrowserView.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2014 The AppCan Open Source Project.
*
* 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, see <http://www.gnu.org/licenses/>.
*
*/
package org.zywx.wbpalmstar.engine;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.inputmethod.InputMethodManager;
import android.webkit.DownloadListener;
import android.webkit.WebView;
import android.widget.FrameLayout;
import org.json.JSONObject;
import org.zywx.wbpalmstar.acedes.ACEDes;
import org.zywx.wbpalmstar.acedes.EXWebViewClient;
import org.zywx.wbpalmstar.base.BDebug;
import org.zywx.wbpalmstar.base.vo.KernelInfoVO;
import org.zywx.wbpalmstar.engine.EBrowserHistory.EHistoryEntry;
import org.zywx.wbpalmstar.engine.universalex.EUExCallback;
import org.zywx.wbpalmstar.engine.universalex.EUExManager;
import org.zywx.wbpalmstar.engine.universalex.EUExWindow;
import org.zywx.wbpalmstar.widgetone.dataservice.WWidgetData;
import java.lang.reflect.Method;
import java.util.Map;
public class EBrowserView extends WebView implements View.OnLongClickListener,
DownloadListener {
public static final String CONTENT_MIMETYPE_HTML = "text/html";
public static final String CONTENT_DEFAULT_CODE = "utf-8";
public static final int F_PRINT_TYPE_DOM_TREE = 0;
public static final int F_PRINT_TYPE_DISPLAY_TREE = 1;
public static final int F_PRINT_TYPE_RENDER_TREE = 2;
public static final int F_PRINT_TYPE_DRAW_PAGE = 3;
private int mType;
private String mName;
private String mQuery;
private String mRelativeUrl;
private Context mContext;
private EUExManager mUExMgr;
private EBrowserBaseSetting mBaSetting;
private EBrowserWindow mBroWind;
private boolean mShouldOpenInSystem;
private boolean mOpaque;
private boolean mOAuth;
private boolean mWebApp;
private boolean mSupportZoom;
private int mDateType;
private boolean mDestroyed;
private EBrwViewAnim mViewAnim;
private EXWebViewClient mEXWebViewClient;
private Method mDismissZoomControl;
private int mDownloadCallback = 0; // 0 下载不回调,使用引擎下载; 1 下载回调给主窗口,前端自己下载; 2 下载回调给当前窗口,前端自己下载;
// use for debug
private Method mDumpDisplayTree;
private Method mDumpDomTree;
private Method mDumpRenderTree;
private Method mDrawPage;
private int mMyCountId;
private int mScrollDistance = 10;
private EUExWindow callback;
private boolean mIsNeedScroll = false;
private boolean isMultilPopoverFlippingEnbaled = false;
private boolean isSupportSlideCallback = false;//is need callback,set by API interface.
private boolean disturbLongPressGesture = false;
private int mThreshold = 5;
private OnEBrowserViewChangeListener mBrowserViewChangeListener;
public static boolean sHardwareAccelerate = true;//配置全部WebView是否硬件加速,默认开启,config.xml 配置关闭
public EBrowserView(Context context, int inType, EBrowserWindow inParent) {
super(context);
mMyCountId = EBrowser.assignCountID();
mBroWind = inParent;
mContext = context;
mType = inType;
initPrivateVoid();
setOnLongClickListener(this);
setDownloadListener(this);
setACEHardwareAccelerate();
}
public EUExManager getEUExManager() {
return mUExMgr;
}
public void setScrollCallBackContex(EUExWindow callback) {
this.callback = callback;
}
public float getCustomScale(){
float nowScale = 1.0f;
if (Build.VERSION.SDK_INT <= 18) {
nowScale = getScale();
}
return nowScale;
}
public void init() {
setInitialScale(100);
setVerticalScrollbarOverlay(true);
setHorizontalScrollbarOverlay(true);
setLayoutAnimation(null);
setAnimation(null);
setNetworkAvailable(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (mBroWind!=null){
int debug = mBroWind.getWidget().m_appdebug;
setWebContentsDebuggingEnabled(debug == 1 ? true : false);
}
}
if (Build.VERSION.SDK_INT <= 7) {
if (mBaSetting == null) {
mBaSetting = new EBrowserSetting(this);
mBaSetting.initBaseSetting(mWebApp);
setWebViewClient(mEXWebViewClient = new CBrowserWindow());
setWebChromeClient(new CBrowserMainFrame(mContext));
}
} else {
if (mBaSetting == null) {
mBaSetting = new EBrowserSetting7(this);
mBaSetting.initBaseSetting(mWebApp);
setWebViewClient(mEXWebViewClient = new CBrowserWindow7());
setWebChromeClient(new CBrowserMainFrame7(mContext));
}
}
mUExMgr = new EUExManager(mContext);
mUExMgr.addJavascriptInterface(this);
}
private void setACEHardwareAccelerate() {
if (!sHardwareAccelerate) {
setLayerType(LAYER_TYPE_SOFTWARE, null);
} else {
closeHardwareForSpecificString();
}
}
@Override
protected void onAttachedToWindow() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (!isHardwareAccelerated()) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
BDebug.i("setLayerType","LAYER_TYPE_SOFTWARE");
} else {
closeHardwareForSpecificString();
}
}
super.onAttachedToWindow();
}
private void closeHardwareForSpecificString() {
WWidgetData widgetData = getCurrentWidget();
if (widgetData != null) {
for (String noHardware : widgetData.noHardwareList) {
String str = noHardware.trim();
// 手机型号、Android系统定制商、硬件制造商
if (Build.MODEL.trim().equals(str)
|| Build.BRAND.trim().equals(str)
|| Build.MANUFACTURER.trim().equals(str)) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
BDebug.i("setLayerType", "LAYER_TYPE_SOFTWARE");
break;
}
}
}
}
@Override
public boolean isHardwareAccelerated() {
//confirm view is attached to a window
boolean isHardwareAccelerated = super.isHardwareAccelerated();
BDebug.v("isHardwareAccelerated", isHardwareAccelerated);
return isHardwareAccelerated;
}
@Override
public void loadUrl(String url) {
if (mDestroyed) {
return;
}
BDebug.i("loadUrl url " + url);
try {
if (url.startsWith("javascript:") && Build.VERSION.SDK_INT >= 19) {
evaluateJavascript(url.substring("javascript:".length()), null);
} else {
super.loadUrl(url);
}
} catch (Exception e) {
;
}
}
@SuppressLint("NewApi")
@Override
public void loadUrl(String url, Map<String, String> extraHeaders) {
if (mDestroyed) {
return;
}
try {
super.loadUrl(url, extraHeaders);
} catch (Exception e) {
;
}
}
@Override
public void loadData(String data, String mimeType, String encoding) {
if (mDestroyed) {
return;
}
try {
super.loadData(data, mimeType, encoding);
} catch (Exception e) {
;
}
}
@Override
public void loadDataWithBaseURL(String baseUrl, String data,
String mimeType, String encoding, String historyUrl) {
if (mDestroyed) {
return;
}
try {
super.loadDataWithBaseURL(baseUrl, data, mimeType, encoding,
historyUrl);
} catch (Exception e) {
;
}
}
public boolean checkType(int inType) {
return inType == mType;
}
public int getMyId() {
return mMyCountId;
}
public void setDefaultFontSize(int size) {
if (mDestroyed) {
return;
}
mBaSetting.setDefaultFontSize(size);
}
public void setSupportZoom() {
mSupportZoom = true;
mBaSetting.setSupportZoom();
}
public boolean supportZoom() {
return mSupportZoom;
}
@SuppressLint("NewApi")
private void initPrivateVoid() {
Class[] nullParm = {};
try {
mDismissZoomControl = WebView.class.getDeclaredMethod(
"dismissZoomControl", nullParm);
mDismissZoomControl.setAccessible(true);
} catch (Exception e) {
;
}
try {
mDumpDisplayTree = WebView.class.getDeclaredMethod(
"dumpDisplayTree", nullParm);
mDumpDisplayTree.setAccessible(true);
} catch (Exception e) {
;
}
Class[] booleanParam = {boolean.class};
try {
mDumpDomTree = WebView.class.getDeclaredMethod("dumpDomTree",
booleanParam);
mDumpDomTree.setAccessible(true);
} catch (Exception e) {
;
}
try {
mDumpRenderTree = WebView.class.getDeclaredMethod("dumpRenderTree",
booleanParam);
mDumpRenderTree.setAccessible(true);
} catch (Exception e) {
;
}
try {
Class[] canvasParam = {Canvas.class};
mDrawPage = WebView.class
.getDeclaredMethod("drawPage", canvasParam);
mDrawPage.setAccessible(true);
} catch (Exception e) {
;
}
if (Build.VERSION.SDK_INT >= 9) {
setOverScrollMode(2);
return;
}
try {
Class[] intParam = {int.class};
Method setOverScrollMode = WebView.class.getDeclaredMethod(
"setOverScrollMode", intParam);
setOverScrollMode.invoke(this, 2);
} catch (Exception e) {
;
}
}
public void dumpPageInfo(int type) {
switch (type) {
case F_PRINT_TYPE_DOM_TREE:
myDumpDomTree();
break;
case F_PRINT_TYPE_DISPLAY_TREE:
myDumpDisplayTree();
break;
case F_PRINT_TYPE_RENDER_TREE:
myDumpRenderTree();
break;
case F_PRINT_TYPE_DRAW_PAGE:
break;
}
}
// protected void setLayerTypeForHeighVersion() {
// // if(Build.VERSION.SDK_INT < 11){
// // return;
// // }
// // String MODEL = Build.MODEL;
// // String MANUFACTURER = Build.MANUFACTURER;
// // if(null != MODEL && null != MANUFACTURER){
// // MODEL = MODEL.toLowerCase();
// // MANUFACTURER = MANUFACTURER.toLowerCase();
// // if((MODEL.contains("9508") || MODEL.contains("9500")) &&
// // MANUFACTURER.contains("samsung")){
// // return;
// // }
// // }
// // Paint paint = new Paint();
// // paint.setColor(0x00000000);
// // if(isHardwareAccelerated()){
// // setLayerType(View.LAYER_TYPE_SOFTWARE, null);
// // }
// }
// @SuppressLint("NewApi")
// @Override
// protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// if (Build.VERSION.SDK_INT >= 11) {
// String MODEL = Build.MODEL;
// String MANUFACTURER = Build.MANUFACTURER;
// if (null != MODEL && null != MANUFACTURER) {
// MODEL = MODEL.toLowerCase();
// MANUFACTURER = MANUFACTURER.toLowerCase();
// if ((MODEL.contains("9508") || MODEL.contains("9500"))
// && MANUFACTURER.contains("samsung")) {
// if (isHardwareAccelerated()) {
// setLayerType(View.LAYER_TYPE_SOFTWARE, null);
// }
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// return;
// }
// }
// setLayerType(View.LAYER_TYPE_SOFTWARE, null);
// invalidate();
// }
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// }
@SuppressLint("NewApi")
public void destroyControl() {
if (null != mDismissZoomControl) {
try {
mDismissZoomControl.invoke(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@SuppressLint("NewApi")
private void pauseCore() {
if (Build.VERSION.SDK_INT >= 11) {
super.onPause();
} else {
try {
Class[] nullParm = {};
Method pause = WebView.class.getDeclaredMethod("onPause",
nullParm);
pause.setAccessible(true);
pause.invoke(this);
} catch (Exception e) {
;
}
}
}
@SuppressLint("NewApi")
private void resumeCore() {
if (Build.VERSION.SDK_INT >= 11) {
super.onResume();
} else {
try {
Class[] nullParm = {};
Method resume = WebView.class.getDeclaredMethod("onResume",
nullParm);
resume.setAccessible(true);
resume.invoke(this);
} catch (Exception e) {
;
}
}
}
public void myDumpDisplayTree() {
if (null != mDumpDisplayTree) {
try {
mDumpDisplayTree.invoke(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void myDumpDomTree() {
if (null != mDumpDomTree) {
try {
mDumpDomTree.invoke(this, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void myDumpRenderTree() {
if (null != mDumpRenderTree) {
try {
mDumpRenderTree.invoke(this, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void myDrawPage(Canvas canvas) {
if (null != mDrawPage) {
try {
mDrawPage.invoke(this, canvas);
} catch (Exception e) {
e.printStackTrace();
}<|fim▁hole|> public boolean onTouchEvent(MotionEvent ev) {
if (mDestroyed) {
return false;
}
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
if (!isFocused()) {
strugglefoucs();
}
onScrollChanged(getScrollX(), getScrollY(), getScrollX(), getScrollY());
if (mIsNeedScroll) {
//modify no-response-for-onclick-event
int temp_ScrollY = this.getScrollY();
this.scrollTo(this.getScrollX(), this.getScrollY() + 1);
this.scrollTo(this.getScrollX(), temp_ScrollY);
}
setMultilPopoverFlippingEnbaled();
break;
case MotionEvent.ACTION_MOVE:
setMultilPopoverFlippingEnbaled();
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
break;
}
return super.onTouchEvent(ev);
}
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
return super.onGenericMotionEvent(event); //To change body of overridden methods use File | Settings | File Templates.
}
public void setIsMultilPopoverFlippingEnbaled(boolean isEnabled) {
isMultilPopoverFlippingEnbaled = isEnabled;
setMultilPopoverFlippingEnbaled();
}
private void setMultilPopoverFlippingEnbaled() {
View parentBounceView = (View) this.getParent();
if (parentBounceView != null && parentBounceView instanceof EBounceView) {
ViewParent parentViewPager = parentBounceView.getParent();
if (parentViewPager != null && parentViewPager instanceof ViewPager) {
parentViewPager.requestDisallowInterceptTouchEvent(isMultilPopoverFlippingEnbaled);
}
}
}
private void strugglefoucs() {
requestFocus();
/**
* InputManager.get().hideSoftInput(getWindowToken(), 0, null);
* Log.d("ldx", "-------------- view in: " + mName);
*
* Log.d("ldx", "hasFocus: " + hasFocus()); Log.d("ldx", "isFocused: " +
* isFocused());
*
* try{ Class[] nullParam = {}; Method clearHelpers =
* WebView.class.getDeclaredMethod("clearHelpers", nullParam);
* clearHelpers.setAccessible(true); clearHelpers.invoke(this); }catch
* (Exception e) { e.printStackTrace(); } Log.d("ldx",
* "-------------- --------------");
*
* boolean Ac1 = InputManager.get().isActive(); boolean Ac2 =
* InputManager.get().isActive(this); if(Ac1){
* InputManager.get().hideSoftInput(this.getWindowToken(), 0, null); }
* Log.d("ldx", "imm Ac1: " + Ac1); Log.d("ldx", "imm Ac2: " + Ac2); int
* childCount = getChildCount(); Log.d("ldx", "childCount: " +
* childCount); for(int i = 0; i < childCount; ++i){ View child =
* getChildAt(i); boolean Ac3 = InputManager.get().isActive(child);
* Log.d("ldx", "imm Ac3: " + Ac3); if(Ac3){
* InputManager.get().hideSoftInput(child.getWindowToken(), 0, null); }
* child.clearFocus(); } boolean requestFocusOk = requestFocus();
* removeAllViews();
*
* Log.d("ldx", "requestFocusOk: " + requestFocusOk);
**/
// int childCount1 = getChildCount();
// Log.d("ldx", "childCount1: " + childCount1);
Log.d("ldx", "hasFocus: " + hasFocus());
Log.d("ldx", "isFocused: " + isFocused());
Log.d("ldx", "-------------- view out: " + mName);
}
@Override
public boolean onLongClick(View v) {
return disturbLongPressGesture;
}
public void setDisturbLongPressGesture(boolean disturbLongPress) {
disturbLongPressGesture = disturbLongPress;
}
@SuppressLint("NewApi")
@Override
protected void onVisibilityChanged(View v, int visibility) {
super.onVisibilityChanged(v, visibility);
if ((v == this || v == mBroWind)
&& (visibility == INVISIBLE || visibility == GONE)) {
hideSoftKeyboard();
}
}
private void hideSoftKeyboard() {
try {
InputMethodManager imm = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onPageStarted(EBrowserView view, String url) {
if (mDestroyed) {
return;
}
mUExMgr.notifyDocChange();
if (checkType(EBrwViewEntry.VIEW_TYPE_POP) && mOAuth) {
mBroWind.onUrlChange(mName, url);
return;
}
if (!checkType(EBrwViewEntry.VIEW_TYPE_MAIN)) {
return;
}
if (mBroWind!=null) {
mBroWind.onPageStarted(view, url);
}
}
protected void onPageFinished(EBrowserView view, String url) {
if (mDestroyed) {
return;
}
if (mBroWind!=null){
mBroWind.onPageFinished(view, url);
}
if (mBrowserViewChangeListener != null) {
mBrowserViewChangeListener.onPageFinish();
}
}
public boolean isObfuscation() {
if (mDestroyed) {
return false;
}
return mBroWind.isObfuscation();
}
public boolean isOAth() {
if (mDestroyed) {
return false;
}
return mBroWind.isOAuth();
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
@Override
public void goBack() {
if (mDestroyed) {
return;
}
if (isObfuscation()) {
EHistoryEntry enty = mBroWind.getHistory(-1);
if (null != enty) {
String url = enty.mUrl;
if (Build.VERSION.SDK_INT >= 11) {
if (url.startsWith("file")) {
int index = url.indexOf("?");
if (index > 0) {
mQuery = url.substring(index + 1);
url = url.substring(0, index);
}
}
}
if (enty.mIsObfuscation) {
needToEncrypt(this, url, EBrowserHistory.UPDATE_STEP_BACK);
} else {
loadUrl(url);
updateObfuscationHistroy(url,
EBrowserHistory.UPDATE_STEP_BACK, false);
}
}
} else {
super.goBack();
}
}
@Override
public void goForward() {
if (mDestroyed) {
return;
}
if (isObfuscation()) {
EHistoryEntry enty = mBroWind.getHistory(1);
if (null != enty) {
if (enty.mIsObfuscation) {
needToEncrypt(this, enty.mUrl,
EBrowserHistory.UPDATE_STEP_FORWARD);
} else {
loadUrl(enty.mUrl);
updateObfuscationHistroy(enty.mUrl,
EBrowserHistory.UPDATE_STEP_FORWARD, false);
}
}
} else {
super.goForward();
}
}
protected void updateObfuscationHistroy(String inUrl, int step,
boolean isObfuscation) {
if (mDestroyed) {
return;
}
if (!checkType(EBrwViewEntry.VIEW_TYPE_MAIN)) {
return;
}
mBroWind.updateObfuscationHistroy(inUrl, step, isObfuscation);
}
protected void clearObfuscationHistroy() {
if (mDestroyed) {
return;
}
mBroWind.clearObfuscationHistroy();
}
public void addViewToCurrentWindow(View child,
FrameLayout.LayoutParams parms) {
if (mDestroyed) {
return;
}
if (parms != null) {
child.setLayoutParams(parms);
}
mBroWind.addViewToCurrentWindow(child);
}
public void removeViewFromCurrentWindow(View child) {
if (mDestroyed) {
return;
}
mBroWind.removeViewFromCurrentWindow(child);
}
public final void startWidget(WWidgetData inData, EWgtResultInfo inResult) {
if (mDestroyed) {
return;
}
mBroWind.startWidget(inData, inResult);
}
protected void start1(String url) {
if (mDestroyed) {
return;
}
if (null == url || 0 == url.length()) {
return;
}
if (Build.VERSION.SDK_INT >= 11) {
if (url != null) {
int index = url.indexOf("?");
if (index > 0) {
setQuery(url.substring(index + 1));
if (!url.startsWith("http")) {
url = url.substring(0, index);
}
}
}
}
addUriTask(url);
}
private void eClearHistory() {
if (mDestroyed) {
return;
}
if (isObfuscation()) {
clearObfuscationHistroy();
} else {
clearHistory();
}
}
protected void start(String url) {
if (mDestroyed) {
return;
}
if (null == url || 0 == url.length()) {
return;
}
if (isObfuscation()) {
clearObfuscationHistroy();
if (url.startsWith("http")) {
addUriTask(url);
updateObfuscationHistroy(url, EBrowserHistory.UPDATE_STEP_INIT,
false);
} else {
needToEncrypt(this, url, EBrowserHistory.UPDATE_STEP_INIT); // may
// be
// crash
}
} else {
if (Build.VERSION.SDK_INT >= 11) {
if (url != null) {
int index = url.indexOf("?");
if (index > 0) {
setQuery(url.substring(index + 1));
if (!url.startsWith("http")) {
url = url.substring(0, index);
}
}
}
}
addUriTask(url);
clearHistory();
}
}
public void newLoadUrl(String url) {
if (mDestroyed) {
return;
}
if (null == url || 0 == url.length()) {
return;
}
addUriTask(url);
}
public void newLoadData(String inData) {
if (mDestroyed) {
return;
}
loadData(inData, CONTENT_MIMETYPE_HTML, CONTENT_DEFAULT_CODE);
}
protected void receivedError(int errorCode, String description,
String failingUrl) {
if (mDestroyed) {
return;
}
if (checkType(EBrwViewEntry.VIEW_TYPE_ADD)) {
loadUrl("about:bank");
mBroWind.closeAd();
return;
}
String errorPath="file:///android_asset/error/error.html";
if (mBroWind!=null&&!TextUtils.isEmpty(getRootWidget().mErrorPath)){
errorPath="file:///android_asset/widget/"+getRootWidget().mErrorPath;
loadUrl(errorPath);
}else{
loadUrl(errorPath);
}
}
public int getType() {
return mType;
}
public void addUriTask(String uri) {
if (null != mBroWind && !mDestroyed) {
mBroWind.addUriTask(this, uri);
}
}
public void addUriTaskAsyn(String uri) {
if (null != mBroWind && !mDestroyed) {
mBroWind.addUriTaskAsyn(this, uri);
}
}
/**
* 设置是否开启硬件加速
*
* @param flag -1不处理,0关闭,1开启
*/
public void setHWEnable(int flag) {
if (flag == -1) {
return;
}
if (flag == 1) {
setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
protected void needToEncrypt(WebView view, String url, int inFlag) {
if (mDestroyed) {
return;
}
int index = url.indexOf("?");
String turl = url;
if (index > 0) {
setQuery(url.substring(index + 1));
turl = turl.substring(0, index);
}
String data = ACEDes.decrypt(turl, mContext, false, null);
;
if (ACEDes.isSpecifiedEncrypt()) {
// data = SpecifiedEncrypt.parseSpecifiedEncryptHtml(data);
}
// if (SpecifiedEncrypt.isSpecifiedEncrypt()) {
//
// data = SpecifiedEncrypt.parseSpecifiedEncrypt(turl);
//
// } else {
// data = BHtmlDecrypt.decrypt(turl, mContext, false, null);
// }
view.loadDataWithBaseURL(url, data, CONTENT_MIMETYPE_HTML,
CONTENT_DEFAULT_CODE, url);
if (mType == EBrwViewEntry.VIEW_TYPE_MAIN) {
updateObfuscationHistroy(url, inFlag, true);
}
}
public EBrowserWindow getBrowserWindow() {
return mBroWind;
}
public int getWidgetType() {
int type = mBroWind.getWidgetType();
return type;
}
public String getWindowName() {
if (mDestroyed) {
return null;
}
return mBroWind.getName();
}
public void setQuery(String query) {
if (mDestroyed) {
return;
}
mQuery = query;
}
public String getQuery() {
if (mDestroyed) {
return null;
}
return mQuery;
}
public String getRelativeUrl() {
if (mDestroyed) {
return null;
}
return mRelativeUrl;
}
public void setRelativeUrl(String url) {
if (mDestroyed) {
return;
}
mRelativeUrl = url;
}
public String getCurrentUrl() {
if (mDestroyed) {
return "";
}
//修改浮动窗口中不能打开窗口问题
//if (!checkType(EBrwViewEntry.VIEW_TYPE_MAIN)) {
// return mBroWind.location();
//} else {
String url = getUrl();
int index = url.indexOf("?");
if (-1 != index) {
url = url.substring(0, index);
}
int indexS = url.indexOf("#");
if (-1 != indexS) {
url = url.substring(0, indexS);
}
return url;
//}
}
public String getCurrentUrl(String baseUrl) {
if (mDestroyed) {
return "";
}
//修改浮动窗口中不能打开窗口问题
//if (!checkType(EBrwViewEntry.VIEW_TYPE_MAIN)) {
// return mBroWind.location();
//} else {
String url = getUrl();
if (TextUtils.isEmpty(url)) {
url = baseUrl;
}
int index = url.indexOf("?");
if (-1 != index) {
url = url.substring(0, index);
}
int indexS = url.indexOf("#");
if (-1 != indexS) {
url = url.substring(0, indexS);
}
return url;
//}
}
public String getWidgetPath() {
if (mDestroyed) {
return "";
}
String ret = getCurrentWidget().m_widgetPath;
return ret;
}
public WWidgetData getCurrentWidget() {
if (mDestroyed) {
return new WWidgetData();
}
return mBroWind.getWidget();
}
public WWidgetData getRootWidget() {
if (mDestroyed) {
return new WWidgetData();
}
return mBroWind.getRootWidget();
}
public boolean isOAuth() {
return mOAuth;
}
public void setOAuth(boolean flag) {
mOAuth = flag;
}
public boolean shouldOpenInSystem() {
return mShouldOpenInSystem;
}
public void setShouldOpenInSystem(boolean flag) {
mShouldOpenInSystem = flag;
}
public void setOpaque(boolean flag) {
mOpaque = flag;
if (mOpaque) {
setBackgroundColor(0xFFFFFFFF);
} else {
setBackgroundColor(Color.TRANSPARENT);
}
}
/**wanglei del 20151124*/
// public void setBrwViewBackground(boolean flag, String bgColor, String baseUrl) {
// if (flag) {
// if(bgColor.startsWith("#") || bgColor.startsWith("rgb")){
// int color = BUtility.parseColor(bgColor);
// setBackgroundColor(color);
// }else{
// String path = BUtility.makeRealPath(BUtility.makeUrl(getCurrentUrl(baseUrl),bgColor),
// getCurrentWidget().m_widgetPath, getCurrentWidget().m_wgtType);
// Bitmap bitmap = BUtility.getLocalImg(mContext, path);
// Drawable d = null;
// if(bitmap != null){
// d = new BitmapDrawable(mContext.getResources(), bitmap);
// }
// int version = Build.VERSION.SDK_INT;
// if(version < 16){
// setBackgroundDrawable(d);
// setBackgroundColor(Color.argb(0, 0, 0, 0));
// }else{
// setBackground(d);
// setBackgroundColor(Color.argb(0, 0, 0, 0));
// }
// }
// } else {
// setBackgroundColor(Color.TRANSPARENT);
// }
// }
public void setWebApp(boolean flag) {
mWebApp = flag;
}
public boolean isWebApp() {
return mWebApp;
}
public int getDateType() {
return mDateType;
}
public void setDateType(int dateType) {
mDateType = dateType;
}
public void beginAnimition() {
if (mDestroyed) {
return;
}
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null == mViewAnim) {
mViewAnim = new EBrwViewAnim();
}
mViewAnim.beginAnimition(v);
}
});
}
public void setAnimitionDelay(final long del) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.setAnimitionDelay(v, del);
}
}
});
}
public void setAnimitionDuration(final long dur) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.setAnimitionDuration(v, dur);
}
}
});
}
public void setAnimitionCurve(final int cur) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.setAnimitionCurve(v, cur);
}
}
});
}
public void setAnimitionRepeatCount(final int count) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.setAnimitionRepeatCount(v, count);
}
}
});
}
public void setAnimitionAutoReverse(final boolean flag) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.setAnimitionAutoReverse(v, flag);
}
}
});
}
public void makeTranslation(final float tx, final float ty, final float tz) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.makeTranslation(v, tx, ty, tz);
}
}
});
}
public void makeScale(final float tx, final float ty, final float tz) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.makeScale(v, tx, ty, tz);
}
}
});
}
public void makeRotate(final float fd, final float px, final float py,
final float pz) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.makeRotate(v, fd, px, py, pz);
}
}
});
}
public void makeAlpha(final float fc) {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.makeAlpha(v, fc);
}
}
});
}
public void commitAnimition() {
final EBrowserView v = this;
post(new Runnable() {
@Override
public void run() {
if (null != mViewAnim && !mDestroyed) {
mViewAnim.commitAnimition(v);
mBroWind.invalidate();
}
}
});
}
public void cbBounceState(int inData) {
String js = "javascript:if(" + EUExWindow.function_cbBounceState + "){"
+ EUExWindow.function_cbBounceState + "(" + 0 + "," + 2 + ","
+ inData + ")}";
addUriTask(js);
}
public void getBounce() {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.obj = getParent();
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_GET_BOUNCE_VIEW);
}
public void setBounce(int flag) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.obj = getParent();
bounceEntry.flag = flag;
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_SET_BOUNCE_VIEW);
}
public void notifyBounceEvent(int inType, int inStatus) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.type = inType;
bounceEntry.obj = getParent();
bounceEntry.flag = inStatus;
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_NOTIFY_BOUNCE_VIEW);
}
public void showBounceView(int inType, String inColor, int inFlag) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.type = inType;
bounceEntry.obj = getParent();
bounceEntry.color = parseColor(inColor);
bounceEntry.flag = inFlag;
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_SHOW_BOUNCE_VIEW);
}
public void onBounceStateChange(int type, int state) {
String js = "javascript:if(uexWindow.onBounceStateChange){uexWindow.onBounceStateChange("
+ type + "," + state + ");}";
loadUrl(js);
}
public int parseColor(String inColor) {
int reColor = 0;
try {
if (inColor != null && inColor.length() != 0) {
inColor = inColor.replace(" ", "");
if (inColor.charAt(0) == 'r') { // rgba
int start = inColor.indexOf('(') + 1;
int off = inColor.indexOf(')');
inColor = inColor.substring(start, off);
String[] rgba = inColor.split(",");
int r = Integer.parseInt(rgba[0]);
int g = Integer.parseInt(rgba[1]);
int b = Integer.parseInt(rgba[2]);
int a = Integer.parseInt(rgba[3]);
reColor = (a << 24) | (r << 16) | (g << 8) | b;
} else { // #
inColor = inColor.substring(1);
if (3 == inColor.length()) {
char[] t = new char[6];
t[0] = inColor.charAt(0);
t[1] = inColor.charAt(0);
t[2] = inColor.charAt(1);
t[3] = inColor.charAt(1);
t[4] = inColor.charAt(2);
t[5] = inColor.charAt(2);
inColor = String.valueOf(t);
} else if (6 == inColor.length()) {
;
}
long color = Long.parseLong(inColor, 16);
reColor = (int) (color | 0x00000000ff000000);
}
}
} catch (Exception e) {
;
}
return reColor;
}
public void resetBounceView(int inType) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.type = inType;
bounceEntry.obj = getParent();
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_RESET_BOUNCE_VIEW);
}
public void hiddenBounceView(int inType) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.type = inType;
bounceEntry.obj = getParent();
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_HIDDEN_BOUNCE_VIEW);
}
public void setBounceParams(int inType, JSONObject json, String guestId) {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.type = inType;
bounceEntry.obj = getParent();
bounceEntry.obj1 = json;
bounceEntry.arg1 = guestId;
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_SET_BOUNCE_PARMS);
}
public void topBounceViewRefresh() {
if (mDestroyed) {
return;
}
EViewEntry bounceEntry = new EViewEntry();
bounceEntry.obj = getParent();
mBroWind.addBounceTask(bounceEntry,
EViewEntry.F_BOUNCE_TASK_TOP_BOUNCE_VIEW_REFRESH);
}
public boolean beDestroy() {
return mDestroyed;
}
protected void reset() {
mDestroyed = false;
View bv = (View) getParent();
if (bv != null && bv instanceof EBounceView) {
((EBounceView) bv).release();
}
clearView();
clearMatches();
mQuery = null;
mName = null;
mRelativeUrl = null;
mShouldOpenInSystem = false;
mOpaque = false;
mOAuth = false;
mWebApp = false;
mSupportZoom = false;
isSupportSlideCallback = false;
disturbLongPressGesture = false;
eClearHistory();
resumeCore();
mUExMgr.notifyReset();
}
@Override
public void stopLoading() {
super.stopLoading();
mUExMgr.notifyStop();
pauseCore();
}
@Override
public void destroy() {
if (mDestroyed) {
return;
}
mDestroyed = true;
mBroWind = null;
mBaSetting = null;
mContext = null;
clearView();
clearHistory();
ViewGroup parent = (ViewGroup) getParent();
if (null != parent) {
parent.removeView(this);
}
mUExMgr.notifyDestroy(this);
mUExMgr = null;
super.destroy();
}
protected void printThreadStackTrace() {
StackTraceElement[] stak = Thread.currentThread().getStackTrace();
String s = "";
int len = stak.length;
for (int i = 0; i < len; ++i) {
StackTraceElement one = stak[i];
String className = one.getClassName();
String methodName = one.getMethodName();
int line = one.getLineNumber();
String x = s + className + "." + methodName + " [" + line + "]";
x.charAt(0);
if (i == 0 || i == 1 || i == 2) {
s += " ";
}
}
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
//if (!EBrowserWindow.isShowDialog) {
int versionA = Build.VERSION.SDK_INT;
boolean isSlideCallback = false;
if (versionA >= 19) {
//system above 4.4, is support callback depend on isSupportSlideCallback which
// set by developer.
// 4.4以上手机系统,是否回调取决于前端接口设置。
isSlideCallback = isSupportSlideCallback;
} else {
//system below 4.4, is support callback depend on isSupportSlideCallback and
//isShowDialog, isShowDialog indicate is pop-up keyboard or whether to switch
// the screen.
// 4.4以下手机系统,是否回调即取决于前端接口设置,也取决于当前键盘是否弹出或者是否变换屏幕。因此在该
// 条件下屏幕旋转之后,上滑下滑的监听不生效。
isSlideCallback = isSupportSlideCallback && !EBrowserWindow.isShowDialog;
}
if (isSlideCallback) {
float contentHeight = getContentHeight() * getCustomScale();
boolean isSlipedDownEdge = t != oldt && t > 0
&& contentHeight <= t + getHeight() + mThreshold;
if (isSlipedDownEdge) {
callback.jsCallback(EUExWindow.function_cbslipedDownEdge, 0,
EUExCallback.F_C_INT, 0);
callback.jsCallback(EUExWindow.function_onSlipedDownEdge, 0,
EUExCallback.F_C_INT, 0);
} else if (getScrollY() == 0) {
callback.jsCallback(EUExWindow.function_cbslipedUpEdge, 0,
EUExCallback.F_C_INT, 0);
callback.jsCallback(EUExWindow.function_onSlipedUpEdge, 0,
EUExCallback.F_C_INT, 0);
} else if (oldt - t > mScrollDistance) {
callback.jsCallback(EUExWindow.function_cbslipedDownward, 0,
EUExCallback.F_C_INT, 0);
callback.jsCallback(EUExWindow.function_onSlipedDownward, 0,
EUExCallback.F_C_INT, 0);
} else if (oldt - t < -mScrollDistance) {
callback.jsCallback(EUExWindow.function_cbslipedUpward, 0,
EUExCallback.F_C_INT, 0);
callback.jsCallback(EUExWindow.function_onSlipedUpward, 0,
EUExCallback.F_C_INT, 0);
}
}
//}
super.onScrollChanged(l, t, oldl, oldt);
}
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength) {
if (mDownloadCallback == 0) {
mEXWebViewClient.onDownloadStart(mContext, url, userAgent,
contentDisposition, mimetype, contentLength);
} else {
mBroWind.executeCbDownloadCallbackJs(this, mDownloadCallback,
url, userAgent, contentDisposition, mimetype, contentLength);
}
}
public void setNeedScroll(boolean b) {
this.mIsNeedScroll = b;
}
public void setIsSupportSlideCallback(boolean isSupport) {
isSupportSlideCallback = isSupport;
}
public void setEBrowserViewChangeListener(OnEBrowserViewChangeListener browserViewChangeListener) {
mBrowserViewChangeListener = browserViewChangeListener;
}
public interface OnEBrowserViewChangeListener {
void onPageFinish();
}
public String getWebViewKernelInfo() {
KernelInfoVO infoVO = new KernelInfoVO();
if (Build.VERSION.SDK_INT > 18) {
infoVO.setKernelType("System(Blink)");
try {
PackageManager pm = this.getContext().getPackageManager();
PackageInfo pinfo = pm.getPackageInfo("com.google.android.webview",
PackageManager.GET_CONFIGURATIONS);
infoVO.setKernelVersion(pinfo.versionName);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
} else {
infoVO.setKernelType("System(Webkit)");
}
String info = DataHelper.gson.toJson(infoVO);
return info;
}
public void setUserAgent(String userAgent) {
mBaSetting.setUserAgent(userAgent);
}
public int getDownloadCallback() {
if (mDestroyed) {
return 0;
}
return mDownloadCallback;
}
public void setDownloadCallback(int downloadCallback) {
if (mDestroyed) {
return;
}
this.mDownloadCallback = downloadCallback;
}
}<|fim▁end|> | }
}
@Override |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Minimal Python 3 shim around PyQt5 and Pyside2 Qt bindings for QML applications.
Forked from https://github.com/mottosso/Qt.py under MIT License.
Copyright (c) 2016 Marcus Ottosson
Changes
* Dropped Python2 and Qt4 support
* Focus on last Python 3 release
* Focus on last Qt API : QML
Requirements
* make use of lazy loading to speed up startup time !
"""
# Fixme: ressource file Patro/QtApplication/rcc/PatroRessource.py
####################################################################################################
# Enable support for `from Qt import *`
__all__ = []
####################################################################################################
import importlib
import logging
import os
import sys
import types
from .QtConfig import _common_members, _misplaced_members, _compatibility_members
####################################################################################################
# _module_logger = logging.getLogger(__name__)
####################################################################################################
# Flags from environment variables
QT_VERBOSE = bool(os.getenv('QT_VERBOSE'))
QT_PREFERRED_BINDING = os.getenv('QT_PREFERRED_BINDING', '')
if QT_PREFERRED_BINDING:
QT_PREFERRED_BINDING = list(x for x in QT_PREFERRED_BINDING.split(',') if x)
else:
# on dec 2018, PySide2 is still not fully operational
QT_PREFERRED_BINDING = ('PyQt5', 'PySide2')
####################################################################################################
def _new_module(name):
return types.ModuleType(__name__ + '.' + name)
####################################################################################################
# Reference to Qt.py
Qt = sys.modules[__name__]
Qt.QtCompat = _new_module('QtCompat')
####################################################################################################
def _log(text):
if QT_VERBOSE:
# _logger print
sys.stdout.write(text + '\n')
####################################################################################################
def _import_sub_module(module, name):
"""import a submodule"""
_log('_import_sub_module {} {}'.format(module, name))
module_name = module.__name__ + '.' + name # e.g. PyQt5.QtCore
module = importlib.import_module(module_name)
return module
####################################################################################################
def _setup(module, extras):
"""Install common submodules"""
Qt.__binding__ = module.__name__
for name in list(_common_members) + extras:
try:
submodule = _import_sub_module(module, name)
except ImportError:
try:
# For extra modules like sip and shiboken that may not be
# children of the binding.
submodule = __import__(name)
except ImportError:
continue
setattr(Qt, '_' + name, submodule)
if name not in extras:
# Store reference to original binding
setattr(Qt, name, _new_module(name)) # Qt.QtCore = module(so module)
####################################################################################################
def _reassign_misplaced_members(binding):
"""Apply misplaced members from `binding` to Qt.py
Arguments:
binding (dict): Misplaced members
"""
for src, dst in _misplaced_members[binding].items():
# print()
dst_value = None
# Fixme: to func
src_parts = src.split('.')
src_module = src_parts[0]
if len(src_parts):
src_member = src_parts[1:]
else:
src_member = None
if isinstance(dst, (list, tuple)):
dst, dst_value = dst
# print(src, '->', dst, dst_value)
# print(src_module, src_member)
dst_parts = dst.split('.')
dst_module = dst_parts[0]
if len(dst_parts):
dst_member = dst_parts[1]
else:
dst_member = None
# print(dst_module, dst_member)
# Get the member we want to store in the namesapce.
if not dst_value:
try:
_part = getattr(Qt, '_' + src_module)
while src_member:
member = src_member.pop(0)
_part = getattr(_part, member)
dst_value = _part
except AttributeError:
# If the member we want to store in the namespace does not
# exist, there is no need to continue. This can happen if a
# request was made to rename a member that didn't exist, for
# example if QtWidgets isn't available on the target platform.
_log('Misplaced member has no source: {0}'.format(src))
continue
# print(dst_value)
try:
# Fixme: src_object ???
src_object = getattr(Qt, dst_module)
except AttributeError:
# print('Failed to get src_object')
if dst_module not in _common_members:
# Only create the Qt parent module if its listed in
# _common_members. Without this check, if you remove QtCore
# from _common_members, the default _misplaced_members will add
# Qt.QtCore so it can add Signal, Slot, etc.
msg = "Not creating missing member module '{m}' for '{c}'"
_log(msg.format(m=dst_module, c=dst_member))
continue
# If the dst is valid but the Qt parent module does not exist
# then go ahead and create a new module to contain the member.
setattr(Qt, dst_module, _new_module(dst_module))
src_object = getattr(Qt, dst_module)
# Enable direct import of the new module
sys.modules[__name__ + '.' + dst_module] = src_object
if not dst_value:
dst_value = getattr(Qt, '_' + src_module)
if src_member:
dst_value = getattr(dst_value, src_member)
setattr(
src_object,
dst_member or dst_module,
dst_value
)
####################################################################################################
def _build_compatibility_members(binding, decorators=None):
"""Apply `binding` to QtCompat
Arguments:
binding (str): Top level binding in _compatibility_members.
decorators (dict, optional): Provides the ability to decorate the
original Qt methods when needed by a binding. This can be used
to change the returned value to a standard value. The key should
be the classname, the value is a dict where the keys are the
target method names, and the values are the decorator functions.
"""
decorators = decorators or dict()
# Allow optional site-level customization of the compatibility members.
# This method does not need to be implemented in QtSiteConfig.
try:
import QtSiteConfig
except ImportError:
pass
else:
if hasattr(QtSiteConfig, 'update_compatibility_decorators'):
QtSiteConfig.update_compatibility_decorators(binding, decorators)
_QtCompat = type('QtCompat', (object,), {})
for classname, bindings in _compatibility_members[binding].items():
attrs = {}
for target, binding in bindings.items():
namespaces = binding.split('.')
try:
src_object = getattr(Qt, '_' + namespaces[0])
except AttributeError as e:
_log('QtCompat: AttributeError: %s' % e)
# Skip reassignment of non-existing members.
# This can happen if a request was made to
# rename a member that didn't exist, for example
# if QtWidgets isn't available on the target platform.
continue
# Walk down any remaining namespace getting the object assuming
# that if the first namespace exists the rest will exist.
for namespace in namespaces[1:]:
src_object = getattr(src_object, namespace)
# decorate the Qt method if a decorator was provided.
if target in decorators.get(classname, []):
# staticmethod must be called on the decorated method to
# prevent a TypeError being raised when the decorated method
# is called.
src_object = staticmethod(
decorators[classname][target](src_object))
attrs[target] = src_object
# Create the QtCompat class and install it into the namespace
compat_class = type(classname, (_QtCompat,), attrs)
setattr(Qt.QtCompat, classname, compat_class)
####################################################################################################
def _pyside2():
"""Initialise PySide2
These functions serve to test the existence of a binding
along with set it up in such a way that it aligns with
the final step; adding members from the original binding
to Qt.py
"""
import PySide2 as module
extras = []
# try:
# from PySide2 import shiboken2
# extras.append('shiboken2')
# except ImportError:
# pass
_setup(module, extras)
Qt.__binding_version__ = module.__version__
# if hasattr(Qt, '_shiboken2'):
# Qt.QtCompat.wrapInstance = _wrapinstance
# Qt.QtCompat.getCppPointer = _getcpppointer
# Qt.QtCompat.delete = shiboken2.delete
if hasattr(Qt, '_QtCore'):
Qt.__qt_version__ = Qt._QtCore.qVersion()
# if hasattr(Qt, '_QtWidgets'):
# Qt.QtCompat.setSectionResizeMode = \
# Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members('PySide2')
# _build_compatibility_members('PySide2')
####################################################################################################
def _pyqt5():
"""Initialise PyQt5"""
import PyQt5 as module
extras = []
# try:
# import sip
# extras.append(sip.__name__)
# except ImportError:
# sip = None
_setup(module, extras)
# if hasattr(Qt, '_sip'):<|fim▁hole|> # Qt.QtCompat.delete = sip.delete
if hasattr(Qt, '_QtCore'):
Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR
Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR
# if hasattr(Qt, '_QtWidgets'):
# Qt.QtCompat.setSectionResizeMode = \
# Qt._QtWidgets.QHeaderView.setSectionResizeMode
_reassign_misplaced_members('PyQt5')
# _build_compatibility_members('PyQt5')
####################################################################################################
def _install():
# Default order (customise order and content via QT_PREFERRED_BINDING)
order = QT_PREFERRED_BINDING
available = {
'PySide2': _pyside2,
'PyQt5': _pyqt5,
}
_log("Order: {}".format(' '.join(order)))
found_binding = False
for name in order:
_log('Trying %s' % name)
try:
available[name]()
found_binding = True
break
except ImportError as e:
_log('ImportError: %s' % e)
except KeyError:
_log("ImportError: Preferred binding '%s' not found." % name)
if not found_binding:
# If not binding were found, throw this error
raise ImportError('No Qt binding were found.')
# Install individual members
for name, members in _common_members.items():
try:
their_submodule = getattr(Qt, '_' + name)
except AttributeError:
continue
our_submodule = getattr(Qt, name)
# Enable import *
__all__.append(name)
# Enable direct import of submodule,
# e.g. import Qt.QtCore
sys.modules[__name__ + '.' + name] = our_submodule
for member in members:
# Accept that a submodule may miss certain members.
try:
their_member = getattr(their_submodule, member)
except AttributeError:
_log("'%s.%s' was missing." % (name, member))
continue
setattr(our_submodule, member, their_member)
# Enable direct import of QtCompat
sys.modules['Qt.QtCompat'] = Qt.QtCompat
####################################################################################################
_install()
####################################################################################################
# Fixme: Python 3.7
# def __getattr__(name):
# print('__getattr__', name)
####################################################################################################
# Setup Binding Enum states
Qt.IsPySide2 = Qt.__binding__ == 'PySide2'
Qt.IsPyQt5 = not Qt.IsPySide2<|fim▁end|> | # Qt.QtCompat.wrapInstance = _wrapinstance
# Qt.QtCompat.getCppPointer = _getcpppointer |
<|file_name|>controller.py<|end_file_name|><|fim▁begin|># Copyright 2011 Tsutomu Uchino
#
# 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 unohelper
from com.sun.star.frame import XController, XTitle, XDispatchProvider
from com.sun.star.lang import XServiceInfo
from com.sun.star.task import XStatusIndicatorSupplier
class MRIUIController(unohelper.Base,
XController, XTitle, XDispatchProvider,
XStatusIndicatorSupplier, XServiceInfo):
""" Provides controller which connects between frame and model. """
IMPLE_NAME = "mytools.mri.UIController"
def __init__(self,frame, model):
self.frame = frame
self.model = model
self.ui = None
def set_ui(self, ui):
self.ui = ui
def get_imple_name(self):
return self.ui.pages.get_imple_name()
# XTitle
def getTitle(self):
return self.frame.getTitle()
def setTitle(self, title):
self.frame.setTitle(title)
def dispose(self):
self.frame = None
self.model = None
def addEventListener(self, xListener):
pass
def removeEventListener(self, aListener):
pass
# XController
def attachFrame(self, frame):
self.frame = frame
def attachModel(self, model):
self.model = model
def suspend(self, Suspend):
return True
def getViewData(self):
""" Returns current instance inspected. """
return self.ui.main.current.target
def restoreViewData(self, Data):
pass
def getModel(self):
return self.model
def getFrame(self):
return self.frame
def getStatusIndicator(self):
pass
# XDispatchProvider
def queryDispatch(self, url, name, flags):
pass
def queryDispatches(self, requests):
pass
# XServiceInfo<|fim▁hole|>
def supportsService(self, name):
return name == self.IMPLE_NAME
def getSupportedServiceNames(self):
return self.IMPLE_NAME,<|fim▁end|> | def getImplementationName(self):
return self.IMPLE_NAME |
<|file_name|>nnet_lasagne.py<|end_file_name|><|fim▁begin|># code adapted from lasagne tutorial
# http://lasagne.readthedocs.org/en/latest/user/tutorial.html
import time
import os
from itertools import product
import numpy as np
from sklearn.cross_validation import KFold
import theano
from theano import tensor as T
import lasagne
from params import nnet_params_dict, feats_train_folder
def set_trace():
from IPython.core.debugger import Pdb
import sys
Pdb(color_scheme='Linux').set_trace(sys._getframe().f_back)
def build_network(input_var, input_shape, nonlins, depth=2,
widths=(1000, 1000, 10), drops=(0.2, 0.5)):
"""
Parameters
----------
input_var : Theano symbolic variable or None (default: None)
Variable representing a network input.
input_shape : tuple of int or None (batchsize, rows, cols)
input_shape of the input. Any element can be set to None to indicate
that dimension is not fixed at compile time
"""
# GlorotUniform is the default mechanism for initializing weights
for i in range(depth):
if i == 0:
network = lasagne.layers.InputLayer(shape=input_shape,
input_var=input_var)
else:
network = lasagne.layers.DenseLayer(network,
widths[i],
nonlinearity=nonlins[i])
if drops[i] != None:
network = lasagne.layers.DropoutLayer(network, p=drops[i])
return network
def floatX(X):
return np.asarray(X, dtype=theano.config.floatX)
def zerosX(X):
return np.zeros(X, dtype=theano.config.floatX)
def init_weights(shape):
return theano.shared(floatX(np.random.randn(*shape) * 0.01))
def sgd(cost, params, gamma):
grads = T.grad(cost=cost, wrt=params)
updates = []
for p, g in zip(params, grads):
updates.append([p, p - g * gamma])
return updates
def model(X, w_h, w_o):
h = T.nnet.sigmoid(T.dot(X, w_h))
pyx = T.nnet.softmax(T.dot(h, w_o))
return pyx
def iterate_minibatches(inputs, targets, batchsize, shuffle=False):
assert len(inputs) == len(targets)
if shuffle:
indices = np.arange(len(inputs))
np.random.shuffle(indices)
for start_idx in range(0, len(inputs) - batchsize + 1, batchsize):
if shuffle:
excerpt = indices[start_idx:start_idx + batchsize]
else:
excerpt = slice(start_idx, start_idx + batchsize)
yield inputs[excerpt], targets[excerpt]
def batch_ids(batch_size, x_train, train_idx):
# change to iterator
ids = zip(range(0, len(x_train[train_idx]), batch_size),
range(batch_size, len(x_train[train_idx]), batch_size))<|fim▁hole|> return ids
verbose = True
# train on every perturbed dataset
filepaths = np.loadtxt("include_data.csv", dtype=object, delimiter=",")
for (include, train_filename, test_filename) in filepaths:
if include == '1':
print '\nExecuting {}'.format(train_filename)
# Load training and test sets
x_train = np.load(os.path.join(feats_train_folder,
train_filename)).astype(np.float32)
y_train = x_train[:, -1].astype(int)
# y_train = (np.eye(2, dtype=np.float32)[x_train[:,-1].astype(int)])
# remove label column from x_train
x_train = x_train[:, :-1]
# Network topology
n_obs = x_train.shape[0]
n_inputs = x_train.shape[1]
n_outputs = len(np.unique(y_train))
# Cross-validation and Neural Net parameters
n_folds = nnet_params_dict['n_folds']
alphas = nnet_params_dict['alphas']
gammas = nnet_params_dict['gammas']
decay_rate = nnet_params_dict['decay_rate']
batch_sizes = nnet_params_dict['batch_sizes']
max_epoch = nnet_params_dict['max_epoch']
depth = nnet_params_dict['depth']
widths = nnet_params_dict['widths']
nonlins = nnet_params_dict['nonlins']
drops = nnet_params_dict['drops']
# Dictionary to store results
results_dict = {}
params_mat = [x for x in product(alphas, gammas, batch_sizes)]
params_mat = np.array(params_mat, dtype=theano.config.floatX)
params_mat = np.column_stack((params_mat,
zerosX(params_mat.shape[0]),
zerosX(params_mat.shape[0]),
zerosX(params_mat.shape[0])))
for param_idx in xrange(params_mat.shape[0]):
# load parameters for neural network model
alpha = params_mat[param_idx, 0]
gamma = params_mat[param_idx, 1]
batch_size = int(params_mat[param_idx, 2])
shape = (batch_size, x_train.shape[1])
# choose n_hidden nodes according to ...
n_hidden = int((n_obs / depth) / (alpha*(n_inputs+n_outputs)))
for i in range(1, depth-1):
widths[i] = n_hidden
model_str = ('\nalpha {} gamma {} batch size {} '
'n_hidden {} depth {}'
'\nnonlins {}'
'\ndrops {}'.format(alpha, gamma, batch_size,
n_hidden, depth, nonlins,
drops))
print model_str
# specify input and target theano data types
input_var = T.fmatrix('input')
target_var = T.ivector('target')
# build neural network model
network = build_network(input_var, shape, nonlins, depth, widths,
drops)
# create loss expression for training
"""
py_x = model(input_var, w_h, w_o)
y_x = T.argmax(py_x, axis=1)
cost = T.mean(T.nnet.categorical_crossentropy(py_x, target_var),
dtype=theano.config.floatX)
"""
prediction = lasagne.layers.get_output(network)
loss = lasagne.objectives.categorical_crossentropy(prediction,
target_var)
loss = loss.mean()
# create paraneter update expressions for training
"""
params = [w_h, w_o]
updates = sgd(cost, params, gamma=gamma)
"""
params = lasagne.layers.get_all_params(network, trainable=True)
updates = lasagne.updates.adadelta(loss, params,
learning_rate=gamma,
rho=decay_rate)
# create loss expression for validation and classification accuracy
# Deterministic forward pass to disable droupout layers
test_prediction = lasagne.layers.get_output(network,
deterministic=True)
test_loss = lasagne.objectives.categorical_crossentropy(
test_prediction,
target_var)
test_loss = test_loss.mean()
test_acc = T.mean(T.eq(T.argmax(test_prediction, axis=1),
target_var), dtype=theano.config.floatX)
# compile functions for performing training step and returning
# corresponding training loss
train_fn = theano.function(inputs=[input_var, target_var],
outputs=loss,
updates=updates,
allow_input_downcast=True)
# compile a function to compute the validation loss and accuracy
val_fn = theano.function(inputs=[input_var, target_var],
outputs=[test_loss, test_acc],
allow_input_downcast=True)
# create kfold iterator
kf = KFold(x_train.shape[0], n_folds=n_folds)
error_rates = []
val_losses = []
running_time = []
fold = 1
for train_idx, val_idx in kf:
start_time = time.time()
for i in range(max_epoch):
train_err = 0
train_batches = 0
for start, end in batch_ids(batch_size, x_train,
train_idx):
train_err += train_fn(x_train[train_idx][start:end],
y_train[train_idx][start:end])
train_batches += 1
val_err = 0
val_acc = 0
val_batches = 0
for start, end in batch_ids(batch_size, x_train,
train_idx):
err, acc = val_fn(x_train[val_idx], y_train[val_idx])
val_err += err
val_acc += acc
val_batches += 1
error_rate = (1 - (val_acc / val_batches)) * 100
val_loss = val_err / val_batches
print("Final results:")
print(" val loss:\t\t\t{:.6f}".format(val_loss))
print(" val error rate:\t\t{:.2f} %".format(error_rate))
error_rates.append(error_rate)
val_losses.append(val_loss)
running_time.append(np.around((time.time() -
start_time) / 60., 1))
fold += 1
params_mat[param_idx, 3] = np.mean(error_rates)
params_mat[param_idx, 4] = np.mean(val_losses)
params_mat[param_idx, 5] = np.mean(running_time)
print('alpha {} gamma {} batchsize {} error rate {} '
'validation cost {} '
'running time {}'.format(params_mat[param_idx, 0],
params_mat[param_idx, 1],
params_mat[param_idx, 2],
params_mat[param_idx, 3],
params_mat[param_idx, 4],
params_mat[param_idx, 5]))
# Save params matrix to disk
params_mat.dump(('results/train/{}'
'_results.np').format(train_filename[:-3]))<|fim▁end|> | |
<|file_name|>test_MagneticField.py<|end_file_name|><|fim▁begin|>from unittest import TestCase
from gnomon import MagneticField
class MockG4ThreeVector():
x = 0
y = 0
z = 0
class TestWandsToroidField(TestCase):
def setUp(self):
self.field_minus = MagneticField.WandsToroidField('-')
self.field_plus = MagneticField.WandsToroidField('+')
self.fields = [self.field_minus, self.field_plus]
def test_PhenomModel(self):
for field in self.fields:
with self.assertRaises(ValueError):
field.PhenomModel(0)
<|fim▁hole|> with self.assertRaises(ValueError):
field.PhenomModel(-1)
field.PhenomModel(1)
def test_GetFieldValue(self):
for field in self.fields:
pos = MockG4ThreeVector()
vector = field.GetFieldValue(pos, 0)
self.assertEqual(vector.x, 0)
self.assertEqual(vector.y, 0)
self.assertEqual(vector.z, 0)
pos.x = 1
vector = field.GetFieldValue(pos, 0)
pos = MockG4ThreeVector()
pos.x = 1
pos.y = 2
pos.z = 3
vector_plus = self.field_plus.GetFieldValue(pos, 0)
vector_minus = self.field_minus.GetFieldValue(pos, 0)
self.assertAlmostEqual(vector_plus.x, -1 * vector_minus.x)
self.assertAlmostEqual(vector_plus.y, -1 * vector_minus.y)
self.assertAlmostEqual(vector_plus.z, -1 * vector_minus.z)<|fim▁end|> | |
<|file_name|>subtensor.py<|end_file_name|><|fim▁begin|>from copy import copy
import sys
from textwrap import dedent
import warnings
import logging
import numpy
from six.moves import xrange
import theano
from theano.compat import izip
from six import integer_types
from theano.gradient import DisconnectedType
from theano import gof
from theano.gof import Apply, Constant, hashtype, Op, Type, MethodNotDefined
from theano.printing import pprint
from theano import scalar as scal
from theano.tensor.basic import alloc
from theano.tensor.basic import (addbroadcast, clip, get_scalar_constant_value,
ARange, TensorType, NotScalarConstantError)
from theano.tensor.elemwise import DimShuffle
from theano.tensor.type_other import NoneConst, SliceType, make_slice
from theano import config
inplace_increment = None
if config.cxx:
import theano.gof.cutils # needed to import cutils_ext
try:
from cutils_ext.cutils_ext import inplace_increment
except ImportError:
pass
_logger = logging.getLogger("theano.tensor.subtensor")
# Do a lazy import of the sparse module
sparse_module_ref = None
class AdvancedIndexingError(TypeError):
"""
Raised when Subtensor is asked to perform advanced indexing.
"""
def __init__(self, *args):
TypeError.__init__(self, *args)
##########
# Helpful functions to deal with Subtensor and IncSubtensor
##########
def make_constant(args):
"""
Convert python litterals to theano constants in subtensor arguments.
"""
def conv(a):
if a is None:
return a
elif isinstance(a, slice):
return slice(conv(a.start),
conv(a.stop),
conv(a.step))
elif isinstance(a, (integer_types, numpy.integer)):
return scal.ScalarConstant(scal.int64, a)
else:
return a
return tuple(map(conv, args))
def get_idx_list(inputs, idx_list, get_count=False):
'''
Given a list of inputs to the subtensor and its idx_list reorders
the inputs according to the idx list to get the right values.
If get_counts=True, instead returns the number of inputs consumed
during this process.
'''
# The number of indices
n = len(inputs) - 1
# The subtensor (or idx_list) does not depend on the inputs.
if n == 0:
return tuple(idx_list)
indices = list(reversed(list(inputs[1:])))
# General case
def convert(entry):
if isinstance(entry, gof.Type):
return indices.pop()
elif isinstance(entry, slice):
return slice(convert(entry.start),
convert(entry.stop),
convert(entry.step))
else:
return entry
cdata = tuple(map(convert, idx_list))
if get_count:
return n - len(indices)
else:
return cdata
def get_canonical_form_slice(theslice, length):
'''
Given a slice [start:stop:step] transform it into a canonical form
that respects the conventions imposed by python and numpy.
In a canonical form a slice is represented by a canonical form slice,
in which 0 <= start <= stop <= length and step > 0, and a flag which says
if the resulting set of numbers needs to be reversed or not.
'''
from theano.tensor import switch, lt, ge, sgn
if isinstance(theslice, slice):
def analyze(x):
try:
x_constant = get_scalar_constant_value(x)
is_constant = True
except theano.tensor.NotScalarConstantError:
x_constant = theano.tensor.extract_constant(x)
is_constant = False
return x_constant, is_constant
start, is_start_constant = analyze(theslice.start)
stop, is_stop_constant = analyze(theslice.stop)
step, is_step_constant = analyze(theslice.step)
length, is_length_constant = analyze(length)
if step is None:
step = 1
is_step_constant = True
# First handle the easier and common case where `step` is 1 and
# either `start` or `stop` is a range boundary. More specializations
# could be added later. This makes the resulting graph smaller than
# in the generic case below.
if step == 1:
is_start_0 = (
start is None or start == 0 or
(is_start_constant and is_length_constant and
start < 0 and start + length <= 0))
is_stop_length = (
stop is None or stop in [length, sys.maxsize] or
(is_stop_constant and is_length_constant and
stop >= length))
if is_start_0:
# 0:stop:1
if is_stop_length:
# Full slice.
return slice(0, length, 1), 1
if is_stop_constant and stop >= 0:
return (slice(0, switch(lt(stop, length), stop, length),
1), 1)
stop_plus_len = stop + length
stop = switch(
lt(stop, 0),
# stop < 0
switch(
lt(stop_plus_len, 0),
# stop + len < 0
0,
# stop + len >= 0
stop_plus_len),
# stop >= 0: use min(stop, length)
switch(lt(stop, length), stop, length))
return slice(0, stop, 1), 1
elif is_stop_length:
# start:length:1
if is_start_constant and start >= 0:
return slice(switch(lt(start, length), start, length),
length, 1), 1
start_plus_len = start + length
start = switch(
lt(start, 0),
# start < 0
switch(
lt(start_plus_len, 0),
# start + len < 0
0,
# start + len >= 0
start_plus_len),
# start >= 0: use min(start, length)
switch(lt(start, length), start, length))
return slice(start, length, 1), 1
# This is the generic case.
if is_step_constant:
# When we know the sign of `step`, the graph can be made simpler.
assert step != 0
if step > 0:
def switch_neg_step(a, b):
return b
abs_step = step
sgn_step = 1
else:
def switch_neg_step(a, b):
return a
abs_step = -step
sgn_step = -1
else:
is_step_neg = lt(step, 0)
def switch_neg_step(a, b):
return switch(is_step_neg, a, b)
abs_step = abs(step)
sgn_step = sgn(step)
defstart = switch_neg_step(length - 1, 0)
defstop = switch_neg_step(-1, length)
if start is None:
start = defstart
else:
start = switch(lt(start, 0), start + length, start)
start = switch(lt(start, 0), switch_neg_step(-1, 0), start)
start = switch(ge(start, length),
switch_neg_step(length - 1, length),
start)
if stop is None or stop == sys.maxsize:
# The special "maxsize" case is probably not needed here,
# as slices containing maxsize are not generated by
# __getslice__ anymore.
stop = defstop
else:
stop = switch(lt(stop, 0), stop + length, stop)
stop = switch(lt(stop, 0), -1, stop)
stop = switch(ge(stop, length), length, stop)
nw_stop = switch_neg_step(start + 1, stop)
slice_len = (start - stop - 1) // abs_step + 1
slice_len = switch(lt(slice_len, 0), 0, slice_len)
neg_start = nw_stop - (slice_len - 1) * abs_step - 1
neg_start = switch(lt(neg_start, 0), (nw_stop - 1), neg_start)
nw_start = switch_neg_step(neg_start, start)
nw_start = switch(lt(nw_start, 0), 0, nw_start)
nw_stop = switch(lt(nw_stop, 0), 0, nw_stop)
# Ensure start <= stop.
nw_start = switch(lt(nw_start, nw_stop), nw_start, nw_stop)
nw_step = abs_step
if step != 1:
reverse = sgn_step
return slice(nw_start, nw_stop, nw_step), reverse
else:
return slice(nw_start, nw_stop, nw_step), 1
else:
value = theano.tensor.extract_constant(theslice)
value = switch(lt(value, 0), (value + length), value)
return value, 1
class Subtensor(Op):
"""Return a subtensor view
The inputs array is the tensor x, followed by scalar integer types.
TODO: WRITEME: how are the scalar integer variables formatted?
This class uses a relatively complex internal representation of the inputs
to remember how the input tensor x should be sliced.
idx_list: instance variable TODO: WRITEME: is this a list or a tuple?
(old docstring gives two conflicting
descriptions)
elements are either integers, theano scalar types, or slices.
one element per "explicitly named dimension"
TODO: WRITEME: what is an "explicitly named dimension" ?
if integer:
indexes into the inputs array
if slice:
start/stop/step members of each slice are integer indices
into the inputs array or None
integer indices be actual integers or theano scalar types
Note that the idx_list defines the Op, so two Subtensor instances are
considered to be different Ops if they have different idx_list fields.
This means that the entries in it are theano Types, not theano Variables.
@todo: add support for advanced tensor indexing (in Subtensor_dx too).
"""
e_invalid = ('The index list is longer (size %d) than the number of '
'dimensions of the tensor(namely %d). You are asking for '
'a dimension of the tensor that does not exist! You might '
'need to use dimshuffle to add extra dimension to your '
'tensor.')
e_subslice = 'nested slicing is not supported'
e_indextype = "Invalid index type or slice for Subtensor"
debug = 0
check_input = False
view_map = {0: [0]}
_f16_ok = True
__props__ = ("idx_list",)
@staticmethod
def collapse(idxs, cond):
"""
idxs: a list of indices or slices.
cond: a callable that returns a bool
returns: idxs, with the slices flattened out into a list.
if cond is true for an entry, does not flatten it.
"""
ret = []
def helper(entry):
if cond(entry):
ret.append(entry)
elif isinstance(entry, slice):
helper(entry.start)
helper(entry.stop)
helper(entry.step)
for idx in idxs:
helper(idx)
return ret
@staticmethod
def convert(entry, slice_ok=True):
"""
The "idx_list" field is unique to each Subtensor instance.
It is not unique to each Apply node, so it should not refer to
specific Variables. This method changes references to Variables
into references to Types.
TODO: WRITEME: This method also accepts "entry" already being a Type;
when would that happen?
"""
invalid_scal_types = [scal.float64, scal.float32, scal.float16]
scal_types = [scal.int64, scal.int32, scal.int16, scal.int8]
tensor_types = [theano.tensor.lscalar, theano.tensor.iscalar,
theano.tensor.wscalar, theano.tensor.bscalar]
invalid_tensor_types = [theano.tensor.fscalar, theano.tensor.dscalar,
theano.tensor.cscalar, theano.tensor.zscalar]
if (isinstance(entry, gof.Variable) and
(entry.type in invalid_scal_types or
entry.type in invalid_tensor_types)):
raise TypeError("Expected an integer")
if isinstance(entry, gof.Variable) and entry.type in scal_types:
return entry.type
elif isinstance(entry, gof.Type) and entry in scal_types:
return entry
if (isinstance(entry, gof.Variable) and
entry.type in tensor_types and
numpy.all(entry.type.broadcastable)):
return scal.get_scalar_type(entry.type.dtype)
elif (isinstance(entry, gof.Type) and
entry in tensor_types and
numpy.all(entry.broadcastable)):
return scal.get_scalar_type(entry.dtype)
elif slice_ok and isinstance(entry, slice):
a = entry.start
b = entry.stop
c = entry.step
if a is not None:
slice_a = Subtensor.convert(a, False)
else:
slice_a = None
if b is not None and b != sys.maxsize:
# The special "maxsize" case is probably not needed here,
# as slices containing maxsize are not generated by
# __getslice__ anymore.
slice_b = Subtensor.convert(b, False)
else:
slice_b = None
if c is not None:
slice_c = Subtensor.convert(c, False)
else:
slice_c = None
return slice(slice_a, slice_b, slice_c)
elif isinstance(entry, (integer_types, numpy.integer)):
# Disallow the use of python scalars in idx_list
raise TypeError("Python scalar in idx_list."
"Please report this error to theano-dev.")
else:
raise AdvancedIndexingError(Subtensor.e_indextype, entry)
def get_constant_idx(self, inputs, allow_partial=False,
only_process_constants=False):
"""
Return the idx_list with constant inputs replaced by their
python scalar equivalent. May raise
`theano.tensor.NotScalarConstantError` if the idx contains
non-constant entries.
If allow_partial is True, then entries that are not constant
will stay as their input variable rather than raising an
exception.
None entries are always left as-is.
Example usage (where v, a are appropriately typed theano variables):
>>> b = a[v, 1:3]
>>> b.owner.op.idx_list
(Scalar(int64), slice(Scalar(int64), Scalar(int64), None))
>>> b.owner.op.get_constant_idx(b.owner.inputs, allow_partial=True)
[v, slice(1, 3, None)]
>>> b.owner.op.get_constant_idx(b.owner.inputs)
NotScalarConstantError: v
:param only_process_constants: If True, we only attempt to obtain
the value of an index/slice if it's directly constant and don't
try to dig through dimshuffles, fills, allocs, and other to figure
out its value.
"""
real_idx = get_idx_list(inputs, self.idx_list)
def conv(val):
if val is None:
return None
elif isinstance(val, slice):
return slice(conv(val.start),
conv(val.stop),
conv(val.step))
else:
try:
return get_scalar_constant_value(
val,
only_process_constants=only_process_constants)
except theano.tensor.NotScalarConstantError:
if allow_partial:
return val
else:
raise
return list(map(conv, real_idx))
def __init__(self, idx_list):
self.idx_list = tuple(map(self.convert, idx_list))
@staticmethod
def my_as_scalar(a):
# Since scal.as_scalar does not know about tensor types (it would
# create a circular import) , this method converts either a
# TensorVariable or a ScalarVariable to a scalar.
if isinstance(a, gof.Variable) and isinstance(a.type, TensorType):
return theano.tensor.scalar_from_tensor(a)
else:
return scal.as_scalar(a)
def make_node(self, x, *inputs):
"""
x: the tensor to take a subtensor of
inputs: a list of theano Scalars
"""
x = theano.tensor.as_tensor_variable(x)
inputs = tuple(self.my_as_scalar(a) for a in inputs)
idx_list = list(self.idx_list)
if len(idx_list) > x.type.ndim:
exception = ValueError(Subtensor.e_invalid % (
len(idx_list), x.type.ndim))
exception.subtensor_invalid = True
raise exception
input_types = Subtensor.collapse(idx_list,
lambda entry: isinstance(entry,
gof.Type))
if len(inputs) != len(input_types):
raise IndexError(
"Not enough inputs to fill in the Subtensor template.",
inputs, idx_list)
for input, expected_type in izip(inputs, input_types):
if input.type != expected_type:
raise TypeError(
"Wrong type for Subtensor template. Expected %s, got %s."
% (input.type, expected_type))
# infer the broadcasting pattern
padded = (self.get_constant_idx((None,) + inputs, allow_partial=True) +
[slice(None, None, None)] * (x.type.ndim - len(idx_list)))
broadcastable = []
for i, (p, bc) in enumerate(izip(padded, x.type.broadcastable)):
if isinstance(p, slice):
if bc:
start = p.start
try:
start = get_scalar_constant_value(start)
except NotScalarConstantError:
pass
if start is None or start == 0:
start = p.start
if start is None:
start = 0
if (p.stop is None or
(isinstance(p.stop, (int, numpy.integer,
numpy.ndarray)) and
p.stop > start)):
broadcastable.append(True)
continue
broadcastable.append(False)
return gof.Apply(self,
(x, ) + inputs,
[theano.tensor.tensor(dtype=x.type.dtype,
broadcastable=broadcastable)])
def perform(self, node, inputs, out_):
out, = out_
x = inputs[0]
cdata = get_idx_list(inputs, self.idx_list)
if len(cdata) == 1:
cdata = cdata[0]
out[0] = numpy.asarray(x.__getitem__(cdata))
def infer_shape(self, node, shapes):
xshp = shapes[0]
assert len(xshp) == node.inputs[0].ndim
outshp = []
actual_idx_list = list(get_idx_list(node.inputs, self.idx_list))
padded = (actual_idx_list +
[slice(None, None, None)] * (len(xshp) - len(self.idx_list)))
i = 0
for idx, xl in izip(padded, xshp):
if isinstance(idx, slice):
# If it is the default (None, None, None) slice, or a variant,
# the shape will be xl
if ((idx.start in [None, 0]) and
(idx.stop in [None, sys.maxsize]) and
(idx.step is None or idx.step == 1)):
outshp.append(xl)
else:
cnf = get_canonical_form_slice(idx, xl)[0]
if cnf.step == 1:
length = cnf.stop - cnf.start
else:
length = (cnf.stop - cnf.start - 1) // cnf.step + 1
outshp.append(length)
i += 1
else:
# That dimension is dropped
pass
assert i == node.outputs[0].ndim
assert len(outshp) == node.outputs[0].ndim
return [outshp]
def grad(self, inputs, grads):
gz, = grads
x = inputs[0]
rest = inputs[1:]
output = self(*inputs)
if output.dtype.find('int') != -1:
first = x.zeros_like().astype(theano.config.floatX)
else:
first = IncSubtensor(self.idx_list)(x.zeros_like(), gz, *rest)
return ([first] + [DisconnectedType()()] * len(rest))
def connection_pattern(self, node):
rval = [[True]]
for ipt in node.inputs[1:]:
rval.append([False])
return rval
def __hash__(self):
# TODO: optimize by cache this hash value
msg = []
for entry in self.idx_list:
if isinstance(entry, slice):
msg += [(entry.start, entry.stop, entry.step)]
else:
msg += [entry]
idx_list = tuple(msg)
# backport
# idx_list = tuple((entry.start, entry.stop, entry.step)
# if isinstance(entry, slice)
# else entry
# for entry in self.idx_list)
return hash(idx_list)
@staticmethod
def str_from_slice(entry):
msg = []
for x in [entry.start, entry.stop, entry.step]:
if x is None:
msg.append("")
else:
msg.append(str(x))
return ":".join(msg)
def __str__(self):
indices = []
for entry in self.idx_list:
if isinstance(entry, slice):
indices.append(self.str_from_slice(entry))
else:
indices.append(str(entry))
return "%s{%s}" % (self.__class__.__name__, ", ".join(indices))
@staticmethod
def default_helper_c_code_args():
"""
Returns a dictionary of default arguments to
helper_c_code
"""
return {"c_prefix": "PyArray",
"strides_mul": 1}
@staticmethod
def helper_c_code(node, name, inputs, outputs, sub, idx_list, view_ndim,
c_prefix=None,
strides_mul=None):
"""
The parameters c_prefix are there to allow reusing this
function on PyArray and CudaNdarray object.
This fct take as input the x,
"""
default_args = Subtensor.default_helper_c_code_args()
if strides_mul is None:
strides_mul = default_args['strides_mul']
if c_prefix is None:
c_prefix = default_args['c_prefix']
#
# two arrays are created in C code:
# is_slice: len == ndim, 0 means int, 1 means slice
# subtensor_spec: len = n_ints + 3 * n_slices
#
fail = sub['fail']
init_cmds = [] # initialization for subtensor_spec
is_slice = []
# TODO: change that, it might lead to unexpected results,
# see assembla-#767
NONE_CODE = sys.maxsize - 1
pos = [0, 1] # annoying version of global variable for init_entry
def inc_spec_pos(amt):
pos[0] += amt
def inc_input_pos(amt):
pos[1] += amt
def spec_pos():
return pos[0]
def input_pos():
return pos[1]
def init_entry(entry, depth=0):
if isinstance(entry, (numpy.integer, int)):
init_cmds.append(
"subtensor_spec[%i] = %i;" % (spec_pos(),
entry))
inc_spec_pos(1)
if depth == 0:
is_slice.append(0)
elif isinstance(entry, Type):
init_cmds.append(
"subtensor_spec[%i] = %s;" % (spec_pos(),
inputs[input_pos()]))
inc_spec_pos(1)
inc_input_pos(1)
if depth == 0:
is_slice.append(0)
elif entry is None:
init_cmds.append(
"subtensor_spec[%i] = %i;" % (spec_pos(),
NONE_CODE))
inc_spec_pos(1)
if depth == 0:
is_slice.append(0)
elif depth == 0 and isinstance(entry, slice):
init_entry(entry.start, depth + 1)
init_entry(entry.stop, depth + 1)
init_entry(entry.step, depth + 1)
is_slice.append(1)
else:
assert 0, entry
for entry in idx_list:
init_entry(entry)
# make sure we used all inputs
assert input_pos() == len(inputs), input_pos()
assert len(is_slice) <= node.inputs[0].ndim, node.inputs[0].ndim
len_is_slice = len(is_slice)
len_subtensor_spec = spec_pos()
subensor_spec = "npy_intp subtensor_spec[%(len_subtensor_spec)s];" % locals()
if len_subtensor_spec == 0:
subensor_spec = "npy_intp * subtensor_spec = NULL;"
if is_slice:
is_slice_init = "int is_slice[] = {" + ",".join([str(s) for s in
is_slice]) + "};"
else:
is_slice_init = "int* is_slice = NULL;"
subtensor_init = "\n".join(init_cmds)
x, = inputs[:1]
z, = outputs
if view_ndim:
rval = """
// Argument of the view
npy_intp xview_dims[%(view_ndim)s];
npy_intp xview_strides[%(view_ndim)s];
""" % locals()
else:
rval = """
// Argument of the view
npy_intp* xview_dims = NULL;
npy_intp* xview_strides = NULL;
"""
rval += """
// One more argument of the view
npy_intp xview_offset = 0;
// The subtensor is created by iterating over the dimensions
// and updating stride, shape, and data pointers
%(is_slice_init)s
%(subensor_spec)s
%(subtensor_init)s;
int spec_pos = 0; //position in subtensor_spec
int inner_ii = 0; // the current dimension of zview
int outer_ii = 0; // current dimension of z
for (; outer_ii < %(len_is_slice)s; ++outer_ii)
{
if (is_slice[outer_ii])
{
npy_intp length = %(c_prefix)s_DIMS(%(x)s)[outer_ii];
npy_intp slicelength;
npy_intp start = subtensor_spec[spec_pos+0];
npy_intp stop = subtensor_spec[spec_pos+1];
npy_intp step = subtensor_spec[spec_pos+2];
if (step == %(NONE_CODE)s) step = 1;
npy_intp defstart = step < 0 ? length-1 : 0;
npy_intp defstop = step < 0 ? -1 : length;
// logic adapted from
// PySlice_GetIndicesEx in python source
if (!step)
{
PyErr_Format(PyExc_ValueError,
"slice step cannot be zero");
%(fail)s;
}
if (start == %(NONE_CODE)s)
{
start = defstart;
}
else
{
if (start < 0) start += length;
if (start < 0) start = (step < 0) ? -1 : 0;
if (start >= length)
start = (step < 0) ? length - 1 : length;
}
if (stop == %(NONE_CODE)s)
{
stop = defstop;
}
else
{
if (stop < 0) stop += length;
if (stop < 0) stop = (step < 0) ? -1 : 0;
if (stop >= length)
stop = (step < 0) ? length - 1 : length;
}
if ((step < 0 && stop >= start)
|| (step > 0 && start >= stop)) {
slicelength = 0;
}
else if (step < 0) {
slicelength = (stop-start+1)/step+1;
}
else {
slicelength = (stop-start-1)/step+1;
}
if (0){
fprintf(stdout, "start %%zi\\n", start);
fprintf(stdout, "stop %%zi\\n", stop);
fprintf(stdout, "step %%zi\\n", step);
fprintf(stdout, "length %%zi\\n", length);
fprintf(stdout, "slicelength %%zi\\n", slicelength);
}
assert (slicelength <= length);
xview_offset += (npy_intp)%(c_prefix)s_STRIDES(%(x)s)[outer_ii]
* start * %(strides_mul)s;
xview_dims[inner_ii] = slicelength;
xview_strides[inner_ii] = (npy_intp)%(c_prefix)s_STRIDES(%(x)s)[outer_ii] * step;
inner_ii += 1;
spec_pos += 3;
}
else // tuple coord `outer_ii` is an int
{
int idx = subtensor_spec[spec_pos];
if (idx < 0) idx += %(c_prefix)s_DIMS(%(x)s)[outer_ii];
if (idx >= 0)
{
if (idx < %(c_prefix)s_DIMS(%(x)s)[outer_ii])
{
xview_offset += (npy_intp)%(c_prefix)s_STRIDES(%(x)s)[outer_ii] * idx *
%(strides_mul)s;
}
else
{
PyErr_Format(PyExc_IndexError,"index out of bounds");
%(fail)s;
}
}
else
{
PyErr_Format(PyExc_IndexError,"index out of bounds");
%(fail)s;
}
spec_pos += 1;
}
}
assert (inner_ii <= %(view_ndim)s);
while (inner_ii < %(view_ndim)s)
{
assert (outer_ii < %(c_prefix)s_NDIM(%(x)s));
xview_dims[inner_ii] = %(c_prefix)s_DIMS(%(x)s)[outer_ii];
xview_strides[inner_ii] = %(c_prefix)s_STRIDES(%(x)s)[outer_ii];
inner_ii += 1;
outer_ii += 1;
}
""" % locals()
# print rval
return rval
@staticmethod
def helper_c_code_cache_version():
return (9,)
def c_code(self, node, name, inputs, outputs, sub): # DEBUG
if not isinstance(node.inputs[0].type, theano.tensor.TensorType):
raise NotImplementedError()
x = inputs[0]
z, = outputs
ndim = node.inputs[0].ndim
view_ndim = node.outputs[0].ndim
fail = sub['fail']
decl = "PyArrayObject * xview = NULL;"
checkNDim = """
if (PyArray_NDIM(%(x)s) != %(ndim)s){
PyErr_SetString(PyExc_ValueError,
"Expected %(ndim)s dimensions input"
);
%(fail)s
}
""" % locals()
get_xview = self.helper_c_code(node, name, inputs, outputs, sub,
self.idx_list, view_ndim)
build_view = """
//TODO: give this Op a second output so that this view can be cached
//TODO: alternatively, fix the memory leak on failure
Py_INCREF(PyArray_DESCR(%(x)s));
xview = (PyArrayObject*)PyArray_NewFromDescr(
&PyArray_Type,
PyArray_DESCR(%(x)s),
%(view_ndim)s,
xview_dims,
xview_strides,
PyArray_BYTES(%(x)s) + xview_offset,
PyArray_FLAGS(%(x)s),
NULL);
assert (PyArray_NDIM(xview) == %(view_ndim)s);
if (!xview)
{
%(fail)s;
}
""" % locals()
finish_view = """
//This is needed for NumPy 1.5, but not 1.7.2
PyArray_UpdateFlags(xview, NPY_ARRAY_C_CONTIGUOUS| NPY_ARRAY_F_CONTIGUOUS);
Py_XDECREF(%(z)s);
Py_INCREF(py_%(x)s);
#if NPY_API_VERSION < 0x00000007
PyArray_BASE(xview) = py_%(x)s;
#else
PyArray_SetBaseObject(xview, py_%(x)s);
#endif
assert(py_%(x)s == (PyObject*)%(x)s);
%(z)s = xview;
""" % locals()
return (decl + checkNDim +
"{" + get_xview + build_view + finish_view + "}")
def c_code_cache_version(self):
hv = self.helper_c_code_cache_version()
# If `helper_c_code_cache_version` is not versioned we do not want to
# have a versioned version of this op's C code.
if len(hv) == 0:
return ()
return (4, hv)
def R_op(self, inputs, eval_points):
# Subtensor is not differentiable wrt to its indices, therefore we
# do not even need to consider the eval_points provided for those
# (they should be defaulted to zeros_like by the global R_op)
if eval_points[0] is None:
return [None]
return self(eval_points[0], *inputs[1:], **dict(return_list=True))
class SubtensorPrinter:
def process(self, r, pstate):
if r.owner is None:
raise TypeError("Can only print Subtensor.")
elif isinstance(r.owner.op, Subtensor):
idxs = r.owner.op.idx_list
inputs = list(r.owner.inputs)
input = inputs.pop()
sidxs = []
inbrack_pstate = pstate.clone(precedence=-1000)
for entry in idxs:
if isinstance(entry, int):
sidxs.append(str(entry))
elif isinstance(entry, scal.Scalar):
sidxs.append(inbrack_pstate.pprinter.process(inputs.pop()))
elif isinstance(entry, slice):
if entry.start is None or entry.start == 0:
msg1 = ""
else:
msg1 = entry.start
if entry.stop is None or entry.stop == sys.maxsize:
msg2 = ""
else:
msg2 = entry.stop
if entry.step is None:
msg3 = ""
else:
msg3 = ":%s" % entry.step
sidxs.append("%s:%s%s" % (msg1, msg2, msg3))
return "%s[%s]" % (pstate.pprinter.process(
input,
pstate.clone(precedence=1000)),
", ".join(sidxs))
else:
raise TypeError("Can only print Subtensor.")
pprint.assign(lambda pstate, r: r.owner and isinstance(r.owner.op, Subtensor),
SubtensorPrinter())
def set_subtensor(x, y, inplace=False,
tolerate_inplace_aliasing=False):
"""Return x with the given subtensor overwritten by y.
Example: To replicate the numpy expression "r[10:] = 5", type
>>> r = ivector()
>>> new_r = set_subtensor(r[10:], 5)
:param x: symbolic variable for the lvalue of = operation
:param y: symbolic variable for the rvalue of = operation
:param tolerate_inplace_aliasing: see inc_subtensor for documentation.
"""
return inc_subtensor(x, y, inplace, set_instead_of_inc=True,
tolerate_inplace_aliasing=tolerate_inplace_aliasing)
def inc_subtensor(x, y, inplace=False, set_instead_of_inc=False,
tolerate_inplace_aliasing=False):
"""Return x with the given subtensor incremented by y.
:param x: the symbolic result of a Subtensor operation.
:param y: the amount by which to increment ths subtensor in question
:param inplace: Don't use. Theano will do it when possible.
:param set_instead_of_inc: If True, do a set_subtensor instead.
:param tolerate_inplace_aliasing: allow x and y to be views of a single
underlying array even while working inplace. For correct results,
x and y must not be overlapping views; if they overlap, the result
of this Op will generally be incorrect. This value has no effect if
inplace=False.
Example: To replicate the numpy expression "r[10:] += 5", type
>>> r = ivector()
>>> new_r = inc_subtensor(r[10:], 5)
"""
# First of all, y cannot have a higher dimension than x,
# nor have non-broadcastable dimensions where x is broadcastable.
x = theano.tensor.as_tensor_variable(x)
y = theano.tensor.as_tensor_variable(y)
if y.ndim > x.ndim:
raise TypeError(("Trying to increment a %d-dimensional "
"subtensor with a %d-dimensional value.") % (x.ndim,
y.ndim))
dim_offset = x.ndim - y.ndim
for dim in xrange(y.ndim):
if (x.broadcastable[dim + dim_offset] and not y.broadcastable[dim]):
# It is acceptable to try to increment a subtensor with a
# broadcastable dim with a tensor that is not broadcastable
# on that dimension. However, its length must then be 1.
# We insert a Rebroadcast Op to make sure it is the case.
y = addbroadcast(y, dim)
if not x.owner:
raise TypeError('x must be the result of a subtensor operation')
# retrieve idx_list from x.owner
if isinstance(x.owner.op, Subtensor):
if tolerate_inplace_aliasing:
destroyhandler_tolerate_aliased = [[0, 1]]
else:
destroyhandler_tolerate_aliased = []
the_op = IncSubtensor(
x.owner.op.idx_list, inplace, set_instead_of_inc,
destroyhandler_tolerate_aliased=destroyhandler_tolerate_aliased)
real_x = x.owner.inputs[0]
real_idxargs = x.owner.inputs[1:]
return the_op(real_x, y, *real_idxargs)
elif isinstance(x.owner.op, AdvancedSubtensor1):
real_x = x.owner.inputs[0]
ilist = x.owner.inputs[1]
the_op = AdvancedIncSubtensor1(inplace,
set_instead_of_inc=set_instead_of_inc)
return the_op(real_x, y, ilist)
elif isinstance(x.owner.op, AdvancedSubtensor):
real_x = x.owner.inputs[0]
ilist = x.owner.inputs[1:]
the_op = AdvancedIncSubtensor(inplace,
set_instead_of_inc=set_instead_of_inc)
return the_op(real_x, y, *ilist)
elif isinstance(x.owner.op, DimShuffle):
inner_x = x.owner.inputs[0]
# In the dimshuffle case, there are in fact two dimshuffles:
# one to make the indexed dimension the last one,
# and one to put it back where it was. So, in the case where we have
# inc_subtensor(x[:,i], y), the graph is actually
# inc_subtensor((x.T)[i].T, y).
# We could get all the way to x, and then get rid of the dimshuffles
# completely, but the problem is that advanced_inc_subtensor1 can only
# work on the first (outer-most, left-most) dimension of x,
# just like advanced_subtensor1.
# So we call advanced_inc_subtensor1(x.T, i, y.T) (as we also need to
# transpose y if it is not a scalar or a vector), but then we need to
# return something that has the same shape as x, not as x.T (inner_x).
# So re-apply the outer dimshuffle on the new inc_subtensor,
# and return advanced_inc_subtensor1(x.T, i, y.T).T.
# Get the dimshuffle pattern to apply to y.
x_order = x.owner.op.new_order
y_order = ['x'] * x.ndim
for i, v in enumerate(x_order):
if v != 'x' and (v - dim_offset) >= 0:
y_order[v - dim_offset] = i
# Warn if this code path would have produced wrong results in the past
if config.warn.inc_set_subtensor1:
# Dimshuffle pattern for y that would be equivalent to past code
prev_y_order = ['x'] * (dim_offset) + list(range(y.ndim))
if y_order != prev_y_order:<|fim▁hole|> 'earlier versions prior to 0.7 (or this development '
'version) may have yielded an incorrect result in '
'this `inc_subtensor` or `set_subtensor` operation. '
'To remove this warning, you can either set the '
'`warn.inc_set_subtensor1` config option to `False`, '
'or `warn.ignore_bug_before` to at least "0.7".',
stacklevel=2)
inner_incsubtensor = inc_subtensor(
inner_x,
y.dimshuffle(y_order),
inplace=inplace,
set_instead_of_inc=set_instead_of_inc,
tolerate_inplace_aliasing=tolerate_inplace_aliasing)
return x.owner.op(inner_incsubtensor, *x.owner.inputs[1:])
elif isinstance(x.owner.op, theano.tensor.Reshape):
# This case happens when the indices are not arranged as a vector, but
# as a higher-dimensional array. This is handled by the subtensor
# by flattening this list, taking the subtensor, then reshaping the
# result.
inner_x = x.owner.inputs[0]
# Try to apply inc_subtensor on inner_x.
# If it works, there is no need to reshape, as the inc_subtensor
# will have the same shape as inner_x, which is what we want.
# We also explicitly duplicate y to its broadcasted shape
# before we partially flatten it to inner_x dimension. This is
# not strictly needed in all cases, but it is easier this way.
if y.ndim > 0:
# This if is needed to prevent some useless warning about
# old code bug.
expanded_y = alloc(y, *[x.shape[i] for i in xrange(x.ndim)])
flattened_y = expanded_y.flatten(inner_x.ndim)
else:
flattened_y = y
# Warn if this code path would have produced wrong results in the past
if config.warn.inc_set_subtensor1:
if inner_x.ndim > 1 and sum(y.broadcastable) > 0:
warnings.warn(
'Although your current code is fine, please note that '
'earlier versions prior to 0.7 (or this development '
'version) may have yielded an incorrect result in '
'this `inc_subtensor` or `set_subtensor` operation. '
'To remove this warning, you can either set the '
'`warn.inc_set_subtensor1` config option to `False`, '
'or `warn.ignore_bug_before` to at least "0.7".',
stacklevel=2)
inner_incsubtensor = inc_subtensor(
inner_x,
flattened_y,
inplace=inplace,
set_instead_of_inc=set_instead_of_inc,
tolerate_inplace_aliasing=tolerate_inplace_aliasing)
return inner_incsubtensor
else:
raise TypeError('x must be the result of a subtensor operation')
class IncSubtensor(Op):
"""Increment a subtensor.
This is like numpy's
x[i,j,k] += y
It is used internally to implement the gradient on SubTensor.
:param set_instead_of_inc: if True set the subtensor to the value instead
of incrementing it by that value.
"""
check_input = False
__props__ = ("idx_list", "inplace", "set_instead_of_inc")
def __init__(self, idx_list, inplace=False, set_instead_of_inc=False,
destroyhandler_tolerate_aliased=None):
if destroyhandler_tolerate_aliased is None:
destroyhandler_tolerate_aliased = []
self.idx_list = list(map(Subtensor.convert, idx_list))
self.inplace = inplace
if inplace:
self.destroy_map = {0: [0]}
self.destroyhandler_tolerate_aliased = list(
destroyhandler_tolerate_aliased)
self.set_instead_of_inc = set_instead_of_inc
def __hash__(self):
msg = []
for entry in self.idx_list:
if isinstance(entry, slice):
msg += [(entry.start, entry.stop, entry.step)]
else:
msg += [entry]
idx_list = tuple(msg)
# backport
# idx_list = tuple((entry.start, entry.stop, entry.step)
# if isinstance(entry, slice)
# else entry
# for entry in self.idx_list)
return (hashtype(self) ^ hash(idx_list) ^ hash(self.inplace) ^
hash(self.set_instead_of_inc))
def __str__(self):
indices = []
for entry in self.idx_list:
if isinstance(entry, slice):
indices.append(Subtensor.str_from_slice(entry))
else:
indices.append(str(entry))
if self.inplace:
msg = 'Inplace'
else:
msg = ''
if not self.set_instead_of_inc:
msg += 'Inc'
else:
msg += 'Set'
return "%s{%s;%s}" % (
self.__class__.__name__,
msg,
", ".join(indices))
def make_node(self, x, y, *inputs):
"""
x: the tensor to increment
y: the value to increment by
inputs: TODO WRITEME
"""
x, y = map(theano.tensor.as_tensor_variable, [x, y])
if y.ndim > x.ndim:
raise ValueError(("Trying to increment a %d-dimensional "
"subtensor with a %d-dimensional value.") % (
x.ndim, y.ndim))
inputs = tuple(map(Subtensor.my_as_scalar, inputs))
idx_list = list(self.idx_list)
if len(idx_list) > x.type.ndim:
exception = ValueError(
Subtensor.e_invalid % (
len(idx_list),
x.type.ndim))
exception.subtensor_invalid = True
raise exception
input_types = Subtensor.collapse(
idx_list,
lambda entry: isinstance(entry, gof.Type))
if len(inputs) != len(input_types):
raise IndexError(
"Not enough inputs to fill in the Subtensor template.",
inputs, idx_list)
for input, expected_type in izip(inputs, input_types):
if input.type != expected_type:
raise TypeError(
"Wrong type for Subtensor template. Expected %s, got %s."
% (input.type, expected_type))
return gof.Apply(self,
(x, y) + inputs,
[x.type()])
def decl_view(self):
return "PyArrayObject * zview = NULL;"
def perform(self, node, inputs, out_):
out, = out_
x, y = inputs[:2]
indices = list(reversed(inputs[2:]))
def convert(entry):
if isinstance(entry, gof.Type):
rval = indices.pop()
if sys.version_info < (2, 5):
# Before Python 2.5, PySlice_GetIndicesEx requires
# Python int to be passed.
rval_ = int(rval)
if rval_ != rval:
raise IndexError((
"Invalid value for indexing: %s. "
"That value may be too big.") % rval)
return rval_
return rval
elif isinstance(entry, slice):
return slice(convert(entry.start),
convert(entry.stop),
convert(entry.step))
else:
return entry
cdata = tuple(map(convert, self.idx_list))
if len(cdata) == 1:
cdata = cdata[0]
if not self.inplace:
x = x.copy()
sub_x = x.__getitem__(cdata)
if sub_x.shape:
# we've sliced out an N-D tensor with N > 0
if not self.set_instead_of_inc:
sub_x += y
else:
# sub_x += -sub_x + y
x.__setitem__(cdata, y)
else:
# scalar case
if not self.set_instead_of_inc:
x.__setitem__(cdata, sub_x + y)
else:
x.__setitem__(cdata, y)
out[0] = x
def c_code(self, node, name, inputs, outputs, sub):
# This method delegates much of the work to helper
# methods. This method implements the main logic
# but subclasses may override the helper methods
# to change the particulars, e.g. GpuIncSubtensor
# turns the view/copy operations on numpy arrays
# into the same operations on cuda arrays.
self.do_type_checking(node)
if self.inplace: # convert bool to int
inplace = 1
else:
inplace = 0
x = inputs[0]
y = inputs[1]
z, = outputs
if self.set_instead_of_inc: # convert bool to int
op_is_set = 1
else:
op_is_set = 0
fail = sub['fail']
view_ndim = (node.inputs[0].ndim -
numpy.sum([not isinstance(idx, slice)
for idx in self.idx_list]))
copy_of_x = self.copy_of_x(x)
copy_input_if_necessary = """
if (%(inplace)s)
{
if (%(x)s != %(z)s)
{
Py_XDECREF(%(z)s);
Py_INCREF(%(x)s);
%(z)s = %(x)s;
}
}
else
{
Py_XDECREF(%(z)s);
%(z)s = %(copy_of_x)s;
}
""" % locals()
# get info needed to make zview: a view of %(z)s
helper_args = self.get_helper_c_code_args()
get_zview = Subtensor.helper_c_code(
node=node,
name=name,
inputs=outputs[:1] + inputs[2:],
outputs=outputs,
sub=sub,
idx_list=self.idx_list,
view_ndim=view_ndim,
** helper_args
)
# Make a view on the output, as we will write into it.
alloc_zview = self.make_view_array(z, view_ndim)
build_view = """
//TODO: give this Op a second output so that this view can be cached
//TODO: alternatively, fix the memory leak on failure
%(alloc_zview)s;
if (!zview)
{
%(fail)s;
}
""" % locals()
copy_into = self.copy_into("zview", y)
add_to_zview = self.add_to_zview(name, y, fail)
make_modification = """
if (%(op_is_set)s)
{
if (%(copy_into)s) // does broadcasting
{
Py_DECREF(zview);
%(fail)s;
}
}
else
{
%(add_to_zview)s
}
""" % locals()
return (self.decl_view() +
copy_input_if_necessary +
get_zview +
build_view +
make_modification +
"Py_DECREF(zview);"
)
def do_type_checking(self, node):
""" Should raise NotImplementedError if c_code does not support
the types involved in this node.
"""
if not isinstance(node.inputs[0].type, theano.tensor.TensorType):
raise NotImplementedError()
def c_code_cache_version(self):
hv = Subtensor.helper_c_code_cache_version()
if hv:
return (1, hv)
else:
return ()
def copy_of_x(self, x):
"""
:param x: a string giving the name of a C variable
pointing to an array
:return: C code expression to make a copy of x
Base class uses PyArrayObject *, subclasses may override for
different types of arrays.
"""
# Parameters of PyArrary_FromAny are:
# array
# dtype: we pass NULL to say any dtype is acceptable, so the existing
# dtype will be copied
# min_depth: we pass 0 to have this parameter ignored
# max_depth: we pass 0 to have this parameter ignored
# requirements: here we pass NPY_ARRAY_ENSURECOPY to force a copy
# context: this is almost always NULL, I'm not sure what it's used for
return """(PyArrayObject*)PyArray_FromAny(py_%(x)s, NULL, 0, 0,
NPY_ARRAY_ENSURECOPY, NULL)""" % locals()
def make_view_array(self, x, view_ndim):
"""
:param x: a string identifying an array to be viewed
:param view_ndim: a string specifying the number of dimensions
to have in the view
This doesn't need to actually set up the view with the
right indexing; we'll do that manually later.
"""
return """Py_INCREF(PyArray_DESCR(%(x)s));
zview = (PyArrayObject*)PyArray_NewFromDescr(
&PyArray_Type,
PyArray_DESCR(%(x)s),
%(view_ndim)s,
xview_dims, //PyArray_DIMS(%(x)s),
xview_strides, //PyArray_STRIDES(%(x)s),
PyArray_BYTES(%(x)s) + xview_offset, //PyArray_DATA(%(x)s),
PyArray_FLAGS(%(x)s),
NULL);
//This is needed for NumPy 1.5, but not 1.7.2
PyArray_UpdateFlags(zview, NPY_ARRAY_C_CONTIGUOUS| NPY_ARRAY_F_CONTIGUOUS);
""" % locals()
def get_helper_c_code_args(self):
""" Return a dictionary of arguments to pass to helper_c_code."""
return Subtensor.default_helper_c_code_args()
def copy_into(self, view, source):
"""
view: string, C code expression for an array
source: string, C code expression for an array
returns a C code expression to copy source into view, and
return 0 on success
"""
return """PyArray_CopyInto(%(view)s, %(source)s)""" % locals()
def add_to_zview(self, name, x, fail):
""" Return C code to add x to zview. Should DECREF zview if the
add fails."""
return """
PyArrayObject * add_rval = (PyArrayObject*)PyNumber_InPlaceAdd(
(PyObject*)zview, py_%(x)s);
if (add_rval)
{
assert (PyArray_Check((PyObject*)add_rval));
assert (PyArray_DATA(add_rval) == PyArray_DATA(zview));
Py_DECREF(add_rval);
}
else
{
Py_DECREF(zview);
%(fail)s;
}""" % locals()
def infer_shape(self, node, shapes):
return [shapes[0]]
def R_op(self, inputs, eval_points):
if eval_points[0] is None or eval_points[1] is None:
return [None]
# Again we ignore eval points for indices because incsubtensor is
# not differentiable wrt to those
return self(eval_points[0], eval_points[1], *inputs[2:],
**dict(return_list=True))
def connection_pattern(self, node):
rval = [[True], [True]]
for ipt in node.inputs[2:]:
rval.append([False])
return rval
def grad(self, inputs, grads):
g_output, = grads
x, y = inputs[:2]
idx_list = inputs[2:]
if x.dtype in theano.tensor.discrete_dtypes:
# The output dtype is the same as x
gx = x.zeros_like(dtype=theano.config.floatX)
if y.dtype in theano.tensor.discrete_dtypes:
gy = y.zeros_like(dtype=theano.config.floatX)
else:
gy = y.zeros_like()
elif x.dtype in theano.tensor.complex_dtypes:
raise NotImplementedError("No support for complex grad yet")
else:
if self.set_instead_of_inc:
gx = set_subtensor(
Subtensor(idx_list=self.idx_list)(g_output, *idx_list),
theano.tensor.zeros_like(y))
else:
gx = g_output
gy = Subtensor(idx_list=self.idx_list)(g_output, *idx_list)
gy = _sum_grad_over_bcasted_dims(y, gy)
return [gx, gy] + [DisconnectedType()()] * len(idx_list)
def _sum_grad_over_bcasted_dims(x, gx):
"""Sum of gx over dimensions to reproduce x.broadcastable.
This is useful to sum gradients over certain dimensions when
x has been broadcasted, and we need to sum the gradient contributions
over all duplications.
"""
if gx.broadcastable != x.broadcastable:
x_dim_added = gx.ndim - x.ndim
x_broad = (True,) * x_dim_added + x.broadcastable
assert sum(gx.broadcastable) < sum(x_broad)
axis_to_sum = []
for i in xrange(gx.ndim):
if gx.broadcastable[i] is False and x_broad[i] is True:
axis_to_sum.append(i)
elif (gx.broadcastable[i] is True and
x_broad[i] is False):
# This means that Theano was able to infer that
# gx.shape[i] is 1, so x.shape[i] is 1, but we
# didn't know it. It is fine.
pass
else:
assert gx.broadcastable[i] == x_broad[i]
gx = gx.sum(axis=axis_to_sum, keepdims=True)
if gx.ndim != x.ndim:
assert gx.ndim > x.ndim
for i in xrange(x_dim_added):
assert gx.broadcastable[i]
gx = gx.dimshuffle(*list(range(x_dim_added, gx.ndim)))
assert gx.broadcastable == x.broadcastable
return gx
#########################
# Advanced indexing
#########################
#
# Should reproduce numpy's behaviour, see url:
# docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing
class AdvancedSubtensor1(Op):
"""Implement x[ilist] where ilist is a vector of integers."""
# sparse_grad doesn't go in here since it only affects the output
# of the grad() method.
__props__ = ()
_f16_ok = True
def __init__(self, sparse_grad=False):
self.sparse_grad = sparse_grad
def make_node(self, x, ilist):
x_ = theano.tensor.as_tensor_variable(x)
ilist_ = theano.tensor.as_tensor_variable(ilist)
if ilist_.type.dtype[:3] not in ('int', 'uin'):
raise TypeError('index must be integers')
if ilist_.type.ndim != 1:
raise TypeError('index must be vector')
if x_.type.ndim == 0:
raise TypeError('cannot index into a scalar')
bcast = (ilist_.broadcastable[0],) + x_.broadcastable[1:]
return Apply(self, [x_, ilist_], [TensorType(dtype=x.dtype,
broadcastable=bcast)()])
def perform(self, node, inp, out_):
x, i = inp
out, = out_
# Copy always implied by numpy advanced indexing semantic.
if out[0] is not None and out[0].shape == (len(i),) + x.shape[1:]:
o = out[0]
else:
o = None
# If i.dtype is more precise than numpy.intp (int32 on 32-bit machines,
# int64 on 64-bit machines), numpy may raise the following error:
# TypeError: array cannot be safely cast to required type.
# We need to check if values in i can fit in numpy.intp, because
# if they don't, that should be an error (no array can have that
# many elements on a 32-bit arch).
if i.dtype != numpy.intp:
i_ = theano._asarray(i, dtype=numpy.intp)
if not numpy.can_cast(i.dtype, numpy.intp):
# Check if there was actually an incorrect conversion
if numpy.any(i != i_):
raise IndexError(
'index contains values that are bigger '
'than the maximum array size on this system.', i)
i = i_
out[0] = x.take(i, axis=0, out=o)
def connection_pattern(self, node):
rval = [[True]]
for ipt in node.inputs[1:]:
rval.append([False])
return rval
def grad(self, inputs, grads):
global sparse_module_ref
x, ilist = inputs
gz, = grads
assert len(inputs) == 2
if self.sparse_grad:
if x.type.ndim != 2:
raise TypeError(
"AdvancedSubtensor1: you can't take the sparse grad"
" from a tensor with ndim != 2. ndim is " +
str(x.type.ndim))
if sparse_module_ref is None:
import theano.sparse as sparse_module_ref
rval1 = [sparse_module_ref.construct_sparse_from_list(x, gz,
ilist)]
else:
rval1 = [advanced_inc_subtensor1(x.zeros_like(), gz, ilist)]
return rval1 + [DisconnectedType()()] * (len(inputs) - 1)
def R_op(self, inputs, eval_points):
if eval_points[0] is None:
return [None]
return self.make_node(eval_points[0], *inputs[1:]).outputs
def infer_shape(self, node, ishapes):
x, ilist = ishapes
return [ilist + x[1:]]
def c_support_code(self):
# In some versions of numpy, NPY_MIN_INTP is defined as MIN_LONG,
# which is not defined. It should be NPY_MIN_LONG instead in that case.
return dedent("""\
#ifndef MIN_LONG
#define MIN_LONG NPY_MIN_LONG
#endif""")
def c_code(self, node, name, input_names, output_names, sub):
if self.__class__ is not AdvancedSubtensor1:
raise MethodNotDefined(
"c_code defined for AdvancedSubtensor1,"
" not for child class", type(self))
a_name, i_name = input_names[0], input_names[1]
output_name = output_names[0]
fail = sub['fail']
return """
PyArrayObject *indices;
int i_type = PyArray_TYPE(%(i_name)s);
if (i_type != NPY_INTP) {
// Cast %(i_name)s to NPY_INTP (expected by PyArray_TakeFrom),
// if all values fit.
if (!PyArray_CanCastSafely(i_type, NPY_INTP)) {
npy_int64 min_val, max_val;
PyObject* py_min_val = PyArray_Min(%(i_name)s, NPY_MAXDIMS,
NULL);
if (py_min_val == NULL) {
%(fail)s;
}
min_val = PyLong_AsLongLong(py_min_val);
Py_DECREF(py_min_val);
if (min_val == -1 && PyErr_Occurred()) {
%(fail)s;
}
PyObject* py_max_val = PyArray_Max(%(i_name)s, NPY_MAXDIMS,
NULL);
if (py_max_val == NULL) {
%(fail)s;
}
max_val = PyLong_AsLongLong(py_max_val);
Py_DECREF(py_max_val);
if (max_val == -1 && PyErr_Occurred()) {
%(fail)s;
}
if (min_val < NPY_MIN_INTP || max_val > NPY_MAX_INTP) {
PyErr_SetString(PyExc_IndexError,
"Index contains values "
"that are bigger than the maximum array "
"size on this system.");
%(fail)s;
}
}
indices = (PyArrayObject*) PyArray_Cast(%(i_name)s, NPY_INTP);
if (indices == NULL) {
%(fail)s;
}
}
else {
indices = %(i_name)s;
Py_INCREF(indices);
}
if (%(output_name)s != NULL) {
npy_intp nd, i, *shape;
nd = PyArray_NDIM(%(a_name)s) + PyArray_NDIM(indices) - 1;
if (PyArray_NDIM(%(output_name)s) != nd) {
Py_CLEAR(%(output_name)s);
}
else {
shape = PyArray_DIMS(%(output_name)s);
for (i = 0; i < PyArray_NDIM(indices); i++) {
if (shape[i] != PyArray_DIMS(indices)[i]) {
Py_CLEAR(%(output_name)s);
break;
}
}
if (%(output_name)s != NULL) {
for (; i < nd; i++) {
if (shape[i] != PyArray_DIMS(%(a_name)s)[
i-PyArray_NDIM(indices)+1]) {
Py_CLEAR(%(output_name)s);
break;
}
}
}
}
}
%(output_name)s = (PyArrayObject*)PyArray_TakeFrom(
%(a_name)s, (PyObject*)indices, 0, %(output_name)s, NPY_RAISE);
Py_DECREF(indices);
if (%(output_name)s == NULL) %(fail)s;
""" % locals()
def c_code_cache_version(self):
return (0, 1, 1)
advanced_subtensor1 = AdvancedSubtensor1()
class AdvancedIncSubtensor1(Op):
"""Increments a subtensor using advanced slicing (list of index)"""
__props__ = ('inplace', 'set_instead_of_inc')
def __init__(self, inplace=False, set_instead_of_inc=False):
self.inplace = inplace
self.set_instead_of_inc = set_instead_of_inc
if inplace:
self.destroy_map = {0: [0]}
def clone_inplace(self):
return self.__class__(
inplace=True,
set_instead_of_inc=self.set_instead_of_inc)
def __str__(self):
if self.inplace:
msg = "inplace"
else:
msg = "no_inplace"
if self.set_instead_of_inc:
msg += ",set"
else:
msg += ",inc"
return self.__class__.__name__ + "{%s}" % msg
def make_node(self, x, y, ilist):
x_ = theano.tensor.as_tensor_variable(x)
y_ = theano.tensor.as_tensor_variable(y)
ilist_ = theano.tensor.as_tensor_variable(ilist)
if ilist_.type.dtype[:3] not in ('int', 'uin'):
raise TypeError('index must be integers')
if ilist_.type.ndim != 1:
raise TypeError('index must be vector')
if x_.type.ndim == 0:
raise TypeError('cannot index into a scalar')
if y_.type.ndim > x_.type.ndim:
if self.set_instead_of_inc:
opname = 'set'
else:
opname = 'increment'
raise TypeError(
'cannot %s x subtensor with ndim=%s'
' by y with ndim=%s to x subtensor with ndim=%s ' % (
opname, x_.type.ndim, y_.type.ndim))
return Apply(self, [x_, y_, ilist_], [x_.type()])
def copy_of_x(self, x):
"""
:param x: a string giving the name of a C variable
pointing to an array
:return: C code expression to make a copy of x
Base class uses PyArrayObject *, subclasses may override for
different types of arrays.
"""
# Parameters of PyArrary_FromAny are:
# array
# dtype: we pass NULL to say any dtype is acceptable, so the existing
# dtype will be copied
# min_depth: we pass 0 to have this parameter ignored
# max_depth: we pass 0 to have this parameter ignored
# requirements: here we pass NPY_ARRAY_ENSURECOPY to force a copy
# context: this is almost always NULL, I'm not sure what it's used for
return """(PyArrayObject*)PyArray_FromAny(py_%(x)s, NULL, 0, 0,
NPY_ARRAY_ENSURECOPY, NULL)""" % locals()
def c_support_code(self):
from theano.gof.cutils import compile_cutils_code
return compile_cutils_code()
def c_code(self, node, name, input_names, output_names, sub):
numpy_ver = [int(n) for n in numpy.__version__.split('.')[:2]]
if bool(numpy_ver < [1, 8]):
raise NotImplementedError
x, y, idx = input_names
out = output_names[0]
fail = sub['fail']
inc_or_set = 1 - self.set_instead_of_inc
if self.inplace: # convert bool to int
inplace = 1
else:
inplace = 0
copy_of_x = self.copy_of_x(x)
return """
if (%(inplace)s)
{
if (%(x)s != %(out)s)
{
Py_XDECREF(%(out)s);
Py_INCREF(%(x)s);
%(out)s = %(x)s;
}
}
else
{
Py_XDECREF(%(out)s);
%(out)s = %(copy_of_x)s;
}
PyObject *arglist = Py_BuildValue("OOOi",%(out)s, %(idx)s, %(y)s, %(inc_or_set)d);
inplace_increment(NULL, arglist);
Py_XDECREF(arglist);
""" % locals()
def c_code_cache_version(self):
return (1,)
def perform(self, node, inp, out_):
# TODO opt to make this inplace
x, y, idx = inp
out, = out_
if not self.inplace:
x = x.copy()
# In Numpy, x[idx] += y doesn't work if the same index is present
# many times: it does it only once. Is it a bug? In any case, for
# this reason we implement our own 'inc' iteration.
if self.set_instead_of_inc:
x[idx] = y
else:
increment = inplace_increment
if increment is None:
increment = self.inplace_increment1d_slow
increment(x, idx, y)
out[0] = x
def inplace_increment1d_slow(self, x, idx, y):
# If `y` has as many dimensions as `x`, then we want to iterate
# jointly on `x` and `y`. Otherwise, it means `y` should be
# broadcasted to fill all relevant rows of `x`.
assert y.ndim <= x.ndim # Should be guaranteed by `make_node`
if y.ndim == x.ndim:
if len(y) == 1:
# Allow broadcasting of y[0]
y_0 = y[0]
for i in idx:
x[i] += y_0
else:
assert len(y) == len(idx)
j = 0
for i in idx:
x[i] += y[j]
j += 1
else:
for i in idx:
x[i] += y
def infer_shape(self, node, ishapes):
x, y, ilist = ishapes
return [x]
def R_op(self, inputs, eval_points):
if None in eval_points[:2]:
return [None]
return self.make_node(eval_points[0], eval_points[1],
*inputs[2:]).outputs
def connection_pattern(self, node):
rval = [[True], [True], [False]]
return rval
def grad(self, inputs, grads):
g_output, = grads
x, y, idx_list = inputs
if x.dtype in theano.tensor.discrete_dtypes:
# The output dtype is the same as x
gx = x.zeros_like(dtype=theano.config.floatX)
if y.dtype in theano.tensor.discrete_dtypes:
gy = y.zeros_like(dtype=theano.config.floatX)
else:
gy = y.zeros_like()
elif x.dtype in theano.tensor.complex_dtypes:
raise NotImplementedError("No support for complex grad yet")
else:
if self.set_instead_of_inc:
gx = advanced_set_subtensor1(
g_output,
y.zeros_like(),
idx_list)
else:
gx = g_output
gy = advanced_subtensor1(g_output, idx_list)
gy = _sum_grad_over_bcasted_dims(y, gy)
return [gx, gy] + [DisconnectedType()()]
advanced_inc_subtensor1 = AdvancedIncSubtensor1()
advanced_set_subtensor1 = AdvancedIncSubtensor1(set_instead_of_inc=True)
def as_index_variable(idx):
if idx is None:
return NoneConst.clone()
if isinstance(idx, slice):
return make_slice(idx)
if isinstance(idx, gof.Variable) and isinstance(idx.type, SliceType):
return idx
idx = theano.tensor.as_tensor_variable(idx)
if idx.type.dtype[:3] not in ('int', 'uin'):
raise TypeError('index must be integers')
return idx
def adv_index_broadcastable_pattern(a, idx):
"""
This function is only used to determine the broadcast pattern for
AdvancedSubtensor output variable.
For this, we make a fake ndarray and a fake idx and call use ask numpy
the output. From this, we find the output broadcast pattern.
"""
def replace_slice(v):
if isinstance(v, gof.Apply):
if len(v.outputs) != 1:
raise ValueError(
"It is ambiguous which output of a multi-output Op has"
" to be fetched.", v)
else:
v = v.outputs[0]
if NoneConst.equals(v):
return None
if isinstance(v.type, SliceType):
return slice(None, None)
return numpy.zeros((2,) * v.ndim, int)
newidx = tuple(map(replace_slice, idx))
# 2 - True = 1; 2 - False = 2
fakeshape = [2 - bc for bc in a.broadcastable]
retshape = numpy.empty(fakeshape)[newidx].shape
return tuple([dim == 1 for dim in retshape])
class AdvancedSubtensor(Op):
"""Return a subtensor copy, using advanced indexing.
"""
# Should be used by __getitem__ and __getslice__, as follow:
# AdvancedSubtensor()(self, *args),
# if args contains and advanced indexing pattern
__props__ = ()
def make_node(self, x, *index):
x = theano.tensor.as_tensor_variable(x)
index = tuple(map(as_index_variable, index))
bcast = adv_index_broadcastable_pattern(x, index)
return gof.Apply(self,
(x,) + index,
[theano.tensor.tensor(dtype=x.type.dtype,
broadcastable=bcast)])
def R_op(self, inputs, eval_points):
if eval_points[0] is None:
return [None]
return self.make_node(eval_points[0], *inputs[1:]).outputs
def infer_shape(self, node, ishapes):
# Really special case
if len(ishapes) == 3:
xshp, ind1shp, ind2shp = ishapes
if (len(xshp) == 2 and
ind1shp is not None and len(ind1shp) == 1 and
ind2shp is not None and len(ind2shp) == 1):
# if the graph is correct, we can assume ind1shp[0] and
# ind2shp[0] will have the same value.
# Try to return the one closest to the graph input.
if node.inputs[2].owner is None:
return [ind2shp]
else:
return [ind1shp]
# Default case, we don't know
raise theano.tensor.basic.ShapeError("case not implemented")
def perform(self, node, inputs, out_):
out, = out_
# TODO: in general, we need to re-pack the inputs into a valid
# index, just like subtensor
out[0] = inputs[0].__getitem__(inputs[1:])
if (numpy.__version__ <= '1.6.1' and
out[0].size != numpy.uint32(out[0].size)):
warnings.warn(
'Numpy versions 1.6.1 and below have a bug preventing '
'advanced indexing from correctly filling arrays that '
'are too big (>= 2^32 elements). It is possible that '
'out[0] (%s), with shape %s, is not correctly filled.'
% (out[0], out[0].shape))
def connection_pattern(self, node):
rval = [[True]]
for ipt in node.inputs[1:]:
rval.append([False])
return rval
def grad(self, inputs, grads):
gz, = grads
x = inputs[0]
rest = inputs[1:]
return [advanced_inc_subtensor(theano.tensor.zeros_like(x), gz,
*rest)] + \
[DisconnectedType()()] * len(rest)
advanced_subtensor = AdvancedSubtensor()
class AdvancedIncSubtensor(Op):
"""Increments a subtensor using advanced indexing.
:note: We need the numpy.inplace_increment() function currently
numpy's PR 326 to be able to make an inplace version of this
op.
"""
__props__ = ("inplace", "set_instead_of_inc")
def __init__(self, inplace=False, set_instead_of_inc=False):
self.inplace = inplace
self.set_instead_of_inc = set_instead_of_inc
# The assert is needed as in the pass the first argument was
# something else that was not used.
assert isinstance(inplace, bool)
if self.inplace:
raise NotImplementedError('In place computation is not'
' implemented')
self.allow_legacy_perform = False
def __str__(self):
return "%s{%s, %s}" % (self.__class__.__name__,
"inplace=" + str(self.inplace),
" set_instead_of_inc=" +
str(self. set_instead_of_inc))
def make_node(self, x, y, *inputs):
x = theano.tensor.as_tensor_variable(x)
y = theano.tensor.as_tensor_variable(y)
op = self
# If we are incrementing, but the increment compiled function is not
# available, we need to support legacy cases.
if not self.set_instead_of_inc and inplace_increment is None:
legacy_conditions = False
if x.ndim == 2 and y.ndim == 1 and len(inputs) == 2:
ind1 = theano.tensor.as_tensor_variable(inputs[0])
ind2 = theano.tensor.as_tensor_variable(inputs[1])
if ind1.ndim == 1 and ind2.ndim == 1:
if ind1.owner and isinstance(ind1.owner.op, ARange):
legacy_conditions = True
elif isinstance(ind1, Constant):
# Make sure no index is duplicated
val = ind1.value
if numpy.unique(val).size == val.size:
legacy_conditions = True
elif ind2.owner and isinstance(ind2.owner.op, ARange):
legacy_conditions = True
elif isinstance(ind2, Constant):
# Make sure no index is duplicated
val = ind2.value
if numpy.unique(val).size == val.size:
legacy_conditions = True
if legacy_conditions:
op = copy(self)
op.allow_legacy_perform = True
else:
raise NotImplementedError(
'Could not import inplace_increment, so some advanced '
'indexing features are disabled. They will be '
'available if you update NumPy to version 1.8 or '
'later, or to the latest development version. '
'You may need to clear the cache (theano-cache clear) '
'afterwards.')
new_inputs = []
for inp in inputs:
if isinstance(inp, (list, tuple)):
inp = theano.tensor.as_tensor_variable(inp)
new_inputs.append(inp)
return gof.Apply(op,
(x, y) + tuple(new_inputs),
[theano.tensor.tensor(
dtype=x.type.dtype,
broadcastable=x.type.broadcastable)])
def perform(self, node, inputs, out_):
# TODO: 1. opt to make this in place 2. generalize as described in
# AdvancedSubtensor's perform TODO
out, = out_
if not self.inplace:
out[0] = inputs[0].copy()
else:
out[0] = inputs[0]
if self.set_instead_of_inc:
out[0][inputs[2:]] = inputs[1]
elif inplace_increment is not None:
inplace_increment(out[0], tuple(inputs[2:]), inputs[1])
elif self.allow_legacy_perform:
out[0][inputs[2:]] += inputs[1]
else:
raise NotImplementedError(
'Could not import inplace_increment, so some advanced '
'indexing features are disabled. They will be '
'available if you update NumPy to version 1.8 or '
'later, or to the latest development version. '
'You may need to clear the cache (theano-cache clear) '
'afterwards.')
if (numpy.__version__ <= '1.6.1' and
out[0].size != numpy.uint32(out[0].size)):
warnings.warn(
'Numpy versions 1.6.1 and below have a bug preventing '
'advanced indexing from correctly filling arrays that '
'are too big (>= 2^32 elements). It is possible that '
'out[0] (%s), with shape %s, is not correctly filled.'
% (out[0], out[0].shape))
def infer_shape(self, node, ishapes):
return [ishapes[0]]
def connection_pattern(self, node):
rval = [[True], [True]]
for ipt in node.inputs[2:]:
rval.append([False])
return rval
def grad(self, inpt, output_gradients):
x, y = inpt[:2]
idxs = inpt[2:]
outgrad, = output_gradients
if x.dtype in theano.tensor.discrete_dtypes:
# The output dtype is the same as x
gx = x.zeros_like(dtype=theano.config.floatX)
if y.dtype in theano.tensor.discrete_dtypes:
gy = y.zeros_like(dtype=theano.config.floatX)
else:
gy = y.zeros_like()
elif x.dtype in theano.tensor.complex_dtypes:
raise NotImplementedError("No support for complex grad yet")
else:
if self.set_instead_of_inc:
gx = advanced_set_subtensor(
outgrad,
y.zeros_like(),
*idxs)
else:
gx = outgrad
gy = advanced_subtensor(outgrad, *idxs)
# Make sure to sum gy over the dimensions of y that have been
# added or broadcasted
gy = _sum_grad_over_bcasted_dims(y, gy)
return [gx, gy] + \
[DisconnectedType()() for _ in idxs]
def R_op(self, inputs, eval_points):
if None in eval_points[:2]:
return [None]
return self.make_node(eval_points[0], eval_points[1],
*inputs[2:]).outputs
advanced_inc_subtensor = AdvancedIncSubtensor()
advanced_set_subtensor = AdvancedIncSubtensor(set_instead_of_inc=True)
def take(a, indices, axis=None, mode='raise'):
a = theano.tensor.as_tensor_variable(a)
indices = theano.tensor.as_tensor_variable(indices)
# Reuse advanced_subtensor1 if indices is a vector
if indices.ndim == 1:
if mode == 'clip':
indices = clip(indices, 0, a.shape[axis] - 1)
elif mode == 'wrap':
indices = indices % a.shape[axis]
if axis is None:
return advanced_subtensor1(a.flatten(), indices)
elif axis == 0:
return advanced_subtensor1(a, indices)
else:
if axis < 0:
axis += a.ndim
assert axis >= 0
shuffle = list(range(a.ndim))
shuffle[0] = axis
shuffle[axis] = 0
return advanced_subtensor1(
a.dimshuffle(shuffle), indices).dimshuffle(shuffle)
if axis is None:
shape = indices.shape
ndim = indices.ndim
else:
# If axis is 0, don't generate a useless concatenation.
if axis == 0:
shape = theano.tensor.concatenate(
[indices.shape, a.shape[axis + 1:]])
else:
shape = theano.tensor.concatenate(
[a.shape[:axis], indices.shape, a.shape[axis + 1:]])
ndim = a.ndim + indices.ndim - 1
return take(a, indices.flatten(), axis, mode).reshape(shape, ndim)<|fim▁end|> | warnings.warn(
'Although your current code is fine, please note that ' |
<|file_name|>SyntroCFS.cpp<|end_file_name|><|fim▁begin|>//
// Copyright (c) 2014 Scott Ellis and Richard Barnett
//
// This file is part of SyntroNet
//
// SyntroNet 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.
//
// SyntroNet 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.
//<|fim▁hole|>//
#include "CFSClient.h"
#include "SyntroCFS.h"
#include "SyntroCFSDefs.h"
SyntroCFS::SyntroCFS(CFSClient *client, QString filePath)
: m_parent(client), m_filePath(filePath)
{
}
SyntroCFS::~SyntroCFS()
{
}
bool SyntroCFS::cfsOpen(SYNTRO_CFSHEADER *)
{
return true;
}
void SyntroCFS::cfsClose()
{
}
void SyntroCFS::cfsRead(SYNTRO_EHEAD *ehead, SYNTRO_CFSHEADER *cfsMsg, SYNTROCFS_STATE *, unsigned int)
{
SyntroUtils::convertIntToUC2(SYNTROCFS_TYPE_READ_INDEX_RES, cfsMsg->cfsType);
cfsReturnError(ehead, cfsMsg, SYNTROCFS_ERROR_INVALID_REQUEST_TYPE);
}
void SyntroCFS::cfsWrite(SYNTRO_EHEAD *ehead, SYNTRO_CFSHEADER *cfsMsg, SYNTROCFS_STATE *, unsigned int)
{
SyntroUtils::convertIntToUC2(SYNTROCFS_TYPE_WRITE_INDEX_RES, cfsMsg->cfsType);
cfsReturnError(ehead, cfsMsg, SYNTROCFS_ERROR_INVALID_REQUEST_TYPE);
}
void SyntroCFS::cfsQuery(SYNTRO_EHEAD *ehead, SYNTRO_CFSHEADER *cfsMsg)
{
SyntroUtils::convertIntToUC2(SYNTROCFS_TYPE_QUERY_RES, cfsMsg->cfsType);
cfsReturnError(ehead, cfsMsg, SYNTROCFS_ERROR_INVALID_REQUEST_TYPE);
}
void SyntroCFS::cfsCancelQuery(SYNTRO_EHEAD *ehead, SYNTRO_CFSHEADER *cfsMsg)
{
SyntroUtils::convertIntToUC2(SYNTROCFS_TYPE_CANCEL_QUERY_RES, cfsMsg->cfsType);
cfsReturnError(ehead, cfsMsg, SYNTROCFS_ERROR_INVALID_REQUEST_TYPE);
}
void SyntroCFS::cfsFetchQuery(SYNTRO_EHEAD *ehead, SYNTRO_CFSHEADER *cfsMsg)
{
SyntroUtils::convertIntToUC2(SYNTROCFS_TYPE_FETCH_QUERY_RES, cfsMsg->cfsType);
cfsReturnError(ehead, cfsMsg, SYNTROCFS_ERROR_INVALID_REQUEST_TYPE);
}
unsigned int SyntroCFS::cfsGetRecordCount()
{
return 0;
}
SYNTRO_EHEAD *SyntroCFS::cfsBuildResponse(SYNTRO_EHEAD *ehead, int length)
{
SYNTRO_EHEAD *responseE2E = m_parent->clientBuildLocalE2EMessage(m_parent->m_CFSPort,
&(ehead->sourceUID),
SyntroUtils::convertUC2ToUInt(ehead->sourcePort),
sizeof(SYNTRO_CFSHEADER) + length);
SYNTRO_CFSHEADER *responseHdr = (SYNTRO_CFSHEADER *)(responseE2E + 1);
memset(responseHdr, 0, sizeof(SYNTRO_CFSHEADER));
SyntroUtils::convertIntToUC4(length, responseHdr->cfsLength);
return responseE2E;
}
SYNTRO_EHEAD *SyntroCFS::cfsBuildQueryResponse(SYNTRO_EHEAD *ehead, int length)
{
SYNTRO_EHEAD *responseE2E = m_parent->clientBuildLocalE2EMessage(m_parent->m_CFSPort,
&(ehead->sourceUID),
SyntroUtils::convertUC2ToUInt(ehead->sourcePort),
sizeof(SYNTRO_QUERYRESULT_HEADER) + length);
SYNTRO_QUERYRESULT_HEADER *responseHdr = (SYNTRO_QUERYRESULT_HEADER *)(responseE2E + 1);
memset(responseHdr, 0, sizeof(SYNTRO_QUERYRESULT_HEADER));
SyntroUtils::convertIntToUC4(length, responseHdr->cfsHeader.cfsLength);
return responseE2E;
}
void SyntroCFS::cfsReturnError(SYNTRO_EHEAD *ehead, SYNTRO_CFSHEADER *cfsMsg, int responseCode)
{
SyntroUtils::swapEHead(ehead);
SyntroUtils::convertIntToUC4(0, cfsMsg->cfsLength);
SyntroUtils::convertIntToUC2(responseCode, cfsMsg->cfsParam);
#ifdef CFS_THREAD_TRACE
TRACE2("Sent error response to %s, response %d", qPrintable(SyntroUtils::displayUID(&ehead->destUID)),
SyntroUtils::convertUC2ToInt(cfsMsg->cfsParam));
#endif
m_parent->sendMessage(ehead, sizeof(SYNTRO_CFSHEADER));
}<|fim▁end|> | // You should have received a copy of the GNU General Public License
// along with SyntroNet. If not, see <http://www.gnu.org/licenses/>. |
<|file_name|>cursor.rs<|end_file_name|><|fim▁begin|>use super::result::PgResult;
use super::row::PgRow;
/// The type returned by various [`Connection`] methods.
/// Acts as an iterator over `T`.
pub struct Cursor<'a> {
current_row: usize,
db_result: &'a PgResult,
}
impl<'a> Cursor<'a> {
pub(super) fn new(db_result: &'a PgResult) -> Self {
Cursor {
current_row: 0,
db_result,
}
}
}
impl<'a> ExactSizeIterator for Cursor<'a> {
fn len(&self) -> usize {
self.db_result.num_rows() - self.current_row
}
}
impl<'a> Iterator for Cursor<'a> {
type Item = PgRow<'a>;
<|fim▁hole|> fn next(&mut self) -> Option<Self::Item> {
if self.current_row < self.db_result.num_rows() {
let row = self.db_result.get_row(self.current_row);
self.current_row += 1;
Some(row)
} else {
None
}
}
fn nth(&mut self, n: usize) -> Option<Self::Item> {
self.current_row = (self.current_row + n).min(self.db_result.num_rows());
self.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
}<|fim▁end|> | |
<|file_name|>fixsessions.server.controller.js<|end_file_name|><|fim▁begin|>'use strict';
/**
* Module dependencies.
*/
var errorHandler = require('./errors.server.controller'),
db = require('../models/fixsession.server.model'),
_ = require('lodash'),
bluebird = require('bluebird');
/**
* Create a Fixsession
*/
exports.create = function(req, res) {
db.FixSession.create({
name: req.body.name,
assignedFixManager: req.body.assignedFixManager,
assignedTcpManager: req.body.assignedTcpManager,
initiator : req.body.initiator,
host: req.body.host,
port: req.body.port,
username: req.body.username,
password: req.body.password,
defaultRoute: req.body.defaultRoute,
assignedOOBProcessor: req.body.assignedOOBProcessor
}).complete(function(err, results){<|fim▁hole|>};
/**
* List of Fixsessions
*/
exports.list = function(req, res) {
db.FixSession.findAll()
.complete(function(err, results){
res.json(results);
});
};<|fim▁end|> | res.sendStatus(201);
}); |
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>"""
Django settings for sample project.
Generated by 'django-admin startproject' using Django 1.10.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
from warnings import warn
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$^yawh-48g!2@mq5!bfj3pq0r%ld+xyr+zlpm_q@5k(4$ur1v2'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sample_app',
]<|fim▁hole|> 'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'sample_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'sample_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
# FIXME: Testes com um ou multiplos dbs.
DATABASES = {
'default': {
'ENGINE': 'arangodb_driver',
'HOST': 'localhost',
'PORT': '8529',
'NAME': 'teste_python',
'USER': 'root',
'PASSWORD': 'omoomo',
}
}
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': 'defaultbd',
# },
# 'arangodb': {
# 'ENGINE': 'arangodb_driver',
# 'HOST': 'localhost',
# 'PORT': '8529',
# 'NAME': 'teste_python',
# 'USER': 'root',
# 'PASSWORD': 'omoomo',
# }
#
# }
# DATABASE_ROUTERS = ['arangodb_driver.router.GraphRouter']
# ARANGODB: Map model types to database names.
# If not defined, "default" maps to "default".
DB_ROUTES = {'graph': 'arangodb'}
# ARANGODB: The name of the property in the model that defines the type of the model (default: 'model_type').
DB_ROUTES_MODEL_TYPE_PROPERTY = 'model_type' # type: str
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'<|fim▁end|> |
MIDDLEWARE = [ |
<|file_name|>androgui.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
'''Androguard Gui'''
import argparse
import sys
from androguard.core import androconf
from androguard.session import Session
from androguard.gui.mainwindow import MainWindow
from androguard.misc import init_print_colors
from PySide import QtCore, QtGui
from threading import Thread
class IpythonConsole(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
from IPython.terminal.embed import InteractiveShellEmbed
from traitlets.config import Config
cfg = Config()
ipshell = InteractiveShellEmbed(
config=cfg,
banner1="Androguard version %s" % androconf.ANDROGUARD_VERSION)
init_print_colors()
ipshell()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Androguard GUI")
parser.add_argument("-d", "--debug", action="store_true", default=False)
parser.add_argument("-i", "--input_file", default=None)
parser.add_argument("-c", "--console", action="store_true", default=False)<|fim▁hole|>
args = parser.parse_args()
if args.debug:
androconf.set_debug()
# We need that to save huge sessions when leaving and avoid
# RuntimeError: maximum recursion depth exceeded while pickling an object
# or
# RuntimeError: maximum recursion depth exceeded in cmp
# http://stackoverflow.com/questions/2134706/hitting-maximum-recursion-depth-using-pythons-pickle-cpickle
sys.setrecursionlimit(50000)
session = Session(export_ipython=args.console)
console = None
if args.console:
console = IpythonConsole()
console.start()
app = QtGui.QApplication(sys.argv)
window = MainWindow(session=session, input_file=args.input_file)
window.resize(1024, 768)
window.show()
sys.exit(app.exec_())<|fim▁end|> | |
<|file_name|>http.py<|end_file_name|><|fim▁begin|># coding=utf8
from cStringIO import StringIO
import time
import random
from twisted.internet import reactor, task
from twisted.internet.defer import (
inlineCallbacks,
returnValue,
Deferred,
succeed,
)
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.internet.protocol import Protocol
from twisted.names.client import Resolver
from twisted.web import client
from twisted.web.http_headers import Headers
from twisted.web.client import (
HTTPPageGetter,
HTTPClientFactory,
_makeGetterFactory,
)
from observer.utils import wait
from observer.lib import log
class HTTPRESTGetter(HTTPPageGetter):
def handleStatus_304(self):
pass
class HTTPRESTClientFactory(HTTPClientFactory):
protocol = HTTPRESTGetter
def getPage(url, contextFactory=None, *args, **kwargs):
return _makeGetterFactory(
url,
HTTPRESTClientFactory,
contextFactory=contextFactory,
*args, **kwargs).deferred
class HTTPBodyReceiver(Protocol):
def __init__(self, deferred):
self.deferred = deferred
self.body = StringIO()
self.reason = None
def dataReceived(self, data):
self.body.write(data)
def connectionLost(self, reason):
body = self.body.getvalue()
self.reason = reason
self.deferred.callback(body)
def _cbRequest(response):
finished = Deferred()
response.deliverBody(HTTPBodyReceiver(finished))
return finished
def request(agent, url, headers=None, body=None):
log.debug('begin request ' + url)
print agent, agent.request
if body is None:
d = agent.request('GET', str(url), headers)
else:
d = agent.request('POST', str(url), headers,
client.FileBodyProducer(StringIO(body)))
d.addCallback(_cbRequest)
return d
class AdditionalHeaderAgent(object):
"""
An L{Agent} wrapper to add default headers.
@param headers: A list or tuple of (name, value) objects. The name
is which of the HTTP header to set the value for. and the value
is which to set for the named header.
"""
def __init__(self, agent, headers):
self._header_list = headers
self._agent = agent
def request(self, method, uri, headers=None, bodyProducer=None):
if headers is None:
headers = Headers()
else:
headers = headers.copy()
for name, value in self._header_list:
headers.addRawHeader(name, value)
return self._agent.request(method, uri, headers, bodyProducer)
class InfiniteLoginError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.message = message
def __str__(self):
return self[0]
class NoAgentError(Exception):
def __init__(self, message):
Exception.__init__(self, message)
self.message = message
def __str__(self):
return self[0]
class LoginResponse(object):
def __init__(self, response, body, reason):
self.original = response
self.data = body
self.reason = reason
def __getattr__(self, name):
return getattr(self.original, name)
def deliverBody(self, protocol):
protocol.dataReceived(self.data)
protocol.connectionLost(self.reason)
class LoginAgent(object):
def __init__(self, agent, retryLimit=1):
self._agent = agent
self.loggedin = False
self.retryLimit = retryLimit
def login(self):
raise NotImplementedError("Must Implement the login method.")
def testLogin(self, content):
raise NotImplementedError("Must Implement the test login method.")
@inlineCallbacks
def request(self, method, uri, headers=None, bodyProducer=None):
retryCount = 0
while True:
if not self.loggedin:
yield self.login()
retryCount += 1
response = yield self._agent.request(method, uri,
headers, bodyProducer)
finished = Deferred()
p = HTTPBodyReceiver(finished)
response.deliverBody(p)
body = yield finished
reason = p.reason
body = yield self.testLogin(body)
if self.loggedin:
returnValue(LoginResponse(response, body, reason))
return
if bodyProducer is not None:
returnValue(None)
return
if retryCount >= self.retryLimit:
raise InfiniteLoginError("Maximum retry limit reached")
class TimedAgentPool(object):
#FIXME here the float value should be replaced by variables
def __init__(
self,
minTimeInterval=10.0,
maxTimeInterval=15.0,
loginInterval=60.0,
):
self.lastLogin = 0.0
self.agents = []
self.idleAgents = []
self.defers = []
def initAgent(self, agent):
self.agents.append(agent)
self.idleAgents.append(agent)
agent.nextAccess = 0
agent.pool = self
def addAgent(self, agent):
t = random.uniform(self.minTimeInterval,
self.maxTimeInterval)
agent.nextAccess = time.time() + t
if self.defers:
d = self.defers[0]
del self.defers[0]
task.deferLater(reactor, t, d.callback, agent)
else:
self.idleAgents.append(agent)
@inlineCallbacks
def getAgent(self):
if not self.agents:
raise NoAgentError('This pool has no agent yet.')
if not self.idleAgents:
d = Deferred()
self.defers.append(d)
agent = yield d
else:
agent = self.idleAgents[0]
del self.idleAgents[0]
now = time.time()
if now > agent.nextAccess:
returnValue(agent)
else:
yield wait(agent.nextAccess - now)
returnValue(agent)
def removeAgent(self, agent):
self.agents.remove(agent)
class DNSCachingResolver(Resolver):
"""
subclass Resolver to add dns caching mechanism
"""
clear_interval = 1 * 60 * 60
def __init__(self, *args, **kwargs):
Resolver.__init__(self, *args, **kwargs)
self.clear_cache()<|fim▁hole|> self.cached_url = {}
reactor.callLater(self.clear_interval, self.clear_cache)
def update_cache(self, result, name):
self.cached_url[name] = result
return result
def getHostByName(self, name, timeout=None, effort=10):
"""
@see: twisted.names.client.getHostByName
"""
# XXX - respect timeout
if name in self.cached_url:
return succeed(self.cached_url[name])
else:
return self.lookupAllRecords(
name,
timeout,
).addCallback(
self._cbRecords,
name,
effort,
).addCallback(self.update_cache, name)<|fim▁end|> |
def clear_cache(self): |
<|file_name|>perf.go<|end_file_name|><|fim▁begin|>// Copyright © 2014 Terry Mao, LiuDing All rights reserved.
// This file is part of gopush-cluster.
// gopush-cluster 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.
// gopush-cluster 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 gopush-cluster. If not, see <http://www.gnu.org/licenses/>.
package perf
import (
"github.com/golang/glog"
"net/http"
"net/http/pprof"
)
// StartPprof start http pprof.
func Init(pprofBind []string) {
pprofServeMux := http.NewServeMux()
pprofServeMux.HandleFunc("/debug/pprof/", pprof.Index)
pprofServeMux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
pprofServeMux.HandleFunc("/debug/pprof/profile", pprof.Profile)
pprofServeMux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
for _, addr := range pprofBind {
go func() {<|fim▁hole|> glog.Errorf("http.ListenAndServe(\"%s\", pprofServeMux) error(%v)", addr, err)
panic(err)
}
}()
}
}<|fim▁end|> | if err := http.ListenAndServe(addr, pprofServeMux); err != nil { |
<|file_name|>fold-real.cpp<|end_file_name|><|fim▁begin|>//===-- lib/Evaluate/fold-real.cpp ----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "fold-implementation.h"<|fim▁hole|>Expr<Type<TypeCategory::Real, KIND>> FoldIntrinsicFunction(
FoldingContext &context,
FunctionRef<Type<TypeCategory::Real, KIND>> &&funcRef) {
using T = Type<TypeCategory::Real, KIND>;
using ComplexT = Type<TypeCategory::Complex, KIND>;
ActualArguments &args{funcRef.arguments()};
auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
CHECK(intrinsic);
std::string name{intrinsic->name};
if (name == "acos" || name == "acosh" || name == "asin" || name == "asinh" ||
(name == "atan" && args.size() == 1) || name == "atanh" ||
name == "bessel_j0" || name == "bessel_j1" || name == "bessel_y0" ||
name == "bessel_y1" || name == "cos" || name == "cosh" || name == "erf" ||
name == "erfc" || name == "erfc_scaled" || name == "exp" ||
name == "gamma" || name == "log" || name == "log10" ||
name == "log_gamma" || name == "sin" || name == "sinh" ||
name == "sqrt" || name == "tan" || name == "tanh") {
CHECK(args.size() == 1);
if (auto callable{context.hostIntrinsicsLibrary()
.GetHostProcedureWrapper<Scalar, T, T>(name)}) {
return FoldElementalIntrinsic<T, T>(
context, std::move(funcRef), *callable);
} else {
context.messages().Say(
"%s(real(kind=%d)) cannot be folded on host"_en_US, name, KIND);
}
} else if (name == "atan" || name == "atan2" || name == "hypot" ||
name == "mod") {
std::string localName{name == "atan2" ? "atan" : name};
CHECK(args.size() == 2);
if (auto callable{
context.hostIntrinsicsLibrary()
.GetHostProcedureWrapper<Scalar, T, T, T>(localName)}) {
return FoldElementalIntrinsic<T, T, T>(
context, std::move(funcRef), *callable);
} else {
context.messages().Say(
"%s(real(kind=%d), real(kind%d)) cannot be folded on host"_en_US,
name, KIND, KIND);
}
} else if (name == "bessel_jn" || name == "bessel_yn") {
if (args.size() == 2) { // elemental
// runtime functions use int arg
using Int4 = Type<TypeCategory::Integer, 4>;
if (auto callable{
context.hostIntrinsicsLibrary()
.GetHostProcedureWrapper<Scalar, T, Int4, T>(name)}) {
return FoldElementalIntrinsic<T, Int4, T>(
context, std::move(funcRef), *callable);
} else {
context.messages().Say(
"%s(integer(kind=4), real(kind=%d)) cannot be folded on host"_en_US,
name, KIND);
}
}
} else if (name == "abs") {
// Argument can be complex or real
if (auto *x{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
return FoldElementalIntrinsic<T, T>(
context, std::move(funcRef), &Scalar<T>::ABS);
} else if (auto *z{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
if (auto callable{
context.hostIntrinsicsLibrary()
.GetHostProcedureWrapper<Scalar, T, ComplexT>("abs")}) {
return FoldElementalIntrinsic<T, ComplexT>(
context, std::move(funcRef), *callable);
} else {
context.messages().Say(
"abs(complex(kind=%d)) cannot be folded on host"_en_US, KIND);
}
} else {
common::die(" unexpected argument type inside abs");
}
} else if (name == "aimag") {
return FoldElementalIntrinsic<T, ComplexT>(
context, std::move(funcRef), &Scalar<ComplexT>::AIMAG);
} else if (name == "aint" || name == "anint") {
// ANINT rounds ties away from zero, not to even
common::RoundingMode mode{name == "aint"
? common::RoundingMode::ToZero
: common::RoundingMode::TiesAwayFromZero};
return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
ScalarFunc<T, T>([&name, &context, mode](
const Scalar<T> &x) -> Scalar<T> {
ValueWithRealFlags<Scalar<T>> y{x.ToWholeNumber(mode)};
if (y.flags.test(RealFlag::Overflow)) {
context.messages().Say("%s intrinsic folding overflow"_en_US, name);
}
return y.value;
}));
} else if (name == "dprod") {
if (auto scalars{GetScalarConstantArguments<T, T>(context, args)}) {
return Fold(context,
Expr<T>{Multiply<T>{
Expr<T>{std::get<0>(*scalars)}, Expr<T>{std::get<1>(*scalars)}}});
}
} else if (name == "epsilon") {
return Expr<T>{Scalar<T>::EPSILON()};
} else if (name == "huge") {
return Expr<T>{Scalar<T>::HUGE()};
} else if (name == "max") {
return FoldMINorMAX(context, std::move(funcRef), Ordering::Greater);
} else if (name == "merge") {
return FoldMerge<T>(context, std::move(funcRef));
} else if (name == "min") {
return FoldMINorMAX(context, std::move(funcRef), Ordering::Less);
} else if (name == "real") {
if (auto *expr{args[0].value().UnwrapExpr()}) {
return ToReal<KIND>(context, std::move(*expr));
}
} else if (name == "sign") {
return FoldElementalIntrinsic<T, T, T>(
context, std::move(funcRef), &Scalar<T>::SIGN);
} else if (name == "tiny") {
return Expr<T>{Scalar<T>::TINY()};
}
// TODO: cshift, dim, dot_product, eoshift, fraction, matmul,
// maxval, minval, modulo, nearest, norm2, pack, product,
// reduce, rrspacing, scale, set_exponent, spacing, spread,
// sum, transfer, transpose, unpack, bessel_jn (transformational) and
// bessel_yn (transformational)
return Expr<T>{std::move(funcRef)};
}
template <int KIND>
Expr<Type<TypeCategory::Real, KIND>> FoldOperation(
FoldingContext &context, ComplexComponent<KIND> &&x) {
using Operand = Type<TypeCategory::Complex, KIND>;
using Result = Type<TypeCategory::Real, KIND>;
if (auto array{ApplyElementwise(context, x,
std::function<Expr<Result>(Expr<Operand> &&)>{
[=](Expr<Operand> &&operand) {
return Expr<Result>{ComplexComponent<KIND>{
x.isImaginaryPart, std::move(operand)}};
}})}) {
return *array;
}
using Part = Type<TypeCategory::Real, KIND>;
auto &operand{x.left()};
if (auto value{GetScalarConstantValue<Operand>(operand)}) {
if (x.isImaginaryPart) {
return Expr<Part>{Constant<Part>{value->AIMAG()}};
} else {
return Expr<Part>{Constant<Part>{value->REAL()}};
}
}
return Expr<Part>{std::move(x)};
}
FOR_EACH_REAL_KIND(template class ExpressionBase, )
template class ExpressionBase<SomeReal>;
} // namespace Fortran::evaluate<|fim▁end|> |
namespace Fortran::evaluate {
template <int KIND> |
<|file_name|>jspsych-categorize-animation.js<|end_file_name|><|fim▁begin|>/**
* jspsych plugin for categorization trials with feedback and animated stimuli
* Josh de Leeuw
*
* documentation: docs.jspsych.org
**/
jsPsych.plugins["categorize-animation"] = (function() {
var plugin = {};
jsPsych.pluginAPI.registerPreload('categorize-animation', 'stimuli', 'image');
plugin.info = {
name: 'categorize-animation',
description: '',
parameters: {
stimuli: {
type: jsPsych.plugins.parameterType.IMAGE,
pretty_name: 'Stimuli',
default: undefined,
description: 'Array of paths to image files.'
},
key_answer: {
type: jsPsych.plugins.parameterType.KEYCODE,
pretty_name: 'Key answer',
default: undefined,
description: 'The key to indicate correct response'
},
choices: {
type: jsPsych.plugins.parameterType.KEYCODE,
pretty_name: 'Choices',
default: jsPsych.ALL_KEYS,
array: true,
description: 'The keys subject is allowed to press to respond to stimuli.'
},
text_answer: {
type: jsPsych.plugins.parameterType.STRING,
pretty_name: 'Text answer',
default: null,
description: 'Text to describe correct answer.'
},
correct_text: {
type: jsPsych.plugins.parameterType.STRING,
pretty_name: 'Correct text',
default: 'Correct.',
description: 'String to show when subject gives correct answer'
},
incorrect_text: {
type: jsPsych.plugins.parameterType.STRING,
pretty_name: 'Incorrect text',
default: 'Wrong.',
description: 'String to show when subject gives incorrect answer.'
},
frame_time: {
type: jsPsych.plugins.parameterType.INT,
pretty_name: 'Frame time',
default: 500,
description: 'Duration to display each image.'
},
sequence_reps: {
type: jsPsych.plugins.parameterType.INT,
pretty_name: 'Sequence repetitions',
default: 1,
description: 'How many times to display entire sequence.'
},
allow_response_before_complete: {
type: jsPsych.plugins.parameterType.BOOL,
pretty_name: 'Allow response before complete',
default: false,
description: 'If true, subject can response before the animation sequence finishes'
},
feedback_duration: {
type: jsPsych.plugins.parameterType.INT,
pretty_name: 'Feedback duration',
default: 2000,
description: 'How long to show feedback'
},
prompt: {
type: jsPsych.plugins.parameterType.STRING,
pretty_name: 'Prompt',
default: null,
description: 'Any content here will be displayed below the stimulus.'
},
render_on_canvas: {
type: jsPsych.plugins.parameterType.BOOL,
pretty_name: 'Render on canvas',
default: true,
description: 'If true, the images will be drawn onto a canvas element (prevents blank screen between consecutive images in some browsers).'+
'If false, the image will be shown via an img element.'
}
}
}
plugin.trial = function(display_element, trial) {
var animate_frame = -1;
var reps = 0;
var showAnimation = true;
var responded = false;
var timeoutSet = false;
var correct;
if (trial.render_on_canvas) {
// first clear the display element (because the render_on_canvas method appends to display_element instead of overwriting it with .innerHTML)
if (display_element.hasChildNodes()) {
// can't loop through child list because the list will be modified by .removeChild()
while (display_element.firstChild) {
display_element.removeChild(display_element.firstChild);
}
}
var canvas = document.createElement("canvas");
canvas.id = "jspsych-categorize-animation-stimulus";
canvas.style.margin = 0;
canvas.style.padding = 0;
display_element.insertBefore(canvas, null);
var ctx = canvas.getContext("2d");
if (trial.prompt !== null) {
var prompt_div = document.createElement("div");
prompt_div.id = "jspsych-categorize-animation-prompt";
prompt_div.style.visibility = "hidden";
prompt_div.innerHTML = trial.prompt;
display_element.insertBefore(prompt_div, canvas.nextElementSibling);
}
var feedback_div = document.createElement("div");
display_element.insertBefore(feedback_div, display_element.nextElementSibling);
}
// show animation
var animate_interval = setInterval(function() {
if (!trial.render_on_canvas) {
display_element.innerHTML = ''; // clear everything
}
animate_frame++;
if (animate_frame == trial.stimuli.length) {
animate_frame = 0;
reps++;
// check if reps complete //
if (trial.sequence_reps != -1 && reps >= trial.sequence_reps) {
// done with animation
showAnimation = false;
}
}
if (showAnimation) {
if (trial.render_on_canvas) {
display_element.querySelector('#jspsych-categorize-animation-stimulus').style.visibility = 'visible';<|fim▁hole|> img.src = trial.stimuli[animate_frame];
canvas.height = img.naturalHeight;
canvas.width = img.naturalWidth;
ctx.drawImage(img,0,0);
} else {
display_element.innerHTML += '<img src="'+trial.stimuli[animate_frame]+'" class="jspsych-categorize-animation-stimulus"></img>';
}
}
if (!responded && trial.allow_response_before_complete) {
// in here if the user can respond before the animation is done
if (trial.prompt !== null) {
if (trial.render_on_canvas) {
prompt_div.style.visibility = "visible";
} else {
display_element.innerHTML += trial.prompt;
}
}
if (trial.render_on_canvas) {
if (!showAnimation) {
canvas.remove();
}
}
} else if (!responded) {
// in here if the user has to wait to respond until animation is done.
// if this is the case, don't show the prompt until the animation is over.
if (!showAnimation) {
if (trial.prompt !== null) {
if (trial.render_on_canvas) {
prompt_div.style.visibility = "visible";
} else {
display_element.innerHTML += trial.prompt;
}
}
if (trial.render_on_canvas) {
canvas.remove();
}
}
} else {
// user has responded if we get here.
// show feedback
var feedback_text = "";
if (correct) {
feedback_text = trial.correct_text.replace("%ANS%", trial.text_answer);
} else {
feedback_text = trial.incorrect_text.replace("%ANS%", trial.text_answer);
}
if (trial.render_on_canvas) {
if (trial.prompt !== null) {
prompt_div.remove();
}
feedback_div.innerHTML = feedback_text;
} else {
display_element.innerHTML += feedback_text;
}
// set timeout to clear feedback
if (!timeoutSet) {
timeoutSet = true;
jsPsych.pluginAPI.setTimeout(function() {
endTrial();
}, trial.feedback_duration);
}
}
}, trial.frame_time);
var keyboard_listener;
var trial_data = {};
var after_response = function(info) {
// ignore the response if animation is playing and subject
// not allowed to respond before it is complete
if (!trial.allow_response_before_complete && showAnimation) {
return false;
}
correct = false;
if (trial.key_answer == info.key) {
correct = true;
}
responded = true;
trial_data = {
"stimulus": JSON.stringify(trial.stimuli),
"rt": info.rt,
"correct": correct,
"key_press": info.key
};
jsPsych.pluginAPI.cancelKeyboardResponse(keyboard_listener);
}
keyboard_listener = jsPsych.pluginAPI.getKeyboardResponse({
callback_function: after_response,
valid_responses: trial.choices,
rt_method: 'performance',
persist: true,
allow_held_key: false
});
function endTrial() {
clearInterval(animate_interval); // stop animation!
display_element.innerHTML = ''; // clear everything
jsPsych.finishTrial(trial_data);
}
};
return plugin;
})();<|fim▁end|> | var img = new Image(); |
<|file_name|>0003_redirection.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-01-10 22:43<|fim▁hole|>from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dns', '0002_auto_20151228_0134'),
]
operations = [
migrations.CreateModel(
name='Redirection',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('abbr', models.CharField(max_length=100, unique=True)),
('target', models.URLField()),
],
),
]<|fim▁end|> | from __future__ import unicode_literals
|
<|file_name|>BindingCustom.java<|end_file_name|><|fim▁begin|>package ahmad.aghazadeh.recyclerviewcardview.logic;
import android.databinding.BindingAdapter;
import android.databinding.BindingConversion;
import android.graphics.Bitmap;
import android.graphics.Typeface;<|fim▁hole|>import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.graphics.Palette;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
/**
* Created by 890683 on 1/10/2016.
*/
public class BindingCustom {
@BindingAdapter("fontName")
public static void setFontName(TextView view, @Nullable String fontName) {
String fontPath = "/fonts/" + fontName;
view.setTypeface(Project.getTypeFace(view.getContext(),fontPath));
}
@BindingAdapter({"imageUrl", "error", "paletteResId"})
public static void loadImage(final ImageView view, String url, @Nullable Drawable error, @Nullable final int paletteResId) {
com.squareup.picasso.Callback callback = new Callback() {
@Override
public void onSuccess() {
Bitmap photo = Project.drawableToBitmap(view.getDrawable());
Palette.generateAsync(photo, new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
int mutedLight = palette.getMutedColor(view.getContext().getResources().getColor(android.R.color.white));
View paletteLayout = (view.getRootView()).findViewById(paletteResId);
if(paletteLayout!=null){
paletteLayout.setBackgroundColor(mutedLight);
}
}
});
}
@Override
public void onError() {
}
};
Picasso.with(view.getContext()).load(url).error(error).into(view, callback);
}
}<|fim▁end|> | import android.graphics.drawable.ColorDrawable; |
<|file_name|>httpclient.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# coding: utf-8
"""阻塞和非阻塞的 HTTP 客户端接口.
这个模块定义了一个被两种实现方式 ``simple_httpclient`` 和
``curl_httpclient`` 共享的通用接口 . 应用程序可以选择直接实例化相对应的实现类,
或使用本模块提供的 `AsyncHTTPClient` 类, 通过复写
`AsyncHTTPClient.configure` 方法来选择一种实现 .
默认的实现是 ``simple_httpclient``, 这可以能满足大多数用户的需要 . 然而, 一
些应用程序可能会因为以下原因想切换到 ``curl_httpclient`` :
* ``curl_httpclient`` 有一些 ``simple_httpclient`` 不具有的功能特性,
包括对 HTTP 代理和使用指定网络接口能力的支持.
* ``curl_httpclient`` 更有可能与不完全符合 HTTP 规范的网站兼容, 或者与
使用很少使用 HTTP 特性的网站兼容.
* ``curl_httpclient`` 更快.
* ``curl_httpclient`` 是 Tornado 2.0 之前的默认值.
注意, 如果你正在使用 ``curl_httpclient``, 强力建议你使用最新版本的
``libcurl`` 和 ``pycurl``. 当前 libcurl 能被支持的最小版本是
7.21.1, pycurl 能被支持的最小版本是 7.18.2. 强烈建议你所安装的 ``libcurl``
是和异步 DNS 解析器 (threaded 或 c-ares) 一起构建的,
否则你可能会遇到各种请求超时的问题 (更多信息请查看
http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTCONNECTTIMEOUTMS
和 curl_httpclient.py 里面的注释).
为了选择 ``curl_httpclient``, 只需要在启动的时候调用
`AsyncHTTPClient.configure` ::
AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
"""
from __future__ import absolute_import, division, print_function, with_statement
import functools
import time
import weakref
from tornado.concurrent import TracebackFuture
from tornado.escape import utf8, native_str
from tornado import httputil, stack_context
from tornado.ioloop import IOLoop
from tornado.util import Configurable
class HTTPClient(object):
"""一个阻塞的 HTTP 客户端.
提供这个接口是为了方便使用和测试; 大多数运行于 IOLoop 的应用程序
会使用 `AsyncHTTPClient` 来替代它.
一般的用法就像这样 ::
http_client = httpclient.HTTPClient()
try:
response = http_client.fetch("http://www.google.com/")
print response.body
except httpclient.HTTPError as e:
# HTTPError is raised for non-200 responses; the response
# can be found in e.response.
print("Error: " + str(e))
except Exception as e:
# Other errors are possible, such as IOError.
print("Error: " + str(e))
http_client.close()
"""
def __init__(self, async_client_class=None, **kwargs):
self._io_loop = IOLoop(make_current=False)
if async_client_class is None:<|fim▁hole|> self._closed = False
def __del__(self):
self.close()
def close(self):
"""关闭该 HTTPClient, 释放所有使用的资源."""
if not self._closed:
self._async_client.close()
self._io_loop.close()
self._closed = True
def fetch(self, request, **kwargs):
"""执行一个请求, 返回一个 `HTTPResponse` 对象.
该请求可以是一个 URL 字符串或是一个 `HTTPRequest` 对象.
如果它是一个字符串, 我们会使用任意关键字参数构造一个
`HTTPRequest` : ``HTTPRequest(request, **kwargs)``
如果在 fetch 过程中发生错误, 我们将抛出一个 `HTTPError` 除非
``raise_error`` 关键字参数被设置为 False.
"""
response = self._io_loop.run_sync(functools.partial(
self._async_client.fetch, request, **kwargs))
return response
class AsyncHTTPClient(Configurable):
"""一个非阻塞 HTTP 客户端.
使用示例::
def handle_request(response):
if response.error:
print "Error:", response.error
else:
print response.body
http_client = AsyncHTTPClient()
http_client.fetch("http://www.google.com/", handle_request)
这个类的构造器有几个比较神奇的考虑: 它实际创建了一个基于特定实现的子
类的实例, 并且该实例被作为一种伪单例重用 (每一个 `.IOLoop` ).
使用关键字参数 ``force_instance=True`` 可以用来限制这种单例行为.
只有使用了 ``force_instance=True`` 时候, 才可以传递 ``io_loop`` 以外其他
的参数给 `AsyncHTTPClient` 构造器.
实现的子类以及它的构造器的参数可以通过静态方法 `configure()` 设置.
所有 `AsyncHTTPClient` 实现都支持一个 ``defaults`` 关键字参数,
可以被用来设置默认 `HTTPRequest` 属性的值. 例如::
AsyncHTTPClient.configure(
None, defaults=dict(user_agent="MyUserAgent"))
# or with force_instance:
client = AsyncHTTPClient(force_instance=True,
defaults=dict(user_agent="MyUserAgent"))
.. versionchanged:: 4.1
``io_loop`` 参数被废弃.
"""
@classmethod
def configurable_base(cls):
return AsyncHTTPClient
@classmethod
def configurable_default(cls):
from tornado.simple_httpclient import SimpleAsyncHTTPClient
return SimpleAsyncHTTPClient
@classmethod
def _async_clients(cls):
attr_name = '_async_client_dict_' + cls.__name__
if not hasattr(cls, attr_name):
setattr(cls, attr_name, weakref.WeakKeyDictionary())
return getattr(cls, attr_name)
def __new__(cls, io_loop=None, force_instance=False, **kwargs):
io_loop = io_loop or IOLoop.current()
if force_instance:
instance_cache = None
else:
instance_cache = cls._async_clients()
if instance_cache is not None and io_loop in instance_cache:
return instance_cache[io_loop]
instance = super(AsyncHTTPClient, cls).__new__(cls, io_loop=io_loop,
**kwargs)
# Make sure the instance knows which cache to remove itself from.
# It can't simply call _async_clients() because we may be in
# __new__(AsyncHTTPClient) but instance.__class__ may be
# SimpleAsyncHTTPClient.
instance._instance_cache = instance_cache
if instance_cache is not None:
instance_cache[instance.io_loop] = instance
return instance
def initialize(self, io_loop, defaults=None):
self.io_loop = io_loop
self.defaults = dict(HTTPRequest._DEFAULTS)
if defaults is not None:
self.defaults.update(defaults)
self._closed = False
def close(self):
"""销毁该 HTTP 客户端, 释放所有被使用的文件描述符.
因为 `AsyncHTTPClient` 对象透明重用的方式, 该方法
**在正常使用时并不需要** .
``close()`` 一般只有在 `.IOLoop` 也被关闭, 或在创建
`AsyncHTTPClient` 的时候使用了 ``force_instance=True`` 参数才需要.
在 `AsyncHTTPClient` 调用 ``close()`` 方法后, 其他方法就不能被调用
了.
"""
if self._closed:
return
self._closed = True
if self._instance_cache is not None:
if self._instance_cache.get(self.io_loop) is not self:
raise RuntimeError("inconsistent AsyncHTTPClient cache")
del self._instance_cache[self.io_loop]
def fetch(self, request, callback=None, raise_error=True, **kwargs):
"""执行一个请求, 并且异步的返回 `HTTPResponse`.
request 参数可以是一个 URL 字符串也可以是一个 `HTTPRequest` 对象.
如果是一个字符串, 我们将使用全部的关键字参数一起构造一个
`HTTPRequest` 对象: ``HTTPRequest(request, **kwargs)``
这个方法返回一个结果为 `HTTPResponse` 的 `.Future` 对象.
默认情况下, 如果该请求返回一个非 200 的响应码, 这个 ``Future``
将会抛出一个 `HTTPError` 错误. 相反, 如果 ``raise_error`` 设置为
False, 则无论响应码如何, 都将返回该 response (响应).
如果给定了 ``callback`` , 它将被 `HTTPResponse` 调用.
在回调接口中, `HTTPError` 不会自动抛出. 相反你必须检查该响应的
``error`` 属性或者调用它的 `~HTTPResponse.rethrow` 方法.
"""
if self._closed:
raise RuntimeError("fetch() called on closed AsyncHTTPClient")
if not isinstance(request, HTTPRequest):
request = HTTPRequest(url=request, **kwargs)
# We may modify this (to add Host, Accept-Encoding, etc),
# so make sure we don't modify the caller's object. This is also
# where normal dicts get converted to HTTPHeaders objects.
request.headers = httputil.HTTPHeaders(request.headers)
request = _RequestProxy(request, self.defaults)
future = TracebackFuture()
if callback is not None:
callback = stack_context.wrap(callback)
def handle_future(future):
exc = future.exception()
if isinstance(exc, HTTPError) and exc.response is not None:
response = exc.response
elif exc is not None:
response = HTTPResponse(
request, 599, error=exc,
request_time=time.time() - request.start_time)
else:
response = future.result()
self.io_loop.add_callback(callback, response)
future.add_done_callback(handle_future)
def handle_response(response):
if raise_error and response.error:
future.set_exception(response.error)
else:
future.set_result(response)
self.fetch_impl(request, handle_response)
return future
def fetch_impl(self, request, callback):
raise NotImplementedError()
@classmethod
def configure(cls, impl, **kwargs):
"""配置要使用的 `AsyncHTTPClient` 子类.
``AsyncHTTPClient()`` 实际上是创建一个子类的实例.
此方法可以使用一个类对象或此类的完全限定名称(或为 ``None`` 则使用默认的,
``SimpleAsyncHTTPClient``) 调用.
如果给定了额外的关键字参数, 它们将会被传递给创建的每个子类实例的
构造函数. 关键字参数 ``max_clients`` 确定了可以在每个 `.IOLoop` 上
并行执行的 `~AsyncHTTPClient.fetch()` 操作的最大数量. 根据使用的
实现类不同, 可能支持其他参数.
例如::
AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
"""
super(AsyncHTTPClient, cls).configure(impl, **kwargs)
class HTTPRequest(object):
"""HTTP 客户端请求对象."""
# Default values for HTTPRequest parameters.
# Merged with the values on the request object by AsyncHTTPClient
# implementations.
_DEFAULTS = dict(
connect_timeout=20.0,
request_timeout=20.0,
follow_redirects=True,
max_redirects=5,
decompress_response=True,
proxy_password='',
allow_nonstandard_methods=False,
validate_cert=True)
def __init__(self, url, method="GET", headers=None, body=None,
auth_username=None, auth_password=None, auth_mode=None,
connect_timeout=None, request_timeout=None,
if_modified_since=None, follow_redirects=None,
max_redirects=None, user_agent=None, use_gzip=None,
network_interface=None, streaming_callback=None,
header_callback=None, prepare_curl_callback=None,
proxy_host=None, proxy_port=None, proxy_username=None,
proxy_password=None, allow_nonstandard_methods=None,
validate_cert=None, ca_certs=None,
allow_ipv6=None,
client_key=None, client_cert=None, body_producer=None,
expect_100_continue=False, decompress_response=None,
ssl_options=None):
r"""除了 ``url`` 以外所有参数都是可选的.
:arg string url: fetch 的 URL
:arg string method: HTTP 方法, e.g. "GET" or "POST"
:arg headers: 额外的 HTTP 请求头
:type headers: `~tornado.httputil.HTTPHeaders` 或 `dict`
:arg body: HTTP 请求体字符串 (byte 或 unicode; 如果是 unicode
则使用 utf-8 编码)
:arg body_producer: 可以被用于延迟/异步请求体调用.
它可以被调用, 带有一个参数, 一个 ``write`` 函数, 并应该
返回一个 `.Future` 对象. 它应该在新的数据可用时调用 write 函数.
write 函数返回一个可用于流程控制的 `.Future` 对象.
只能指定 ``body`` 和 ``body_producer`` 其中之一.
``body_producer`` 不被 ``curl_httpclient`` 支持.
当使用 ``body_producer`` 时, 建议传递一个
``Content-Length`` 头, 否则将使用其他的分块编码,
并且很多服务断不支持请求的分块编码. Tornado 4.0 新增
:arg string auth_username: HTTP 认证的用户名
:arg string auth_password: HTTP 认证的密码
:arg string auth_mode: 认证模式; 默认是 "basic".
所允许的值是根据实现方式定义的; ``curl_httpclient``
支持 "basic" 和 "digest"; ``simple_httpclient`` 只支持 "basic"
:arg float connect_timeout: 初始化连接的超时时间
:arg float request_timeout: 整个请求的超时时间
:arg if_modified_since: ``If-Modified-Since`` 头的时间戳
:type if_modified_since: `datetime` 或 `float`
:arg bool follow_redirects: 是否应该自动跟随重定向还是返回 3xx 响应?
:arg int max_redirects: ``follow_redirects`` 的最大次数限制
:arg string user_agent: ``User-Agent`` 头
:arg bool decompress_response: 从服务器请求一个压缩过的响应, 在下载
后对其解压缩. 默认是 True.
Tornado 4.0 新增.
:arg bool use_gzip: ``decompress_response`` 的别名从 Tornado 4.0 已弃用.
:arg string network_interface: 请求所使用的网络接口.
只有 ``curl_httpclient`` ; 请看下面的备注.
:arg callable streaming_callback: 如果设置了, ``streaming_callback`` 将
用它接收到的数据块执行, 并且
``HTTPResponse.body`` 和 ``HTTPResponse.buffer`` 在最后的响应中将为空.
:arg callable header_callback: 如果设置了, ``header_callback`` 将
在接收到每行头信息时运行(包括第一行, e.g. ``HTTP/1.0 200 OK\r\n``,
最后一行只包含 ``\r\n``. 所有行都包含结尾的换行符).
``HTTPResponse.headers`` 在最终响应中将为空. 这与
``streaming_callback`` 结合是最有用的, 因为它是在请求正在进行时
访问头信息唯一的方法.
:arg callable prepare_curl_callback: 如果设置, 将使用
``pycurl.Curl`` 对象调用, 以允许应用程序进行额外的
``setopt`` 调用.
:arg string proxy_host: HTTP 代理主机名. 如果想要使用代理,
``proxy_host`` 和 ``proxy_port`` 必须设置; ``proxy_username`` 和
``proxy_pass`` 是可选项. 目前只有 ``curl_httpclient`` 支持代理.
:arg int proxy_port: HTTP 代理端口
:arg string proxy_username: HTTP 代理用户名
:arg string proxy_password: HTTP 代理密码
:arg bool allow_nonstandard_methods: 允许 ``method`` 参数使用未知值?
:arg bool validate_cert: 对于 HTTPS 请求, 是否验证服务器的证书?
:arg string ca_certs: PEM 格式的 CA 证书的文件名, 或者默认为 None.
当与 ``curl_httpclient`` 一起使用时参阅下面的注释.
:arg string client_key: 客户端 SSL key 文件名(如果有).
当与 ``curl_httpclient`` 一起使用时参阅下面的注释.
:arg string client_cert: 客户端 SSL 证书的文件名(如果有).
当与 ``curl_httpclient`` 一起使用时参阅下面的注释.
:arg ssl.SSLContext ssl_options: 用在
``simple_httpclient`` (``curl_httpclient`` 不支持) 的
`ssl.SSLContext` 对象.
覆写 ``validate_cert``, ``ca_certs``, ``client_key``,
和 ``client_cert``.
:arg bool allow_ipv6: 当 IPv6 可用时是否使用? 默认是 true.
:arg bool expect_100_continue: 如果为 true, 发送
``Expect: 100-continue`` 头并在发送请求体前等待继续响应.
只被 simple_httpclient 支持.
.. 注意::
当使用 ``curl_httpclient`` 时, 某些选项可能会被后续获取
的继承, 因为 ``pycurl`` 不允许它们被彻底重置. 这适用于
``ca_certs``, ``client_key``, ``client_cert``, 和
``network_interface`` 参数. 如果你使用这些参数, 你应该在
每次请求中都传递它们(你不必总使用相同的值, 但不能混合
指定了这些参数和使用默认参数的请求).
.. versionadded:: 3.1
``auth_mode`` 参数.
.. versionadded:: 4.0
``body_producer`` 和 ``expect_100_continue`` 参数.
.. versionadded:: 4.2
``ssl_options`` 参数.
"""
# Note that some of these attributes go through property setters
# defined below.
self.headers = headers
if if_modified_since:
self.headers["If-Modified-Since"] = httputil.format_timestamp(
if_modified_since)
self.proxy_host = proxy_host
self.proxy_port = proxy_port
self.proxy_username = proxy_username
self.proxy_password = proxy_password
self.url = url
self.method = method
self.body = body
self.body_producer = body_producer
self.auth_username = auth_username
self.auth_password = auth_password
self.auth_mode = auth_mode
self.connect_timeout = connect_timeout
self.request_timeout = request_timeout
self.follow_redirects = follow_redirects
self.max_redirects = max_redirects
self.user_agent = user_agent
if decompress_response is not None:
self.decompress_response = decompress_response
else:
self.decompress_response = use_gzip
self.network_interface = network_interface
self.streaming_callback = streaming_callback
self.header_callback = header_callback
self.prepare_curl_callback = prepare_curl_callback
self.allow_nonstandard_methods = allow_nonstandard_methods
self.validate_cert = validate_cert
self.ca_certs = ca_certs
self.allow_ipv6 = allow_ipv6
self.client_key = client_key
self.client_cert = client_cert
self.ssl_options = ssl_options
self.expect_100_continue = expect_100_continue
self.start_time = time.time()
@property
def headers(self):
return self._headers
@headers.setter
def headers(self, value):
if value is None:
self._headers = httputil.HTTPHeaders()
else:
self._headers = value
@property
def body(self):
return self._body
@body.setter
def body(self, value):
self._body = utf8(value)
@property
def body_producer(self):
return self._body_producer
@body_producer.setter
def body_producer(self, value):
self._body_producer = stack_context.wrap(value)
@property
def streaming_callback(self):
return self._streaming_callback
@streaming_callback.setter
def streaming_callback(self, value):
self._streaming_callback = stack_context.wrap(value)
@property
def header_callback(self):
return self._header_callback
@header_callback.setter
def header_callback(self, value):
self._header_callback = stack_context.wrap(value)
@property
def prepare_curl_callback(self):
return self._prepare_curl_callback
@prepare_curl_callback.setter
def prepare_curl_callback(self, value):
self._prepare_curl_callback = stack_context.wrap(value)
class HTTPResponse(object):
"""HTTP 响应对象.
属性:
* request: HTTPRequest 对象
* code: HTTP 状态码数值, e.g. 200 或 404
* reason: 人类可读的, 对状态码原因的简短描述
* headers: `tornado.httputil.HTTPHeaders` 对象
* effective_url: 跟随重定向后资源的最后位置
* buffer: 响应体的 ``cStringIO`` 对象
* body: string 化的响应体 (从 ``self.buffer`` 的需求创建)
* error: 任何异常对象
* request_time: 请求开始到结束的时间(秒)
* time_info: 来自请求的诊断时间信息的字典.
可用数据可能会更改, 不过当前在用的时间信息是
http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html,
加上 ``queue``, 这是通过等待在 `AsyncHTTPClient` 的 ``max_clients``
设置下的插槽引入的延迟(如果有的话).
"""
def __init__(self, request, code, headers=None, buffer=None,
effective_url=None, error=None, request_time=None,
time_info=None, reason=None):
if isinstance(request, _RequestProxy):
self.request = request.request
else:
self.request = request
self.code = code
self.reason = reason or httputil.responses.get(code, "Unknown")
if headers is not None:
self.headers = headers
else:
self.headers = httputil.HTTPHeaders()
self.buffer = buffer
self._body = None
if effective_url is None:
self.effective_url = request.url
else:
self.effective_url = effective_url
if error is None:
if self.code < 200 or self.code >= 300:
self.error = HTTPError(self.code, message=self.reason,
response=self)
else:
self.error = None
else:
self.error = error
self.request_time = request_time
self.time_info = time_info or {}
def _get_body(self):
if self.buffer is None:
return None
elif self._body is None:
self._body = self.buffer.getvalue()
return self._body
body = property(_get_body)
def rethrow(self):
"""如果请求中有错误发生, 将抛出一个 `HTTPError`."""
if self.error:
raise self.error
def __repr__(self):
args = ",".join("%s=%r" % i for i in sorted(self.__dict__.items()))
return "%s(%s)" % (self.__class__.__name__, args)
class HTTPError(Exception):
"""一个 HTTP 请求失败后抛出的异常.
属性:
* ``code`` - 整数的 HTTP 错误码, e.g. 404. 当没有接收到 HTTP 响应时
将会使用 599 错误码, e.g. 超时.
* ``response`` - 全部的 `HTTPResponse` 对象.
注意如果 ``follow_redirects`` 为 False, 重定向将导致 HTTPErrors,
并且你可以通过 ``error.response.headers['Location']`` 查看重定向的
描述.
"""
def __init__(self, code, message=None, response=None):
self.code = code
self.message = message or httputil.responses.get(code, "Unknown")
self.response = response
super(HTTPError, self).__init__(code, message, response)
def __str__(self):
return "HTTP %d: %s" % (self.code, self.message)
class _RequestProxy(object):
"""将对象和默认字典相结合.
本质上是被 AsyncHTTPClient 的实现使用.
"""
def __init__(self, request, defaults):
self.request = request
self.defaults = defaults
def __getattr__(self, name):
request_attr = getattr(self.request, name)
if request_attr is not None:
return request_attr
elif self.defaults is not None:
return self.defaults.get(name, None)
else:
return None
def main():
from tornado.options import define, options, parse_command_line
define("print_headers", type=bool, default=False)
define("print_body", type=bool, default=True)
define("follow_redirects", type=bool, default=True)
define("validate_cert", type=bool, default=True)
args = parse_command_line()
client = HTTPClient()
for arg in args:
try:
response = client.fetch(arg,
follow_redirects=options.follow_redirects,
validate_cert=options.validate_cert,
)
except HTTPError as e:
if e.response is not None:
response = e.response
else:
raise
if options.print_headers:
print(response.headers)
if options.print_body:
print(native_str(response.body))
client.close()
if __name__ == "__main__":
main()<|fim▁end|> | async_client_class = AsyncHTTPClient
self._async_client = async_client_class(self._io_loop, **kwargs) |
<|file_name|>authentication.component.ts<|end_file_name|><|fim▁begin|>import { Component } from "@angular/core";
@Component({
selector: 'app-authentication',<|fim▁hole|> <header class="row spacing">
<nav class="col-md-8 col-md-offset-2">
<ul class="nav nav-tabs">
<li routerLinkActive="active"><a [routerLink]="['signup']">Signup</a></li>
<li routerLinkActive="active"><a [routerLink]="['signin']">Signin</a></li>
<li routerLinkActive="active"><a [routerLink]="['logout']">Logout</a></li>
</ul>
</nav>
</header>
<div class="row spacing">
<router-outlet></router-outlet>
</div>
`
})
export class AuthenticationComponent {
}<|fim▁end|> | template: ` |
<|file_name|>text.py<|end_file_name|><|fim▁begin|><|fim▁hole|>def standard_text_from_block(block, offset, max_length):
str = ''
for i in range(offset, offset + max_length):
c = block[i]
if c == 0:
return str
else:
str += chr(c - 0x30)
return str
def standard_text_to_byte_list(text, max_length):
# First, substitute all of the characters
if CharacterSubstitutions.character_substitutions:
for k, v in CharacterSubstitutions.character_substitutions.items():
text = text.replace(k, v)
byte_list = []
text_pos = 0
while text_pos < len(text):
c = text[text_pos]
if c == '[':
end_bracket_pos = text.find(']', text_pos)
if end_bracket_pos == -1:
raise ValueError("String contains '[' at position {} but no subsequent ']': {}".format(
text_pos, text
))
bracket_bytes = text[text_pos+1:end_bracket_pos].split()
for bracket_byte in bracket_bytes:
if len(bracket_byte) != 2:
raise ValueError("String contains invalid hex number '{}', must be two digits: {}".format(
bracket_byte, text
))
try:
bracket_byte_value = int(bracket_byte, 16)
except ValueError as e:
raise ValueError("String contains invalid hex number '{}': {}".format(
bracket_byte, text
), e)
byte_list.append(bracket_byte_value)
text_pos = end_bracket_pos + 1
else:
byte_list.append(ord(c) + 0x30)
text_pos += 1
num_bytes = len(byte_list)
if num_bytes > max_length:
raise ValueError("String cannot be written in {} bytes or less: {}".format(
max_length, text
))
elif num_bytes < max_length:
byte_list.append(0)
return byte_list
def standard_text_to_block(block, offset, text, max_length):
byte_list = standard_text_to_byte_list(text, max_length)
block[offset:offset+len(byte_list)] = byte_list<|fim▁end|> | class CharacterSubstitutions(object):
character_substitutions = dict()
|
<|file_name|>test_beadstructure_base.cc<|end_file_name|><|fim▁begin|>/*
* Copyright 2009-2021 The VOTCA Development Team (http://www.votca.org)
*
* 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.
*
*/
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE beadstructure_test
// Standard includes
#include <stdexcept>
// Third party includes
#include <boost/test/unit_test.hpp>
// VOTCA includes
#include <votca/tools/types.h>
// Local VOTCA includes
#include "votca/csg/basebead.h"
#include "votca/csg/beadstructure.h" // IWYU pragma: keep
using namespace std;
using namespace votca::csg;
using namespace votca::tools;
class TestBead : public BaseBead {
public:
TestBead() : BaseBead(){};
};
BOOST_AUTO_TEST_SUITE(beadstructure_test)
BOOST_AUTO_TEST_CASE(test_beadstructure_constructor) {
BeadStructure beadstructure;
}
BOOST_AUTO_TEST_CASE(test_beadstructure_beadcount) {
BeadStructure beadstructure;
BOOST_CHECK_EQUAL(beadstructure.BeadCount(), 0);
}
BOOST_AUTO_TEST_CASE(test_beadstructure_add_and_getbead) {
BeadStructure beadstructure;
TestBead testbead;
testbead.setId(2);
testbead.setName("Carbon");
beadstructure.AddBead(testbead);
BOOST_CHECK_EQUAL(beadstructure.BeadCount(), 1);
BOOST_CHECK(beadstructure.BeadExist(2));
}
BOOST_AUTO_TEST_CASE(test_beadstructure_ConnectBeads) {
BeadStructure beadstructure;
TestBead testbead1;
testbead1.setId(1);
testbead1.setName("Carbon");
TestBead testbead2;
testbead2.setId(2);
testbead2.setName("Carbon");
beadstructure.AddBead(testbead1);
beadstructure.AddBead(testbead2);
beadstructure.ConnectBeads(1, 2);
}
BOOST_AUTO_TEST_CASE(test_beadstructure_getBeadIds) {
BeadStructure beadstructure;
TestBead testbead1;
testbead1.setId(1);
testbead1.setName("Carbon");
TestBead testbead2;
testbead2.setId(2);
testbead2.setName("Carbon");
beadstructure.AddBead(testbead1);
beadstructure.AddBead(testbead2);
vector<votca::Index> bead_ids = beadstructure.getBeadIds();
BOOST_CHECK_EQUAL(bead_ids.size(), 2);
sort(bead_ids.begin(), bead_ids.end());
BOOST_CHECK_EQUAL(bead_ids.at(0), 1);
BOOST_CHECK_EQUAL(bead_ids.at(1), 2);
}
BOOST_AUTO_TEST_CASE(test_beadstructure_getSubStructure) {
BeadStructure beadstructure;
TestBead testbead1;
testbead1.setId(1);
testbead1.setName("Carbon");
TestBead testbead2;
testbead2.setId(2);
testbead2.setName("Carbon");
TestBead testbead3;
testbead3.setId(3);
testbead3.setName("Hydrogen");
beadstructure.AddBead(testbead1);
beadstructure.AddBead(testbead2);
beadstructure.AddBead(testbead3);
beadstructure.ConnectBeads(1, 2);
beadstructure.ConnectBeads(2, 3);
vector<votca::Index> CH = {2, 3};
vector<Edge> CH_bond = {Edge(2, 3)};
BeadStructure CHstructure = beadstructure.getSubStructure(CH, CH_bond);
BOOST_CHECK(CHstructure.BeadExist(2));
BOOST_CHECK(CHstructure.BeadExist(3));
/// Should Throw bond connecting bead 1 and 3 is not in beadstructure
vector<Edge> CH_bond_false = {Edge(1, 3)};
BOOST_CHECK_THROW(beadstructure.getSubStructure(CH, CH_bond_false),
std::runtime_error);
/// Should Throw bead with id 4 is not in beadstructure
vector<votca::Index> CHH_false = {2, 3, 4};
BOOST_CHECK_THROW(beadstructure.getSubStructure(CHH_false, CH_bond),
std::runtime_error);
}
BOOST_AUTO_TEST_CASE(test_beadstructure_isSingleStructure) {
BeadStructure beadstructure;
TestBead testbead1;
testbead1.setName("Carbon");
testbead1.setId(1);
TestBead testbead2;
testbead2.setName("Carbon");
testbead2.setId(2);
TestBead testbead3;
testbead3.setName("Oxygen");
testbead3.setId(3);
TestBead testbead4;
testbead4.setName("Hydrogen");
testbead4.setId(4);
TestBead testbead5;
testbead5.setName("Hydrogen");
testbead5.setId(5);
beadstructure.AddBead(testbead1);
beadstructure.AddBead(testbead2);
BOOST_CHECK(!beadstructure.isSingleStructure());
// C - C
beadstructure.ConnectBeads(1, 2);
BOOST_CHECK(beadstructure.isSingleStructure());
// C - C O
beadstructure.AddBead(testbead3);
BOOST_CHECK(!beadstructure.isSingleStructure());
// C - C - O
beadstructure.ConnectBeads(2, 3);
BOOST_CHECK(beadstructure.isSingleStructure());
// C - C - O H - H
beadstructure.AddBead(testbead4);
beadstructure.AddBead(testbead5);
beadstructure.ConnectBeads(4, 5);
BOOST_CHECK(!beadstructure.isSingleStructure());
}
BOOST_AUTO_TEST_CASE(test_beadstructure_isStructureEquivalent) {
BeadStructure beadstructure1;
BeadStructure beadstructure2;
// Beads for bead structure 1
TestBead testbead1;
testbead1.setName("Carbon");
testbead1.setId(1);
TestBead testbead2;
testbead2.setName("Carbon");
testbead2.setId(2);
TestBead testbead3;
testbead3.setName("Oxygen");
testbead3.setId(3);
TestBead testbead4;
testbead4.setName("Hydrogen");
testbead4.setId(4);
TestBead testbead5;
testbead5.setName("Hydrogen");
testbead5.setId(5);
// Beads for bead structure 2
TestBead testbead6;
testbead6.setName("Carbon");
testbead6.setId(6);
TestBead testbead7;
testbead7.setName("Carbon");
testbead7.setId(7);
TestBead testbead8;
testbead8.setName("Oxygen");
testbead8.setId(8);
TestBead testbead9;
testbead9.setName("Hydrogen");
testbead9.setId(9);
TestBead testbead10;
testbead10.setName("Hydrogen");
testbead10.setId(10);
BOOST_CHECK(beadstructure1.isStructureEquivalent(beadstructure2));
beadstructure1.AddBead(testbead1);
BOOST_CHECK(!beadstructure1.isStructureEquivalent(beadstructure2));
beadstructure2.AddBead(testbead6);
BOOST_CHECK(beadstructure1.isStructureEquivalent(beadstructure2));
beadstructure1.AddBead(testbead2);
beadstructure2.AddBead(testbead7);
beadstructure1.ConnectBeads(1, 2);
BOOST_CHECK(!beadstructure1.isStructureEquivalent(beadstructure2));
beadstructure2.ConnectBeads(6, 7);
BOOST_CHECK(beadstructure1.isStructureEquivalent(beadstructure2));
beadstructure1.AddBead(testbead3);
beadstructure1.AddBead(testbead4);
beadstructure1.AddBead(testbead5);
beadstructure1.ConnectBeads(2, 3);
beadstructure1.ConnectBeads(4, 5);
beadstructure2.AddBead(testbead10);
beadstructure2.AddBead(testbead8);
beadstructure2.AddBead(testbead9);
beadstructure2.ConnectBeads(7, 8);
beadstructure2.ConnectBeads(9, 10);
BOOST_CHECK(beadstructure1.isStructureEquivalent(beadstructure2));
}
BOOST_AUTO_TEST_CASE(test_beadstructure_getNeighBeadIds) {
BeadStructure beadstructure1;
// Beads for bead structure 1
// Make a methane molecule
//
// H
// |
// H - C - H
// |
// H
//
TestBead testbead1;
testbead1.setName("Hydrogen");
testbead1.setId(1);
TestBead testbead2;
testbead2.setName("Carbon");
testbead2.setId(2);
TestBead testbead3;
testbead3.setName("Hydrogen");
testbead3.setId(3);
TestBead testbead4;
testbead4.setName("Hydrogen");
testbead4.setId(4);
TestBead testbead5;
testbead5.setName("Hydrogen");
testbead5.setId(5);
// Make a Water molecule
//<|fim▁hole|> testbead6.setName("Hydrogen");
testbead6.setId(6);
TestBead testbead7;
testbead7.setName("Oxygen");
testbead7.setId(7);
TestBead testbead8;
testbead8.setName("Hydrogen");
testbead8.setId(8);
beadstructure1.AddBead(testbead1);
beadstructure1.AddBead(testbead2);
beadstructure1.AddBead(testbead3);
beadstructure1.AddBead(testbead4);
beadstructure1.AddBead(testbead5);
beadstructure1.AddBead(testbead6);
beadstructure1.AddBead(testbead7);
beadstructure1.AddBead(testbead8);
// At this point non of the beads are connected so should return a vector of
// size 0
auto v1 = beadstructure1.getNeighBeadIds(1);
BOOST_CHECK_EQUAL(v1.size(), 0);
auto v2 = beadstructure1.getNeighBeadIds(2);
BOOST_CHECK_EQUAL(v2.size(), 0);
auto v3 = beadstructure1.getNeighBeadIds(3);
BOOST_CHECK_EQUAL(v3.size(), 0);
auto v4 = beadstructure1.getNeighBeadIds(4);
BOOST_CHECK_EQUAL(v4.size(), 0);
auto v5 = beadstructure1.getNeighBeadIds(5);
BOOST_CHECK_EQUAL(v5.size(), 0);
auto v6 = beadstructure1.getNeighBeadIds(1);
BOOST_CHECK_EQUAL(v6.size(), 0);
auto v7 = beadstructure1.getNeighBeadIds(7);
BOOST_CHECK_EQUAL(v7.size(), 0);
auto v8 = beadstructure1.getNeighBeadIds(8);
BOOST_CHECK_EQUAL(v8.size(), 0);
// Connect beads
beadstructure1.ConnectBeads(1, 2);
beadstructure1.ConnectBeads(3, 2);
beadstructure1.ConnectBeads(4, 2);
beadstructure1.ConnectBeads(5, 2);
beadstructure1.ConnectBeads(6, 7);
beadstructure1.ConnectBeads(7, 8);
v1 = beadstructure1.getNeighBeadIds(1);
BOOST_CHECK_EQUAL(v1.size(), 1);
v2 = beadstructure1.getNeighBeadIds(2);
BOOST_CHECK_EQUAL(v2.size(), 4);
v3 = beadstructure1.getNeighBeadIds(3);
BOOST_CHECK_EQUAL(v3.size(), 1);
v4 = beadstructure1.getNeighBeadIds(4);
BOOST_CHECK_EQUAL(v4.size(), 1);
v5 = beadstructure1.getNeighBeadIds(5);
BOOST_CHECK_EQUAL(v5.size(), 1);
v6 = beadstructure1.getNeighBeadIds(1);
BOOST_CHECK_EQUAL(v6.size(), 1);
v7 = beadstructure1.getNeighBeadIds(7);
BOOST_CHECK_EQUAL(v7.size(), 2);
v8 = beadstructure1.getNeighBeadIds(8);
BOOST_CHECK_EQUAL(v8.size(), 1);
}
BOOST_AUTO_TEST_CASE(test_beadstructure_catchError) {
{
TestBead testbead1;
testbead1.setName("Hydrogen");
testbead1.setId(1);
TestBead testbead2;
testbead2.setName("Carbon");
testbead2.setId(2);
TestBead testbead3;
testbead3.setName("Hydrogen");
testbead3.setId(3);
TestBead testbead4;
testbead4.setName("Hydrogen");
testbead4.setId(4);
TestBead testbead5;
testbead5.setName("Hydrogen");
testbead5.setId(5);
TestBead testbead6;
testbead6.setName("Hydrogen");
testbead6.setId(5);
BeadStructure beadstructure;
beadstructure.AddBead(testbead1);
beadstructure.AddBead(testbead2);
beadstructure.AddBead(testbead3);
beadstructure.AddBead(testbead4);
beadstructure.AddBead(testbead5);
BOOST_CHECK_THROW(beadstructure.AddBead(testbead6), invalid_argument);
BOOST_CHECK_THROW(beadstructure.ConnectBeads(0, 1), invalid_argument);
BOOST_CHECK_THROW(beadstructure.ConnectBeads(5, 6), invalid_argument);
BOOST_CHECK_THROW(beadstructure.ConnectBeads(1, 1), invalid_argument);
}
}
BOOST_AUTO_TEST_SUITE_END()<|fim▁end|> | // H - O - H
//
TestBead testbead6; |
<|file_name|>controllers.js<|end_file_name|><|fim▁begin|>angular.module('starter.controllers', [])
// A simple controller that fetches a list of data from a service
.controller('PetIndexCtrl', function($scope, PetService) {
// "Pets" is a service returning mock data (services.js)
$scope.pets = PetService.all();
})
// A simple controller that shows a tapped item's data
.controller('PetDetailCtrl', function($scope, $stateParams, PetService) {
// "Pets" is a service returning mock data (services.js)
$scope.pet = PetService.get($stateParams.petId);
})
<|fim▁hole|>
// getting fake favor data
.controller('FavorIndexCtrl', function($scope, FavorService) {
$scope.favors = FavorService.all();
})
// A simple controller that shows a tapped item's data
.controller('FavorDetailCtrl', function($scope, $stateParams, FavorService) {
// "Pets" is a service returning mock data (services.js)
$scope.favor = FavorService.get($stateParams.favorId);
});<|fim▁end|> | |
<|file_name|>showSubMenu.py<|end_file_name|><|fim▁begin|>import time
from menu.ncolor import *
from menu.showMainMenu import *
from command.shell import *
from write.dnsmasq_write import *
class Sub_Menu():
dns_message = """ you can add a redirect entry in this menu or edit the dnsmasq configuration
file located in""" + color.BLEU + """ '/etc/redirect/dnsmasq.host'\n """ + color.ENDC
#the user choose a new name. the input of the user will be put in the user
#object
def nameMenu(ssid):
while True:
print ("\nthe current name of the access point is " + color.VERT + "'" + ssid + "'" + color.ENDC)
print("")
print("%49s" % ("current options" + color.ENDC))
print("%58s" % (color.DARKCYAN + "-----------------------" + color.ENDC))
print("%48s" % ("(1) choose a new name."))
print("%41s" % ("(5) main menu.\n"))
while True:
NameChoice = input(color.BLEU + "name > " + color.ENDC)
if NameChoice == "1":
print(color.DARKYELLOW + "enter the new name of the ap..." + color.ENDC)
ssid = input(color.BLEU + "name > " + color.DARKROUGE + "new name > " + color.ENDC)
print (color.VERT + "[+]" + color.ENDC + " changing the name for " + color.VERT + "'" + ssid + "'" + color.ENDC)
time.sleep(1)
return ssid
elif NameChoice == "5":
print(color.VERT + "[+]" + color.ENDC + " going back to main menu.")
time.sleep(0.3)
return ssid
else:
print(color.ROUGE + "[*]" + color.ENDC + " please enter a valid option!")
#taking the crypt variable object to check if an encryption have been chosen. If not
#the user is ask to choose an encryption type. The PassHandle function will be called
#to verify if the password respect the security exigence
def PassordMenu(crypt, password):
while True:
if crypt != "N/A":
print("")
print("%48s" % ("current options" + color.ENDC))
print("%56s" % (color.DARKCYAN + "-----------------------" + color.ENDC))
print("%48s" % ("(1) choose new password."))
print("%39s" % ("(5) main menu.\n"))
while True:
PasswordChoice = input(color.BLEU + "password > " + color.ENDC)
if PasswordChoice == "1":
print(color.DARKYELLOW + "enter the new password for the ap..." + color.ENDC)
error = False
while error == False:
password = input(color.BLEU + "password > " + color.DARKROUGE + "new password > " + color.ENDC)
error = Sub_Menu.PassHandle(crypt, password)
print (color.VERT + "[+]" + color.ENDC + " changing the password to " + color.VERT + "'" + password + "'" + color.ENDC)
time.sleep(1)
return password
elif PasswordChoice == "5":
print(color.VERT + "[+]" + color.ENDC + " going back to main menu.")
time.sleep(0.3)
return password
else:
print(color.ROUGE + "[*]" + color.ENDC + " please enter a valid option!")
else:
print(color.ROUGE + "[*]" + color.ENDC + " please select a security type if you want to choose a password.")
time.sleep(1.5)
return password
#take the security type and password in parameter. If a new password is chosen the old
#password gonna be reset to zero.
def securityMenu(crypt, password):
while True:
security_text = color.BLEU + color.BOLD + """
-WPA2 """ + color.ENDC + """is the most advanced wifi security protocol curently used by most
router by default. The passphrase must have a minimum of 8 character.""" + color.BLEU + color.BOLD + """\n
-WPA""" + color.ENDC + """ wpa is older and less secure than wpa2. it is using an older
encryption (TKIP). Like wpa2 you need to put at least 8 charactere. """ + color.BLEU + color.BOLD + """\n
-WEP""" + color.ENDC + """ wep is deprecated and can be very easely cracked. your wep key must
be at least 10 charactere and only contain hexadecimal character."""
print(security_text)
print ("\n - the current security of the access point is " + color.VERT + "'" + crypt + "'" + color.ENDC)
print("")
print("%53s" % ("current options" + color.ENDC))
print("%61s" % (color.DARKCYAN + "-----------------------" + color.ENDC))
print("%38s" % ("(1) WPA2."))
print("%44s" % ("(2) WPA (TKIP)."))
print("%47s" % ("(3) WEP (64 bits)."))
print("%45s" % ("(4) no security."))
print("%44s" % ("(5) main menu.\n"))
while True:
NameChoice = input(color.BLEU + "security > " + color.ENDC)
pwd = ""
if NameChoice == "1":
Sec = "WPA2"
crypt, password = Sub_Menu.AskPassword(Sec, pwd)
return crypt, password
elif NameChoice == "2":
Sec = "WPA"
crypt, password = Sub_Menu.AskPassword(Sec, pwd)
return crypt, password
elif NameChoice == "3":
Sec = "WEP"
crypt, password = Sub_Menu.AskPassword(Sec, pwd)
return crypt, password
elif NameChoice == "4":
print (color.VERT + "[+]" + color.ENDC + " deleting the " + color.VERT + crypt + color.ENDC + " security.")
time.sleep(1)
crypt = "N/A"
password = "N/A"
return crypt, password
elif NameChoice == "5":
print(color.VERT + "[+]" + color.ENDC + " going back to main menu.")
time.sleep(0.3)
return crypt, password
else:
print(color.ROUGE + "[*]" + color.ENDC + " please enter a valid option!")
#giving the option to decide if the dhcp server will be on or off. It will also
#give the option to change the dhcp pool adresse.
def dhcpMenu(dhcp):
while True:
#putting some information for the dhcp in variable
couleur = color.Color_check(dhcp)
dhcpPool = "10.0.0.10-250"
dhcpLease = "12h"
# show the appropriate option in the menu
if dhcp == "N/A":
dhcpOPTION = "(1) set dhcp server to" + color.VERT + " 'on'" + color.ENDC
else:
dhcpOPTION = "%47s" % " (1) set dhcp server to" + color.ROUGE + " 'off'" + color.ENDC
print ("""\n the dhcp server should always be on. If the dhcp is set to 'N/A' the client
will need to have is adresse, gateway and dns set manualy.\n""")
print (color.BOLD + " dhcp status: " + color.ENDC + couleur + "'" + dhcp + "'" + color.ENDC)
print (color.BOLD + " dhcp pool: " + color.ENDC + color.BLEU + dhcpPool + color.ENDC)
print (color.BOLD + " dhcp lease: " + color.ENDC + color.BLEU + dhcpLease + color.ENDC)
print("")
print("%49s" % ("current options" + color.ENDC))
print("%57s" % (color.DARKCYAN + "-----------------------" + color.ENDC))
print("%61s" % ( dhcpOPTION))
print("%40s" % ("(5) main menu.\n"))
while True:
DhcpChoice = input(color.BLEU + "dhcp > " + color.ENDC)
#check the last dhcp value and take the decision to put it to on or off
if DhcpChoice == "1":
if dhcp == "N/A":
dhcp = "ON"
else:
dhcp = "N/A"
print (color.VERT + "[+]" + color.ENDC + " changing dhcp status to " + color.VERT + "'" + dhcp + "'" + color.ENDC)
time.sleep(1)
return dhcp
#if this option is chosen to go back to main menu
elif DhcpChoice == "5":
print(color.VERT + "[+]" + color.ENDC + " going back to main menu.")
time.sleep(0.3)
return dhcp
else:
print(color.ROUGE + "[*]" + color.ENDC + " please enter a valid option!")
#show the menu for chosing dns option. The dns object can be change to on or N/A.
# I am planing to give the user the choice to put their dns redirect entry directly
# in the program and in the config file.
def dnsMenu(dns):
while True:
couleur = color.Color_check(dns)
# show the appropriate option in the menu
if dns == "N/A":
dnsOPTION = "(1) set dns server to" + color.VERT + " 'on' " + color.ENDC
else:
dnsOPTION = "(1) set dns server to" + color.ROUGE + " 'off'" + color.ENDC
print ("""\n if dns fowarding is set to 'on' dnsmasq will start the dns server and
start fowarding all the request to the google dns server. When the dns
server is active its possible to redirect the client to the ip adresse
of your choice """)
print (color.BOLD + "\n dns status:" + color.ENDC + couleur + " '" + dns + "'" + color.ENDC)
print("%51s" % ("current options" + color.ENDC))
print("%59s" % (color.DARKCYAN + "-----------------------" + color.ENDC))
print("%63s" % (dnsOPTION))
print("%47s" % ("(2) redirect client."))
print("%46s" % ("(3) cleaning entry."))
print("%42s" % ("(5) main menu.\n"))
while True:
DnsChoice = input(color.BLEU + "dns > " + color.ENDC)
if DnsChoice == "1":
if dns == "N/A":
dns = "ON"
else:
dns = "N/A"
print (color.VERT + "[+]" + color.ENDC + " changing dns status to " + color.VERT + "'" + dns + "'" + color.ENDC)
time.sleep(1)
return dns
if DnsChoice == "2":
while True:
# read the dnsmasq.host file and print the message.
print(Sub_Menu.dns_message)
entry_number = read_dnsmasq_host()
# give the user de choice to do a new entry.
print(color.DARKYELLOW + "\ndo you want to write an entry in the file? (y/n)" + color.ENDC)
choice = input(color.BLEU + "dns > " + color.ENDC)
# if choice is yes, we ask the user to enter the entry withthe spicified format.
if choice == "y":
error = False
print (color.DARKCYAN + "enter the new entry with the adresse and the domain separated only by a single")
print("space. Example: (192.168.1.60 www.google.com)")
# if an error is detected in the checkup of the pattern, we stay in the loop.
while not error:
entry = input(color.BLEU + "dns > " + color.DARKROUGE + "entry > " + color.ENDC)
error = Entry_handeling(entry)
else:
break
break
if DnsChoice == "3":
# handle the delete of the entry.
delete_handeling()
break
if DnsChoice == "5":
print(color.VERT + "[+]" + color.ENDC + " going back to main menu.")
time.sleep(0.3)
return dns
else:
print(color.ROUGE + "[*]" + color.ENDC + " please enter a valid option!")
#this function is allowing the user to chose the in and out interface. When the
#interface will be chosen it gonna allow the user to see the status. A refresh
#option will be included
def interfaceMenu(inside, outside):
print("""\n Quick ap will use the interface that you have selected to apply the ip tables
rules on them and make the hotspot working. The inside interface is the wifi
card that will be use whith hostapd for creating the hotspot. The outside
interface will be use to share the connection with the victims. You need to
make sure that the outside interface have an addresse if you want to share
the Internet. \n""")
while True:
#put genral status of the interface in the variables and return false if interface is down.
addresse_in, addresse_out, check_in, check_out = command.nic_selectedStatus(inside, outside)
#color status of the interface are put into varirables.
color_in = color.color_checkINT(inside, check_in)
color_out = color.color_checkINT(outside, check_out)
#show the status of the selected interface with the help of the method nic_selected
print("%50s" % (" interface status" + color.ENDC))
print("%59s" % (color.DARKCYAN + "=======================" + color.ENDC))
print("\t\t\t [" + color_in + inside + color.ENDC + "]" + " <-> " + addresse_in)
print("\t\t\t [" + color_out + outside + color.ENDC + "]" + " <-> " + addresse_out + "\n")
print("%50s" % ("current options" + color.ENDC))
print("%59s" % (color.DARKCYAN + "-----------------------" + color.ENDC))
print("%48s" % ("(1) choose interface."))
print("%39s" % ("(2) refresh."))
print("%41s" % ("(5) main menu."))
#first menu choice.
interfaceChoiceFirst = input(color.BLEU + "\nnetwork > " + color.ENDC)
if interfaceChoiceFirst == "1":
Menu = True
check_choice = False
while Menu == True:
print("%52s" % (" available interface" + color.ENDC))
print("%59s" % (color.VERT + "=======================" + color.ENDC))
#looping to all interface disponible and show their status and if they are selected
interface = command.nic_status(inside, outside)
print("")
print("%51s" % ("current options" + color.ENDC))
print("%59s" % (color.VERT + "-----------------------" + color.ENDC))
print("%49s" % ("(1) choose inside nic."))
print("%50s" % ("(2) choose outside nic."))
print("%48s" % ("(3) deselect all nic."))
print("%39s" % ("(4) refresh."))
print("%41s" % ("(5) main menu."))
interfaceChoice = input(color.BLEU + "\nnetwork > " + color.ENDC + color.DARKROUGE + "nic > " + color.ENDC)
if interfaceChoice == "1":
print(color.DARKYELLOW + "enter the name of the inside interface that you want to select..." + color.ENDC)
insideChoice = input(color.BLEU + "network > " + color.ENDC + color.DARKROUGE + "inside > " + color.ENDC)
#checking in the list of interface to see if the interface is in the choice
interface_check = command.choice_check(insideChoice, interface)
#make sure that the interface selected is not the same has the outside interface.
duplicate = command.nic_duplicate("inside", insideChoice, "", inside, outside)
# if the duplicate is detected the statement continu make the program skip the conditions
# and go back to the start of the loop
if duplicate == True:
continue
#if interface_check return false, return the user to main menu.
elif interface_check == False:
print(color.ROUGE + "[*]" + color.ENDC + " please enter a valid interface. Press 'refresh' to scan interface again.")
time.sleep(1.5)
print("\n")
#run sevral check to see if the choice is wireless compactible etc... If the choice is
#not accepted the last_choice is returned by wifi check
else:
last_choice_in = inside
inside = command.wifi_check(insideChoice, last_choice_in)
elif interfaceChoice == "2":
print(color.DARKYELLOW + "enter the name of the outside interface that you want to select..." + color.ENDC)
outsideChoice = input(color.BLEU + "network > " + color.ENDC + color.DARKROUGE + "outside > " + color.ENDC)
interface_check = command.choice_check(outsideChoice, interface)
duplicate = command.nic_duplicate("outside", "", outsideChoice, inside, outside)
if duplicate == True:
continue
elif interface_check == False:
print(color.ROUGE + "[*]" + color.ENDC + " please enter a valid interface. Press 'refresh' to scan interface again.")
time.sleep(1.5)
print("\n")
else:
outside = command.out_check(outsideChoice)
elif interfaceChoice == "3":
inside = "N/A"
outside = "N/A"
print(color.VERT + "[+]" + color.ENDC + " unselecting all network interface!")
time.sleep(1)
print("\n")
elif interfaceChoice == "4":
print (color.VERT + "[+] " + color.ENDC + "refreshing!")
time.sleep(0.3)
elif interfaceChoice == "5":
print (color.VERT + "[+] " + color.ENDC + "main menu.")
time.sleep(0.3)
return inside, outside
else:
print (color.ROUGE + "[-] " + color.ENDC + "please enter a valid option!\n")
time.sleep(0.3)
elif interfaceChoiceFirst == "2":
print (color.VERT + "[+] " + color.ENDC + "refreshing!")<|fim▁hole|> time.sleep(0.3)
elif interfaceChoiceFirst == "5":
print (color.VERT + "[+] " + color.ENDC + "main menu")
time.sleep(0.3)
return inside, outside
else:
print(color.ROUGE + "[-] " + color.ENDC + "please enter a valid choice!\n")
time.sleep(0.3)
return inside, outside
#this function take in parameter the security type and the actual password. If the
#wpa key or the wep key is incorrect it gonna show an error message and send true or
#false depending on the situation
def PassHandle(handleSEC, handlePASS):
passLenght = len(handlePASS)
allowed = set("123456789" + "abcdef")
if handleSEC == "WPA2" or handleSEC == "WPA":
if passLenght < 8:
print (color.ROUGE + "[*]" + color.ENDC + " the wpa password must be at least 8 charactere!")
return False
else:
return True
elif handleSEC == "WEP":
if set(handlePASS) <= allowed and passLenght == 10:
return True
else:
print (color.ROUGE + "[*]" + color.ENDC + " the wep password must have 10 charactere and use HEX only")
return False
#this function take the secutiry type and password in parameter and it check with a loop
#if the password is following the rule.
def AskPassword(Sec, pwd):
error = False
print(color.DARKYELLOW + "enter the new " + Sec + " password for the ap..." + color.ENDC)
while error == False:
pwd = input(color.BLEU + "security > " + color.DARKROUGE + Sec + " > " + color.ENDC)
error = Sub_Menu.PassHandle(Sec, pwd)
print (color.VERT + "[+]" + color.ENDC + " changing the security to " + color.VERT + "'" + Sec + "'" + color.ENDC)
print (color.VERT + "[+]" + color.ENDC + " changing the password to " + color.VERT + "'" + pwd + "'" + color.ENDC)
time.sleep(1)
return Sec, pwd<|fim▁end|> | |
<|file_name|>app.js<|end_file_name|><|fim▁begin|>/* some devices call home before accepting a wifi access point. Spoof those responses. */
var path = require('path');
exports.load = function(server, boatData, settings) {
var endpointMap = [
{'route': '/kindle-wifi/wifiredirect.html', 'responseFile': 'kindle.html'} ,
{'route': '/kindle-wifi/wifistub.html', 'responseFile': 'kindle.html'} //http://spectrum.s3.amazonaws.com<|fim▁hole|> _.each(endpointMap, function(endpoint) {
server.get(endpoint.route, function(req, res) {
res.sendFile(path.join(__dirname + endpoint.responseFile));
});
});
};<|fim▁end|> | ];
|
<|file_name|>autostart.py<|end_file_name|><|fim▁begin|># user.py is the autostart code for a ulnoiot node.
# Configure your devices, sensors and local interaction here.
# Always start with this to make everything from ulnoiot available.
# Therefore, do not delete the following line.
from ulnoiot import *
# The following is just example code, adjust to your needs accordingly.
# wifi and mqtt connect are done automatically, we assume for this example
# the following configuration.
# mqtt("ulnoiotgw", "myroom/test1")
## Use some shields
# The onboard-led is always available.
# With this configuration it will report under myroom/test1/blue
# and can be set via sending off or on to myroom/test1/blue/test.
from ulnoiot.shield.onboardled import blue
blue.high() # make sure it's off (it's reversed)
## Add some other devices
# Add a button with a slightly higher debounce rate, which will report<|fim▁hole|>
# Count rising signals on d2=Pin(4) and
# report number counted at myroom/test1/shock1.
# trigger("shock1",Pin(4))
## Start to transmit every 10 seconds (or when status changed).
# Don't forget the run-comamnd at the end.
run(5)<|fim▁end|> | # in the topic myroom/test1/button1.
button("b1", d6, pullup=False, threshold=2) |
<|file_name|>tcp.rs<|end_file_name|><|fim▁begin|>use std::io::{Read, Write};
use std::net::{self, SocketAddr};
use std::os::unix::io::{RawFd, FromRawFd, IntoRawFd, AsRawFd};
use libc;
use net2::TcpStreamExt;
use {io, Evented, Ready, Poll, PollOpt, Token};
use sys::unix::eventedfd::EventedFd;
use sys::unix::io::set_nonblock;
#[derive(Debug)]
pub struct TcpStream {
inner: net::TcpStream,
}
#[derive(Debug)]
pub struct TcpListener {
inner: net::TcpListener,
}
impl TcpStream {
pub fn connect(stream: net::TcpStream, addr: &SocketAddr) -> io::Result<TcpStream> {
try!(set_nonblock(&stream));
match stream.connect(addr) {
Ok(..) => {}
Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {}
Err(e) => return Err(e),
}
Ok(TcpStream {
inner: stream,
})
}
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
self.inner.peer_addr()
}
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.inner.local_addr()
}
pub fn try_clone(&self) -> io::Result<TcpStream> {
self.inner.try_clone().map(|s| {
TcpStream {
inner: s,
}
})
}
pub fn shutdown(&self, how: net::Shutdown) -> io::Result<()> {
self.inner.shutdown(how)
}
pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
self.inner.set_nodelay(nodelay)
}
pub fn nodelay(&self) -> io::Result<bool> {
self.inner.nodelay()
}
pub fn set_keepalive_ms(&self, millis: Option<u32>) -> io::Result<()> {
self.inner.set_keepalive_ms(millis)
}
pub fn keepalive_ms(&self) -> io::Result<Option<u32>> {
self.inner.keepalive_ms()
}
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
self.inner.set_ttl(ttl)
}
pub fn ttl(&self) -> io::Result<u32> {
self.inner.ttl()
}
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
self.inner.take_error()
}
}
impl<'a> Read for &'a TcpStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
(&self.inner).read(buf)
}
}
impl<'a> Write for &'a TcpStream {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
(&self.inner).write(buf)
}
fn flush(&mut self) -> io::Result<()> {
(&self.inner).flush()
}
}
impl Evented for TcpStream {
fn register(&self, poll: &Poll, token: Token,
interest: Ready, opts: PollOpt) -> io::Result<()> {
EventedFd(&self.as_raw_fd()).register(poll, token, interest, opts)
}
fn reregister(&self, poll: &Poll, token: Token,
interest: Ready, opts: PollOpt) -> io::Result<()> {
EventedFd(&self.as_raw_fd()).reregister(poll, token, interest, opts)
}
fn deregister(&self, poll: &Poll) -> io::Result<()> {
EventedFd(&self.as_raw_fd()).deregister(poll)
}
}
impl FromRawFd for TcpStream {
unsafe fn from_raw_fd(fd: RawFd) -> TcpStream {<|fim▁hole|> TcpStream {
inner: net::TcpStream::from_raw_fd(fd),
}
}
}
impl IntoRawFd for TcpStream {
fn into_raw_fd(self) -> RawFd {
self.inner.into_raw_fd()
}
}
impl AsRawFd for TcpStream {
fn as_raw_fd(&self) -> RawFd {
self.inner.as_raw_fd()
}
}
impl TcpListener {
pub fn new(inner: net::TcpListener, _addr: &SocketAddr) -> io::Result<TcpListener> {
try!(set_nonblock(&inner));
Ok(TcpListener {
inner: inner,
})
}
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.inner.local_addr()
}
pub fn try_clone(&self) -> io::Result<TcpListener> {
self.inner.try_clone().map(|s| {
TcpListener {
inner: s,
}
})
}
pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
self.inner.accept().and_then(|(s, a)| {
try!(set_nonblock(&s));
Ok((TcpStream {
inner: s,
}, a))
})
}
pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
self.inner.set_only_v6(only_v6)
}
pub fn only_v6(&self) -> io::Result<bool> {
self.inner.only_v6()
}
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
self.inner.set_ttl(ttl)
}
pub fn ttl(&self) -> io::Result<u32> {
self.inner.ttl()
}
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
self.inner.take_error()
}
}
impl Evented for TcpListener {
fn register(&self, poll: &Poll, token: Token,
interest: Ready, opts: PollOpt) -> io::Result<()> {
EventedFd(&self.as_raw_fd()).register(poll, token, interest, opts)
}
fn reregister(&self, poll: &Poll, token: Token,
interest: Ready, opts: PollOpt) -> io::Result<()> {
EventedFd(&self.as_raw_fd()).reregister(poll, token, interest, opts)
}
fn deregister(&self, poll: &Poll) -> io::Result<()> {
EventedFd(&self.as_raw_fd()).deregister(poll)
}
}
impl FromRawFd for TcpListener {
unsafe fn from_raw_fd(fd: RawFd) -> TcpListener {
TcpListener {
inner: net::TcpListener::from_raw_fd(fd),
}
}
}
impl IntoRawFd for TcpListener {
fn into_raw_fd(self) -> RawFd {
self.inner.into_raw_fd()
}
}
impl AsRawFd for TcpListener {
fn as_raw_fd(&self) -> RawFd {
self.inner.as_raw_fd()
}
}<|fim▁end|> | |
<|file_name|>utils.py<|end_file_name|><|fim▁begin|># Copyright (c) 2016 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import io
import functools
import hashlib
import hmac
import logging
import os
import re
import shlex
import shutil
import stat
import subprocess
import urllib.parse
import uuid
import werkzeug
import zipfile
from . import app, config, models
from urllib.parse import urlparse
from flask import request, session, redirect, url_for, Response
from datetime import datetime
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
def get_raise(data, key, expect_type=None):
''' Helper function to retrieve an element from a JSON data structure.
The *key* must be a string and may contain periods to indicate nesting.
Parts of the key may be a string or integer used for indexing on lists.
If *expect_type* is not None and the retrieved value is not of the
specified type, TypeError is raised. If the key can not be found,
KeyError is raised. '''
parts = key.split('.')
resolved = ''
for part in parts:
resolved += part
try:
part = int(part)
except ValueError:
pass
if isinstance(part, str):
if not isinstance(data, dict):
raise TypeError('expected dictionary to access {!r}'.format(resolved))
try:
data = data[part]
except KeyError:
raise KeyError(resolved)
elif isinstance(part, int):
if not isinstance(data, list):
raise TypeError('expected list to access {!r}'.format(resolved))
try:
data = data[part]
except IndexError:
raise KeyError(resolved)
else:
assert False, "unreachable"
resolved += '.'
if expect_type is not None and not isinstance(data, expect_type):
raise TypeError('expected {!r} but got {!r} instead for {!r}'.format(
expect_type.__name__, type(data).__name__, key))
return data
def get(data, key, expect_type=None, default=None):
''' Same as :func:`get_raise`, but returns *default* if the key could
not be found or the datatype doesn't match. '''
try:
return get_raise(data, key, expect_type)
except (TypeError, ValueError):
return default
def basic_auth(message='Login required'):
''' Sends a 401 response that enables basic auth. '''
headers = {'WWW-Authenticate': 'Basic realm="{}"'.format(message)}
return Response('Please log in.', 401, headers, mimetype='text/plain')
def requires_auth(func):
''' Decorator for view functions that require basic authentication. '''
@functools.wraps(func)
def wrapper(*args, **kwargs):
ip = request.remote_addr
token_string = session.get('flux_login_token')
token = models.LoginToken.select(lambda t: t.token == token_string).first()
if not token or token.ip != ip or token.expired():
if token and token.expired():
flash("Your login session has expired.")
token.delete()
return redirect(url_for('login'))
request.login_token = token
request.user = token.user
return func(*args, **kwargs)
return wrapper
def with_io_response(kwarg='stream', stream_type='text', **response_kwargs):
''' Decorator for View functions that create a :class:`io.StringIO` or
:class:`io.BytesIO` (based on the *stream_type* parameter) and pass it
as *kwarg* to the wrapped function. The contents of the buffer are
sent back to the client. '''
if stream_type == 'text':
factory = io.StringIO
elif stream_type == 'bytes':
factory = io.BytesIO
else:
raise ValueError('invalid value for stream_type: {!r}'.format(stream_type))
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if kwarg in kwargs:
raise RuntimeError('keyword argument {!r} already occupied'.format(kwarg))
kwargs[kwarg] = stream = factory()
status = func(*args, **kwargs)
return Response(stream.getvalue(), status=status, **response_kwargs)
return wrapper
return decorator
def with_logger(kwarg='logger', stream_dest_kwarg='stream', replace=True):
''' Decorator that creates a new :class:`logging.Logger` object
additionally to or in-place for the *stream* parameter passed to
the wrapped function. This is usually used in combination with
the :func:`with_io_response` decorator.
Note that exceptions with this decorator will be logged and the
returned status code will be 500 Internal Server Error. '''
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if replace:
stream = kwargs.pop(stream_dest_kwarg)
else:
stream = kwargs[stream_dest_kwarg]
kwargs[kwarg] = logger = create_logger(stream)
try:
return func(*args, **kwargs)
except BaseException as exc:
logger.exception(exc)
return 500
return wrapper
return decorator
def create_logger(stream, name=__name__, fmt=None):
''' Creates a new :class:`logging.Logger` object with the
specified *name* and *fmt* (defaults to a standard logging
formating including the current time, levelname and message).
The logger will also output to stderr. '''
fmt = fmt or '[%(asctime)-15s - %(levelname)s]: %(message)s'
formatter = logging.Formatter(fmt)
logger = logging.Logger(name)
handler = logging.StreamHandler(stream)
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
def stream_file(filename, name=None, mime=None):
def generate():
with open(filename, 'rb') as fp:
yield from fp
if name is None:
name = os.path.basename(filename)
headers = {}
headers['Content-Type'] = mime or 'application/x-octet-stream'
headers['Content-Length'] = os.stat(filename).st_size
headers['Content-Disposition'] = 'attachment; filename="' + name + '"'
return Response(generate(), 200, headers)
def flash(message=None):
if message is None:
return session.pop('flux_flash', None)
else:
session['flux_flash'] = message
def make_secret():
return str(uuid.uuid4())
def hash_pw(pw):
return hashlib.md5(pw.encode('utf8')).hexdigest()
def makedirs(path):
''' Shorthand that creates a directory and stays silent when it
already exists. '''
if not os.path.exists(path):
os.makedirs(path)
def rmtree(path, remove_write_protection=False):
"""
A wrapper for #shutil.rmtree() that can try to remove write protection
if removing fails, if enabled.
"""
if remove_write_protection:
def on_rm_error(func, path, exc_info):
os.chmod(path, stat.S_IWRITE)
os.unlink(path)
else:
on_rm_error = None
shutil.rmtree(path, onerror=on_rm_error)
def zipdir(dirname, filename):
dirname = os.path.abspath(dirname)
zipf = zipfile.ZipFile(filename, 'w')
for root, dirs, files in os.walk(dirname):
for fname in files:
arcname = os.path.join(os.path.relpath(root, dirname), fname)
zipf.write(os.path.join(root, fname), arcname)
zipf.close()
def secure_filename(filename):
"""
Similar to #werkzeug.secure_filename(), but preserves leading dots in
the filename.
"""
while True:
filename = filename.lstrip('/').lstrip('\\')
if filename.startswith('..') and filename[2:3] in '/\\':
filename = filename[3:]
elif filename.startswith('.') and filename[1:2] in '/\\':
filename = filename[2:]
else:
break
has_dot = filename.startswith('.')
filename = werkzeug.secure_filename(filename)
if has_dot:
filename = '.' + filename
return filename
def quote(s, for_ninja=False):
"""
Enhanced implementation of #shlex.quote().
Does not generate single-quotes on Windows.
"""
if os.name == 'nt' and os.sep == '\\':
s = s.replace('"', '\\"')
if re.search('\s', s) or any(c in s for c in '<>'):
s = '"' + s + '"'
else:
s = shlex.quote(s)
return s
def run(command, logger, cwd=None, env=None, shell=False, return_stdout=False,
inherit_env=True):
"""
Run a subprocess with the specified command. The command and output of is
logged to logger. The command will automatically be converted to a string
or list of command arguments based on the *shell* parameter.
# Parameters
command (str, list): A command-string or list of command arguments.
logger (logging.Logger): A logger that will receive the command output.
cwd (str, None): The current working directory.
env (dict, None): The environment for the subprocess.
shell (bool): If set to #True, execute the command via the system shell.
return_stdout (bool): Return the output of the command (including stderr)
to the caller. The result will be a tuple of (returncode, output).
inherit_env (bool): Inherit the current process' environment.
# Return
int, tuple of (int, str): The return code, or the returncode and the
output of the command.
"""
if shell:
if not isinstance(command, str):
command = ' '.join(quote(x) for x in command)
if logger:
logger.info('$ ' + command)
else:
if isinstance(command, str):
command = shlex.split(command)
if logger:
logger.info('$ ' + ' '.join(map(quote, command)))
if env is None:
env = {}
if inherit_env:
env = {**os.environ, **env}
popen = subprocess.Popen(
command, cwd=cwd, env=env, shell=shell, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, stdin=None)
stdout = popen.communicate()[0].decode()
if stdout:
if popen.returncode != 0 and logger:
logger.error('\n' + stdout)
else:
if logger:
logger.info('\n' + stdout)
if return_stdout:
return popen.returncode, stdout
return popen.returncode
def ssh_command(url, *args, no_ptty=False, identity_file=None,
verbose=None, options=None):
''' Helper function to generate an SSH command. If not options are
specified, the default option ``BatchMode=yes`` will be set. '''
if options is None:
options = {'BatchMode': 'yes'}
if verbose is None:
verbose = config.ssh_verbose
command = ['ssh']
if url is not None:
command.append(url)
command += ['-o{}={}'.format(k, v) for (k, v) in options.items()]
if no_ptty:
command.append('-T')
if identity_file:
command += ['-o', 'IdentitiesOnly=yes']
# NOTE: Workaround for windows, as the backslashes are gone at the time
# Git tries to use the GIT_SSH_COMMAND.
command += ['-i', identity_file.replace('\\', '/')]
if verbose:
command.append('-v')
if args:
command.append('--')
command += args
return command
def strip_url_path(url):
''' Strips that path part of the specified *url*. '''
result = list(urllib.parse.urlparse(url))
result[2] = ''
return urllib.parse.urlunparse(result)
def get_github_signature(secret, payload_data):
''' Generates the Github HMAC signature from the repository
*secret* and the *payload_data*. The GitHub signature is sent
with the ``X-Hub-Signature`` header. '''
return hmac.new(secret.encode('utf8'), payload_data, hashlib.sha1).hexdigest()
def get_bitbucket_signature(secret, payload_data):
''' Generates the Bitbucket HMAC signature from the repository
*secret* and the *payload_data*. The Bitbucket signature is sent
with the ``X-Hub-Signature`` header. '''
return hmac.new(secret.encode('utf8'), payload_data, hashlib.sha256).hexdigest()
def get_date_diff(date1, date2):
if (not date1) or (not date2):
if (not date1) and date2:
date1 = datetime.now()
else:
return '00:00:00'
diff = (date1 - date2) if date1 > date2 else (date2 - date1)
seconds = int(diff.seconds % 60)
minutes = int(((diff.seconds - seconds) / 60) % 60)
hours = int((diff.seconds - seconds - minutes * 60) / 3600)
return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
def is_page_active(page, user):
path = request.path
if page == 'dashboard' and (not path or path == '/'):
return True
elif page == 'repositories' and (path.startswith('/repositories') or path.startswith('/repo') or path.startswith('/edit/repo') or path.startswith('/build') or path.startswith('/overrides')):
return True
elif page == 'users' and (path.startswith('/users') or (path.startswith('/user') and path != ('/user/' + str(user.id)))):
return True
elif page == 'profile' and path == ('/user/' + str(user.id)):
return True
elif page == 'integration' and path == '/integration':
return True
return False
def ping_repo(repo_url, repo = None):
if not repo_url or repo_url == '':
return 1
if repo and os.path.isfile(get_repo_private_key_path(repo)):
identity_file = get_repo_private_key_path(repo)
else:
identity_file = config.ssh_identity_file
ssh_cmd = ssh_command(None, identity_file=identity_file)
env = {'GIT_SSH_COMMAND': ' '.join(map(quote, ssh_cmd))}
ls_remote = ['git', 'ls-remote', '--exit-code', repo_url]
res = run(ls_remote, app.logger, env=env)
return res
def get_customs_path(repo):
return os.path.join(config.customs_dir, repo.name.replace('/', os.sep))
def get_override_path(repo):
return os.path.join(config.override_dir, repo.name.replace('/', os.sep))
def get_override_build_script_path(repo):
return os.path.join(get_override_path(repo), config.build_scripts[0])
def read_override_build_script(repo):
build_script_path = get_override_build_script_path(repo)
if os.path.isfile(build_script_path):
build_script_file = open(build_script_path, mode='r')
build_script = build_script_file.read()
build_script_file.close()
return build_script
return ''
def write_override_build_script(repo, build_script):
build_script_path = get_override_build_script_path(repo)
if build_script.strip() == '':
if os.path.isfile(build_script_path):
os.remove(build_script_path)
else:
makedirs(os.path.dirname(build_script_path))
build_script_file = open(build_script_path, mode='w')
build_script_file.write(build_script.replace('\r', ''))
build_script_file.close()
def get_public_key():
"""
Returns the servers SSH public key.
"""
<|fim▁hole|> filename = config.ssh_identity_file or os.path.expanduser('~/.ssh/id_rsa')
if not filename.endswith('.pub'):
filename += '.pub'
if os.path.isfile(filename):
with open(filename) as fp:
return fp.read()
return None
def generate_ssh_keypair(public_key_comment):
"""
Generates new RSA ssh keypair.
Return:
tuple(str, str): generated private and public keys
"""
key = rsa.generate_private_key(backend=default_backend(), public_exponent=65537, key_size=4096)
private_key = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()).decode('ascii')
public_key = key.public_key().public_bytes(serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH).decode('ascii')
if public_key_comment:
public_key += ' ' + public_key_comment
return private_key, public_key
def get_repo_private_key_path(repo):
"""
Returns path of private key for repository from Customs folder.
Return:
str: path to custom private SSH key
"""
return os.path.join(get_customs_path(repo), 'id_rsa')
def get_repo_public_key_path(repo):
"""
Returns path of public key for repository from Customs folder.
Return:
str: path to custom public SSH key
"""
return os.path.join(get_customs_path(repo), 'id_rsa.pub')<|fim▁end|> | # XXX Support all valid options and eventually parse the config file? |
<|file_name|>forms.py<|end_file_name|><|fim▁begin|>from flask.ext.wtf import Form
from flask.ext.wtf.html5 import EmailField
from wtforms.validators import Required
from wtforms.fields import (
TextAreaField,
HiddenField
)
<|fim▁hole|>
class FeedbackForm(Form):
feedback = TextAreaField('Your feedback', validators=[Required()])<|fim▁end|> | class LoginForm(Form):
email = EmailField('Email address', validators=[Required()])
next = HiddenField('next')
|
<|file_name|>matsa.go<|end_file_name|><|fim▁begin|>// Matsa Discovery Library
// Copyright (C) 2015 by Todd Moses ([email protected])
// Use of this source code is governed by an Apache
// license that can be found in the LICENSE file.
// version 0.0.1
package matsa
type List_f64 []float64
type List_str []string
// general list methods
//length - return the number of values in the collection
func (list List_str) Length() int {
return len(list)
}
func (list List_f64) Length() int {
return len(list)
}
//isempty - provides an clear way to determine if list has elements or not
func (list List_f64) IsEmpty() bool {
if list.Length() == 0 {
return true
}
return false
}
func (list List_str) IsEmpty() bool {
if list.Length() == 0 {
return true
}
return false
}
//insert item into list
func (list List_f64) Insert(values ...float64) List_f64 {
for _, val := range values {
list = append(list, val)
}
return list
}
func (list List_str) Insert(values ...string) List_str {
for _, val := range values {
list = append(list, val)
}
return list
}
//removebyindex - item from list by index
func (list List_f64) RemoveByIndex(i int) List_f64 {
list, list[len(list)-1] = append(list[:i], list[i+1:]...), 0
return list
}
func (list List_str) RemoveByIndex(i int) List_str {
list, list[len(list)-1] = append(list[:i], list[i+1:]...), ""
return list
}
//removebyvalue - item from list by value
func (list List_f64) RemoveByValue(v float64) List_f64 {
return list.Without(v)
}
func (list List_str) RemoveByValue(v string) List_str {
return list.Without(v)
}
//pop element from list
func (list List_f64) Pop() (float64, List_f64) {
out, list := list[len(list)-1], list[:len(list)-1]
return out, list
}
func (list List_str) Pop() (string, List_str) {
out, list := list[len(list)-1], list[:len(list)-1]
return out, list
}
//push element onto list
func (list List_f64) Push(val float64) List_f64 {
list.Insert(val)
return list
}
func (list List_str) Push(val string) List_str {
list.Insert(val)
return list
}
//copy - create a copy of the list
func (list List_f64) Copy() List_f64 {
out := make(List_f64, len(list))<|fim▁hole|>
func (list List_str) Copy() List_str {
out := make(List_str, len(list))
copy(out, list)
return out
}
//append - add a list onto the end of the current list
func (list List_f64) Append(list2 List_f64) List_f64 {
list = append(list, list2...)
return list
}
func (list List_str) Append(list2 List_str) List_str {
list = append(list, list2...)
return list
}<|fim▁end|> | copy(out, list)
return out
} |
<|file_name|>strategy.go<|end_file_name|><|fim▁begin|>/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package namespace
import (
"fmt"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation/field"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
apistorage "k8s.io/apiserver/pkg/storage"
"k8s.io/apiserver/pkg/storage/names"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/validation"
"k8s.io/kubernetes/pkg/genericapiserver/registry/generic"
)
// namespaceStrategy implements behavior for Namespaces
type namespaceStrategy struct {
runtime.ObjectTyper
names.NameGenerator
}
// Strategy is the default logic that applies when creating and updating Namespace
// objects via the REST API.
var Strategy = namespaceStrategy{api.Scheme, names.SimpleNameGenerator}
// NamespaceScoped is false for namespaces.
func (namespaceStrategy) NamespaceScoped() bool {
return false
}
// PrepareForCreate clears fields that are not allowed to be set by end users on creation.
func (namespaceStrategy) PrepareForCreate(ctx genericapirequest.Context, obj runtime.Object) {
// on create, status is active
namespace := obj.(*api.Namespace)
namespace.Status = api.NamespaceStatus{
Phase: api.NamespaceActive,
}
// on create, we require the kubernetes value
// we cannot use this in defaults conversion because we let it get removed over life of object
hasKubeFinalizer := false
for i := range namespace.Spec.Finalizers {
if namespace.Spec.Finalizers[i] == api.FinalizerKubernetes {
hasKubeFinalizer = true
break
}
}
if !hasKubeFinalizer {
if len(namespace.Spec.Finalizers) == 0 {
namespace.Spec.Finalizers = []api.FinalizerName{api.FinalizerKubernetes}
} else {
namespace.Spec.Finalizers = append(namespace.Spec.Finalizers, api.FinalizerKubernetes)
}
}
}
// PrepareForUpdate clears fields that are not allowed to be set by end users on update.
func (namespaceStrategy) PrepareForUpdate(ctx genericapirequest.Context, obj, old runtime.Object) {
newNamespace := obj.(*api.Namespace)
oldNamespace := old.(*api.Namespace)
newNamespace.Spec.Finalizers = oldNamespace.Spec.Finalizers
newNamespace.Status = oldNamespace.Status
}
// Validate validates a new namespace.
func (namespaceStrategy) Validate(ctx genericapirequest.Context, obj runtime.Object) field.ErrorList {
namespace := obj.(*api.Namespace)
return validation.ValidateNamespace(namespace)
}
// Canonicalize normalizes the object after validation.
func (namespaceStrategy) Canonicalize(obj runtime.Object) {
}
// AllowCreateOnUpdate is false for namespaces.
func (namespaceStrategy) AllowCreateOnUpdate() bool {
return false
}
// ValidateUpdate is the default update validation for an end user.
func (namespaceStrategy) ValidateUpdate(ctx genericapirequest.Context, obj, old runtime.Object) field.ErrorList {
errorList := validation.ValidateNamespace(obj.(*api.Namespace))
return append(errorList, validation.ValidateNamespaceUpdate(obj.(*api.Namespace), old.(*api.Namespace))...)
}
func (namespaceStrategy) AllowUnconditionalUpdate() bool {
return true
}
type namespaceStatusStrategy struct {
namespaceStrategy
}
var StatusStrategy = namespaceStatusStrategy{Strategy}
func (namespaceStatusStrategy) PrepareForUpdate(ctx genericapirequest.Context, obj, old runtime.Object) {
newNamespace := obj.(*api.Namespace)
oldNamespace := old.(*api.Namespace)
newNamespace.Spec = oldNamespace.Spec
}
func (namespaceStatusStrategy) ValidateUpdate(ctx genericapirequest.Context, obj, old runtime.Object) field.ErrorList {
return validation.ValidateNamespaceStatusUpdate(obj.(*api.Namespace), old.(*api.Namespace))
}
type namespaceFinalizeStrategy struct {
namespaceStrategy
}
var FinalizeStrategy = namespaceFinalizeStrategy{Strategy}
func (namespaceFinalizeStrategy) ValidateUpdate(ctx genericapirequest.Context, obj, old runtime.Object) field.ErrorList {
return validation.ValidateNamespaceFinalizeUpdate(obj.(*api.Namespace), old.(*api.Namespace))
}
// PrepareForUpdate clears fields that are not allowed to be set by end users on update.
func (namespaceFinalizeStrategy) PrepareForUpdate(ctx genericapirequest.Context, obj, old runtime.Object) {
newNamespace := obj.(*api.Namespace)
oldNamespace := old.(*api.Namespace)
newNamespace.Status = oldNamespace.Status
}
// GetAttrs returns labels and fields of a given object for filtering purposes.
func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {
namespaceObj, ok := obj.(*api.Namespace)
if !ok {
return nil, nil, fmt.Errorf("not a namespace")
}
return labels.Set(namespaceObj.Labels), NamespaceToSelectableFields(namespaceObj), nil
}
// MatchNamespace returns a generic matcher for a given label and field selector.
func MatchNamespace(label labels.Selector, field fields.Selector) apistorage.SelectionPredicate {
return apistorage.SelectionPredicate{
Label: label,
Field: field,
GetAttrs: GetAttrs,
}
}
// NamespaceToSelectableFields returns a field set that represents the object
func NamespaceToSelectableFields(namespace *api.Namespace) fields.Set {
objectMetaFieldsSet := generic.ObjectMetaFieldsSet(&namespace.ObjectMeta, false)
specificFieldsSet := fields.Set{
"status.phase": string(namespace.Status.Phase),
// This is a bug, but we need to support it for backward compatibility.
"name": namespace.Name,
}<|fim▁hole|><|fim▁end|> | return generic.MergeFieldsSets(objectMetaFieldsSet, specificFieldsSet)
} |
<|file_name|>interfaces.rs<|end_file_name|><|fim▁begin|>// Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.
//! A handler and associated types for the interfaces action.
//!
//! The interfaces action lists all network interfaces available on the client,
//! collecting their names, MAC and IP addresses.
use log::error;
use pnet::{
datalink::{self, NetworkInterface},
ipnetwork::IpNetwork,
util::MacAddr,
};
use rrg_proto::{Interface, NetworkAddress};
use crate::session::{self, Session};
/// A response type for the interfaces action.
#[derive(Debug)]
pub struct Response {
/// Information about an interface.
interface: NetworkInterface,
}
/// Handles requests for the interfaces action.
pub fn handle<S: Session>(session: &mut S, _: ()) -> session::Result<()> {
for interface in datalink::interfaces() {
session.reply(Response {
interface: interface,
})?;
}
Ok(())
}
/// Converts a [`MacAddr`][mac_addr] to a vector of bytes,
/// which is what protobuf expects as a MAC.
///
/// [mac_addr]: ../../../pnet/util/struct.MacAddr.html
fn mac_to_vec(mac: MacAddr) -> Vec<u8> {
vec![mac.0, mac.1, mac.2, mac.3, mac.4, mac.5]
}
/// Converts a single [`IpNetwork`][ip_network] to a protobuf struct
/// corresponding to an IP address.
///
/// [ip_network]: ../../../ipnetwork/enum.IpNetwork.html
fn ip_to_proto(ip_network: IpNetwork) -> NetworkAddress {
use rrg_proto::network_address::Family;
use std::net::IpAddr::{V4, V6};
match ip_network.ip() {
V4(ipv4) => NetworkAddress {
address_type: Some(Family::Inet.into()),
packed_bytes: Some(ipv4.octets().to_vec()),
..Default::default()
},
V6(ipv6) => NetworkAddress {
address_type: Some(Family::Inet6.into()),
packed_bytes: Some(ipv6.octets().to_vec()),
..Default::default()
},
}
}
/// Maps a vector of [`IpNetwork`][ip_network]s to a vector
/// of protobuf structs corresponding to an IP address.
///
/// [ip_network]: ../../../ipnetwork/enum.IpNetwork.html
fn ips_to_protos(ips: Vec<IpNetwork>) -> Vec<NetworkAddress> {
ips.into_iter().map(ip_to_proto).collect()
}
impl super::Response for Response {
const RDF_NAME: Option<&'static str> = Some("Interface");
type Proto = Interface;
fn into_proto(self) -> Interface {
let mac = match self.interface.mac {
Some(mac) => Some(mac_to_vec(mac)),
None => {
error!(
"unable to get MAC address for {} interface",
self.interface.name,
);
None
},
};
Interface {
mac_address: mac,
ifname: Some(self.interface.name),
addresses: ips_to_protos(self.interface.ips),
..Default::default()
}
}
}
#[cfg(test)]<|fim▁hole|>
use super::*;
#[test]
fn test_loopback_presence() {
let mut session = session::test::Fake::new();
assert!(handle(&mut session, ()).is_ok());
let mut is_loopback_present = false;
for i in 0..session.reply_count() {
let interface = &session.reply::<Response>(i).interface;
is_loopback_present |= interface.is_loopback();
}
assert!(is_loopback_present);
}
}<|fim▁end|> | mod tests { |
<|file_name|>EventTarget.js<|end_file_name|><|fim▁begin|>/**
* @author Mat Groves http://matgroves.com/ @Doormat23
* @author Chad Engler https://github.com/englercj @Rolnaaba
*/
/**
* Originally based on https://github.com/mrdoob/eventtarget.js/ from mr Doob.
* Currently takes inspiration from the nodejs EventEmitter, EventEmitter3, and smokesignals
*/
/**
* Mixins event emitter functionality to a class
*
* @class EventTarget
* @example
* function MyEmitter() {}
*
* Phaser.EventTarget.mixin(MyEmitter.prototype);
*
* var em = new MyEmitter();
* em.emit('eventName', 'some data', 'some more data', {}, null, ...);
*/
Phaser.EventTarget = {
/**
* Backward compat from when this used to be a function
*/
call: function callCompat(obj) {
if(obj) {
obj = obj.prototype || obj;
Phaser.EventTarget.mixin(obj);
}
},
/**
* Mixes in the properties of the EventTarget prototype onto another object
*
* @method Phaser.EventTarget.mixin
* @param object {Object} The obj to mix into
*/
mixin: function mixin(obj) {
/**
* Return a list of assigned event listeners.
*
* @method Phaser.EventTarget.listeners
* @param eventName {String} The events that should be listed.
* @return {Array} An array of listener functions
*/
obj.listeners = function listeners(eventName) {
this._listeners = this._listeners || {};
return this._listeners[eventName] ? this._listeners[eventName].slice() : [];
};
/**
* Emit an event to all registered event listeners.
*
* @method Phaser.EventTarget.emit
* @alias dispatchEvent
* @param eventName {String} The name of the event.
* @return {Boolean} Indication if we've emitted an event.
*/
obj.emit = obj.dispatchEvent = function emit(eventName, data) {
this._listeners = this._listeners || {};
//backwards compat with old method ".emit({ type: 'something' })"
if(typeof eventName === 'object') {
data = eventName;
eventName = eventName.type;
}
//ensure we are using a real pixi event
if(!data || data.__isEventObject !== true) {
data = new Phaser.Event(this, eventName, data);
}
//iterate the listeners
if(this._listeners && this._listeners[eventName]) {
var listeners = this._listeners[eventName].slice(0),
length = listeners.length,
fn = listeners[0],
i;
for(i = 0; i < length; fn = listeners[++i]) {
//call the event listener
fn.call(this, data);
<|fim▁hole|> }
}
//if "stopPropagation" is called then don't bubble the event
if(data.stopped) {
return this;
}
}
//bubble this event up the scene graph
if(this.parent && this.parent.emit) {
this.parent.emit.call(this.parent, eventName, data);
}
return this;
};
/**
* Register a new EventListener for the given event.
*
* @method Phaser.EventTarget.on
* @alias addEventListener
* @param eventName {String} Name of the event.
* @param callback {Functon} fn Callback function.
*/
obj.on = obj.addEventListener = function on(eventName, fn) {
this._listeners = this._listeners || {};
(this._listeners[eventName] = this._listeners[eventName] || [])
.push(fn);
return this;
};
/**
* Add an EventListener that's only called once.
*
* @method Phaser.EventTarget.once
* @param eventName {String} Name of the event.
* @param callback {Function} Callback function.
*/
obj.once = function once(eventName, fn) {
this._listeners = this._listeners || {};
var self = this;
function onceHandlerWrapper() {
fn.apply(self.off(eventName, onceHandlerWrapper), arguments);
}
onceHandlerWrapper._originalHandler = fn;
return this.on(eventName, onceHandlerWrapper);
};
/**
* Remove event listeners.
*
* @method Phaser.EventTarget.off
* @alias removeEventListener
* @param eventName {String} The event we want to remove.
* @param callback {Function} The listener that we need to find.
*/
obj.off = obj.removeEventListener = function off(eventName, fn) {
this._listeners = this._listeners || {};
if(!this._listeners[eventName])
return this;
var list = this._listeners[eventName],
i = fn ? list.length : 0;
while(i-- > 0) {
if(list[i] === fn || list[i]._originalHandler === fn) {
list.splice(i, 1);
}
}
if(list.length === 0) {
delete this._listeners[eventName];
}
return this;
};
/**
* Remove all listeners or only the listeners for the specified event.
*
* @method Phaser.EventTarget.removeAllListeners
* @param eventName {String} The event you want to remove all listeners for.
*/
obj.removeAllListeners = function removeAllListeners(eventName) {
this._listeners = this._listeners || {};
if(!this._listeners[eventName])
return this;
delete this._listeners[eventName];
return this;
};
}
};
/**
* Creates an homogenous object for tracking events so users can know what to expect.
*
* @class Event
* @extends Object
* @constructor
* @param target {Object} The target object that the event is called on
* @param name {String} The string name of the event that was triggered
* @param data {Object} Arbitrary event data to pass along
*/
Phaser.Event = function(target, name, data) {
//for duck typing in the ".on()" function
this.__isEventObject = true;
/**
* Tracks the state of bubbling propagation. Do not
* set this directly, instead use `event.stopPropagation()`
*
* @property stopped
* @type Boolean
* @private
* @readOnly
*/
this.stopped = false;
/**
* Tracks the state of sibling listener propagation. Do not
* set this directly, instead use `event.stopImmediatePropagation()`
*
* @property stoppedImmediate
* @type Boolean
* @private
* @readOnly
*/
this.stoppedImmediate = false;
/**
* The original target the event triggered on.
*
* @property target
* @type Object
* @readOnly
*/
this.target = target;
/**
* The string name of the event that this represents.
*
* @property type
* @type String
* @readOnly
*/
this.type = name;
/**
* The data that was passed in with this event.
*
* @property data
* @type Object
* @readOnly
*/
this.data = data;
//backwards compat with older version of events
this.content = data;
/**
* The timestamp when the event occurred.
*
* @property timeStamp
* @type Number
* @readOnly
*/
this.timeStamp = Date.now();
};
/**
* Stops the propagation of events up the scene graph (prevents bubbling).
*
* @method Phaser.Event#stopPropagation
*/
Phaser.Event.prototype.stopPropagation = function stopPropagation() {
this.stopped = true;
};
/**
* Stops the propagation of events to sibling listeners (no longer calls any listeners).
*
* @method Phaser.Event#stopImmediatePropagation
*/
Phaser.Event.prototype.stopImmediatePropagation = function stopImmediatePropagation() {
this.stoppedImmediate = true;
};<|fim▁end|> | //if "stopImmediatePropagation" is called, stop calling sibling events
if(data.stoppedImmediate) {
return this;
|
<|file_name|>listadoCooperativa.service.ts<|end_file_name|><|fim▁begin|>import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import "rxjs/add/operator/map";
import {Observable} from "rxjs/Observable";
@Injectable()
export class ListadoCooperativaService {
constructor(private http: Http) {
}
getCooperativas(): Observable<string[]> {
return this.http.get("/cooperativa/cooperativalist")<|fim▁hole|> .map(response => <string[]>response.json());
}
}<|fim▁end|> | |
<|file_name|>viewportimagemap.go<|end_file_name|><|fim▁begin|>package viewer
import (
"fmt"
"image"
"github.com/driusan/de/demodel"
"github.com/driusan/de/renderer"
)
type offsetImageMap struct {
buf *demodel.CharBuffer
visibleViewport image.Rectangle
viewport *Viewport
}
func (v *Viewport) GetImageMap(buf *demodel.CharBuffer, viewport image.Rectangle) demodel.ImageMap {
return &offsetImageMap{buf, viewport, v}
}
func (i *offsetImageMap) At(x, y int) (uint, error) {
if i == nil || i.viewport == nil || i.viewport.Renderer == nil {
return 0, fmt.Errorf("Viewport renderer is nil")
}
switch i.viewport.lineNumberMode {
case NoLineNumbers:<|fim▁hole|> }
return im.At(x, y)
default:
lineNumberOffset := renderer.MonoFontAdvance * 6
if x < lineNumberOffset.Ceil() {
imap := i.viewport.Renderer.GetImageMap(i.buf, i.visibleViewport)
if imap == nil {
return 0, fmt.Errorf("Renderer imagemap is nil")
}
return imap.At(lineNumberOffset.Ceil(), y)
}
return i.viewport.Renderer.GetImageMap(i.buf, i.visibleViewport).At(x-lineNumberOffset.Floor(), y)
}
}
func (i *offsetImageMap) Get(idx uint) (image.Rectangle, error) {
switch i.viewport.lineNumberMode {
case NoLineNumbers:
return i.viewport.Renderer.GetImageMap(i.buf, i.visibleViewport).Get(idx)
default:
lineNumberOffset := renderer.MonoFontAdvance * 6
r, err := i.viewport.Renderer.GetImageMap(i.buf, i.visibleViewport).Get(idx)
r.Min.X += lineNumberOffset.Floor()
r.Max.X += lineNumberOffset.Floor()
return r, err
}
}<|fim▁end|> | im := i.viewport.Renderer.GetImageMap(i.buf, i.visibleViewport)
if im == nil {
return 0, fmt.Errorf("Renderer does not provide an image map.") |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.