prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>main.js<|end_file_name|><|fim▁begin|>import Vue from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
import vuetify from './plugins/vuetify';
import 'roboto-fontface/css/roboto/roboto-fontface.css'
import '@mdi/font/css/materialdesignicons.css'
import VueCompositionApi from "@vue/composition-api";
Vue.use(VueCompositionApi);
Vue.config.productionTip = false
new Vue({
router,
store,
vuetify,
render: h => h(App)<|fim▁hole|><|fim▁end|> | }).$mount('#app') |
<|file_name|>formfield.go<|end_file_name|><|fim▁begin|>package fork
import (
"fmt"
"net/http"
"strconv"
"strings"
)
func NewFieldIndex(s string, i int) *FieldIndex {<|fim▁hole|> return &FieldIndex{N: s, I: i}
}
type FieldIndex struct {
I int
N string
}
type formField struct {
base Form
Index *FieldIndex
Forms []Form
*named
Processor
}
func (f *formField) New(i ...interface{}) Field {
var newfield formField = *f
newfield.named = f.named.Copy()
newfield.SetValidateable(false)
return &newfield
}
func (f *formField) Get() *Value {
return NewValue(f.Forms)
}
func (f *formField) Set(r *http.Request) {
f.Forms = nil
i := f.Filter(f.Name(), r)
f.Index = i.Raw.(*FieldIndex)
for x := 0; x < f.Index.I; x++ {
nf := f.base.New()
renameFormFields(f.name, x, nf)
nf.Process(r)
f.Forms = append(f.Forms, nf)
}
f.SetValidateable(true)
}
func FilterIndex(index string) *FieldIndex {
i, _ := strconv.Atoi(index)
return NewFieldIndex(index, i)
}
func ValidateIndex(f *formField) error {
_, err := strconv.Atoi(f.Index.N)
if err != nil {
return fmt.Errorf("form field index error: %s", err.Error())
}
return nil
}
func formFieldWidget(name string) Widget {
in := strings.Join([]string{
fmt.Sprintf(`<fieldset name="%s">`, name),
fmt.Sprintf(`<input type="hidden" name="%s" `, name),
`value="{{ .Index.N }}"><ul>{{ range $x := .Forms }}`,
`<li>{{ .Render }}</li>{{ end }}</ul></fieldset>`,
}, "")
return NewWidget(in)
}
func renameFormFields(name string, number int, f Form) Form {
for index, field := range f.Fields() {
field.ReName(name, strconv.Itoa(number), field.Name(), strconv.Itoa(index))
}
return f
}
func addForm(name string, number int, form Form) []Form {
var ret []Form
for i := 0; i < number; i++ {
n := form.New()
ret = append(ret, renameFormFields(name, i, n))
}
return ret
}
func FormField(name string, f Form) Field {
return FormsField(name, 1, f)
}
func FormsField(name string, startwith int, start Form) Field {
return &formField{
base: start,
Index: NewFieldIndex(strconv.Itoa(startwith), startwith),
Forms: addForm(name, startwith, start),
named: newnamed(name),
Processor: NewProcessor(
formFieldWidget(name),
NewValidater(ValidateIndex),
NewFilterer(FilterIndex),
),
}
}<|fim▁end|> | |
<|file_name|>.test_particles_resampling.py<|end_file_name|><|fim▁begin|>#coding:utf-8
"""
functionモジュールのparticle_resampling関数をテストする
"""
from functions import particles_resampling
import pfoe
robot1 = pfoe.Robot(sensor=4,choice=3,particle_num=100)
#case1:パーティクルの分布・重みは等分
for i in range(100):
robot1.particles.distribution[i] = i % 5<|fim▁hole|>
robot1.particles = particles_resampling(robot1.particles,5)
print robot1.particles.weight
print robot1.particles.distribution
#case2:パーティクルの分布は等分、重みはイベント0に集中
for i in range(100):
robot1.particles.distribution[i] = i % 5
if i % 5 == 0:
robot1.particles.weight[i] = 1.0 / 20.0
else:
robot1.particles.weight[i] = 0.0
robot1.particles = particles_resampling(robot1.particles,5)
print robot1.particles.weight
print robot1.particles.distribution<|fim▁end|> | robot1.particles.weight[i] = 1.0 / 100.0 |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'metuly.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}),
url(r'', include('meddit.urls')),
)<|fim▁end|> | from django.conf.urls import patterns, include, url |
<|file_name|>base.rs<|end_file_name|><|fim▁begin|>//! WARNING: This file is generated, derived from table system.base, DO NOT EDIT
use chrono::datetime::DateTime;
use chrono::offset::utc::UTC;
use gen::column;
use gen::schema;
use gen::table;
use rustc_serialize::json::Json;<|fim▁hole|>use rustorm::dao::IsDao;
use rustorm::dao::Type;
use rustorm::dao::Value;
use rustorm::query::Operand;
use rustorm::table::Column;
use rustorm::table::IsTable;
use rustorm::table::Table;
use uuid::Uuid;
///
/// Base table contains the creation and modification status of a record
///
#[derive(RustcEncodable)]
#[derive(Debug, Clone)]
pub struct Base {
/// db data type: uuid
pub client_id: Option<Uuid>,
/// default: 'now()'
/// not nullable
/// db data type: timestamp with time zone
pub created: DateTime<UTC>,
/// db data type: uuid
pub created_by: Option<Uuid>,
/// db data type: uuid
pub organization_id: Option<Uuid>,
/// priority of saving data and eviction
/// db data type: double precision
pub priority: Option<f64>,
/// default: 'now()'
/// not nullable
/// db data type: timestamp with time zone
pub updated: DateTime<UTC>,
/// db data type: uuid
pub updated_by: Option<Uuid>,
}
impl IsDao for Base {
fn from_dao(dao: &Dao) -> Self {
Base {
organization_id: dao.get_opt(column::organization_id),
client_id: dao.get_opt(column::client_id),
created: dao.get(column::created),
created_by: dao.get_opt(column::created_by),
updated: dao.get(column::updated),
updated_by: dao.get_opt(column::updated_by),
priority: dao.get_opt(column::priority),
}
}
fn to_dao(&self) -> Dao {
let mut dao = Dao::new();
match self.organization_id {
Some(ref _value) => dao.set(column::organization_id, _value),
None => dao.set_null(column::organization_id)
}
match self.client_id {
Some(ref _value) => dao.set(column::client_id, _value),
None => dao.set_null(column::client_id)
}
dao.set(column::created, &self.created);
match self.created_by {
Some(ref _value) => dao.set(column::created_by, _value),
None => dao.set_null(column::created_by)
}
dao.set(column::updated, &self.updated);
match self.updated_by {
Some(ref _value) => dao.set(column::updated_by, _value),
None => dao.set_null(column::updated_by)
}
match self.priority {
Some(ref _value) => dao.set(column::priority, _value),
None => dao.set_null(column::priority)
}
dao
}
}
impl ToJson for Base {
fn to_json(&self) -> Json {
self.to_dao().to_json()
}
}
impl Default for Base {
fn default() -> Self {
Base{
organization_id: Default::default(),
client_id: Default::default(),
created: UTC::now(),
created_by: Default::default(),
updated: UTC::now(),
updated_by: Default::default(),
priority: Default::default(),
}
}
}
impl IsTable for Base {
fn table() -> Table {
Table {
schema: Some(schema::system.to_owned()),
name: table::base.to_owned(),
parent_table: None,
sub_table: vec![table::record.to_owned(),table::product_availability.to_owned(),table::product_category.to_owned(),table::product_photo.to_owned(),table::product_review.to_owned(),],
comment: Some(r#"Base table contains the creation and modification status of a record"#.to_owned()),
columns: vec![
organization_id(),
client_id(),
created(),
created_by(),
updated(),
updated_by(),
priority(),
],
is_view: false,
}
}
}
// Generated columns for easier development of dynamic queries without sacrificing wrong spelling of column names
pub fn organization_id()->Column{
Column {
table: Some(table::base.to_owned()),
name: column::organization_id.to_owned(),
data_type: Type::Uuid,
db_data_type: "uuid".to_owned(),
is_primary: false, is_unique: false, not_null: false, is_inherited: false,
default: None,
comment: None,
foreign: None,
}
}
pub fn client_id()->Column{
Column {
table: Some(table::base.to_owned()),
name: column::client_id.to_owned(),
data_type: Type::Uuid,
db_data_type: "uuid".to_owned(),
is_primary: false, is_unique: false, not_null: false, is_inherited: false,
default: None,
comment: None,
foreign: None,
}
}
pub fn created()->Column{
Column {
table: Some(table::base.to_owned()),
name: column::created.to_owned(),
data_type: Type::DateTime,
db_data_type: "timestamp with time zone".to_owned(),
is_primary: false, is_unique: false, not_null: true, is_inherited: false,
default: Some(Operand::Value(Value::String("'now()'".to_owned()))),
comment: None,
foreign: None,
}
}
pub fn created_by()->Column{
Column {
table: Some(table::base.to_owned()),
name: column::created_by.to_owned(),
data_type: Type::Uuid,
db_data_type: "uuid".to_owned(),
is_primary: false, is_unique: false, not_null: false, is_inherited: false,
default: None,
comment: None,
foreign: None,
}
}
pub fn updated()->Column{
Column {
table: Some(table::base.to_owned()),
name: column::updated.to_owned(),
data_type: Type::DateTime,
db_data_type: "timestamp with time zone".to_owned(),
is_primary: false, is_unique: false, not_null: true, is_inherited: false,
default: Some(Operand::Value(Value::String("'now()'".to_owned()))),
comment: None,
foreign: None,
}
}
pub fn updated_by()->Column{
Column {
table: Some(table::base.to_owned()),
name: column::updated_by.to_owned(),
data_type: Type::Uuid,
db_data_type: "uuid".to_owned(),
is_primary: false, is_unique: false, not_null: false, is_inherited: false,
default: None,
comment: None,
foreign: None,
}
}
pub fn priority()->Column{
Column {
table: Some(table::base.to_owned()),
name: column::priority.to_owned(),
data_type: Type::F64,
db_data_type: "double precision".to_owned(),
is_primary: false, is_unique: false, not_null: false, is_inherited: false,
default: None,
comment: Some(r#"priority of saving data and eviction"#.to_owned()),
foreign: None,
}
}<|fim▁end|> | use rustc_serialize::json::ToJson;
use rustorm::dao::Dao; |
<|file_name|>shimSetup.ts<|end_file_name|><|fim▁begin|>(global as any).requestAnimationFrame = (callback: any) => {<|fim▁hole|>};<|fim▁end|> | setTimeout(callback, 0); |
<|file_name|>errors.rs<|end_file_name|><|fim▁begin|>#[derive(Debug)]
pub enum MidiError {
<|fim▁hole|> EndOfStream,
}<|fim▁end|> | |
<|file_name|>test_df.py<|end_file_name|><|fim▁begin|>from insights.parsers import df, ParseException
from insights.tests import context_wrap
import pytest
DF_ALP = """
Filesystem 1024-blocks Used Available Capacity Mounted on
/dev/mapper/vg_lxcrhel6sat56-lv_root 98571884 4244032 89313940 5% /
sysfs 0 0 0 - /sys
proc 0 0 0 - /proc
devtmpfs 5988480 0 5988480 0% /dev
securityfs 0 0 0 - /sys/kernel/security
tmpfs 5998736 491660 5507076 9% /dev/shm
devpts 0 0 0 - /dev/pts
tmpfs 5998736 1380 5997356 1% /run
tmpfs 5998736 0 5998736 0% /sys/fs/cgroup
""".strip()
DF_LI = """
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/mapper/vg_lxcrhel6sat56-lv_root
6275072 124955 6150117 2% /
devtmpfs 1497120 532 1496588 1% /dev
tmpfs 1499684 331 1499353 1% /dev/shm
tmpfs 1499684 728 1498956 1% /run
tmpfs 1499684 16 1499668 1% /sys/fs/cgroup
tmpfs 1499684 54 1499630 1% /tmp
/dev/sda2 106954752 298662 106656090 1% /home
/dev/sda1 128016 429 127587 1% /boot
tmpfs 1499684 6 1499678 1% /V M T o o l s
tmpfs 1499684 15 1499669 1% /VM Tools
""".strip()
DF_AL = """
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/mapper/vg_lxcrhel6sat56-lv_root 98571884 4244032 89313940 5% /
sysfs 0 0 0 - /sys
proc 0 0 0 - /proc
devtmpfs 5988480 0 5988480 0% /dev
securityfs 0 0 0 - /sys/kernel/security
tmpfs 5998736 491660 5507076 9% /dev/shm
devpts 0 0 0 - /dev/pts
tmpfs 5998736 1380 5997356 1% /run
tmpfs 5998736 0 5998736 0% /sys/fs/cgroup
""".strip()
def test_df_li():
df_list = df.DiskFree_LI(context_wrap(DF_LI))
assert len(df_list) == 10
assert len(df_list.mounts) == 10
assert len(df_list.filesystems) == 5
assert '/home' in df_list.mounts
r = df.Record(
filesystem='/dev/sda2',
total='106954752',
used='298662',
available='106656090',
capacity='1%',
mounted_on='/home'
)
assert df_list.get_mount('/home') == r
assert '/dev/sda2' in df_list.filesystems
assert len(df_list.get_filesystem('/dev/sda2')) == 1
assert df_list.get_filesystem('/dev/sda2')[0] == r
assert len(df_list.get_filesystem('tmpfs')) == 6
assert df_list.get_mount('/dev').filesystem == 'devtmpfs'
assert df_list.get_mount('/run').total == '1499684'
assert df_list.get_mount('/tmp').used == '54'
assert df_list.get_mount('/boot').available == '127587'
assert df_list.get_filesystem('/dev/sda2')[0].capacity == '1%'
assert df_list.get_filesystem('/dev/sda2')[0].available == '106656090'
assert df_list.get_filesystem('devtmpfs')[0].mounted_on == '/dev'
assert df_list.get_mount('/V M T o o l s').available == '1499678'
assert df_list.get_filesystem('/dev/mapper/vg_lxcrhel6sat56-lv_root')[0].mounted_on == '/'
sorted_mount_names = sorted([
'/', '/dev', '/dev/shm', '/run', '/sys/fs/cgroup', '/tmp', '/home',
'/boot', '/V M T o o l s', '/VM Tools'
])
assert sorted([d.mounted_on for d in df_list]) == sorted_mount_names
assert sorted(df_list.mount_names) == sorted_mount_names
assert sorted(df_list.filesystem_names) == sorted([
'/dev/mapper/vg_lxcrhel6sat56-lv_root', 'devtmpfs', 'tmpfs',
'/dev/sda2', '/dev/sda1'
])
def test_df_alP():
df_list = df.DiskFree_ALP(context_wrap(DF_ALP))
assert len(df_list) == 9
assert len(df_list.mounts) == 9
assert len(df_list.filesystems) == 7
assert '/' in df_list.mounts
r = df.Record(
filesystem='/dev/mapper/vg_lxcrhel6sat56-lv_root',
total='98571884',
used='4244032',
available='89313940',
capacity='5%',
mounted_on='/'
)
assert df_list.get_mount('/') == r
assert '/dev/mapper/vg_lxcrhel6sat56-lv_root' in df_list.filesystems
assert len(df_list.get_filesystem('/dev/mapper/vg_lxcrhel6sat56-lv_root')) == 1
assert df_list.get_filesystem('/dev/mapper/vg_lxcrhel6sat56-lv_root')[0] == r
assert len(df_list.get_filesystem('tmpfs')) == 3
assert df_list.get_mount('/sys').filesystem == 'sysfs'
assert df_list.get_mount('/proc').total == '0'
assert df_list.get_mount('/dev').used == '0'
assert df_list.get_mount('/run').available == '5997356'
assert df_list.get_mount('/sys/fs/cgroup').capacity == '0%'
assert df_list.get_mount('/').filesystem == '/dev/mapper/vg_lxcrhel6sat56-lv_root'
assert df_list.get_mount('/').capacity == '5%'
def test_df_al():
df_list = df.DiskFree_AL(context_wrap(DF_AL))
assert len(df_list) == 9
assert len(df_list.mounts) == 9<|fim▁hole|> assert len(df_list.filesystems) == 7
assert '/' in df_list.mounts
r = df.Record(
filesystem='/dev/mapper/vg_lxcrhel6sat56-lv_root',
total='98571884',
used='4244032',
available='89313940',
capacity='5%',
mounted_on='/'
)
assert df_list.get_mount('/') == r
assert '/dev/mapper/vg_lxcrhel6sat56-lv_root' in df_list.filesystems
assert len(df_list.get_filesystem('/dev/mapper/vg_lxcrhel6sat56-lv_root')) == 1
assert df_list.get_filesystem('/dev/mapper/vg_lxcrhel6sat56-lv_root')[0] == r
assert len(df_list.get_filesystem('tmpfs')) == 3
assert df_list.get_mount('/sys').filesystem == 'sysfs'
assert df_list.get_mount('/proc').total == '0'
assert df_list.get_mount('/dev').used == '0'
assert df_list.get_mount('/run').available == '5997356'
assert df_list.get_mount('/sys/fs/cgroup').capacity == '0%'
assert df_list.get_mount('/').filesystem == '/dev/mapper/vg_lxcrhel6sat56-lv_root'
assert df_list.get_mount('/').capacity == '5%'
DF_AL_BAD = """
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/mapper/vg_lxcrhel6sat56-lv_root 98571884 4244032 89313940 5% /
sysfs 0
"""
def test_df_al_bad():
with pytest.raises(ParseException) as exc:
df_list = df.DiskFree_AL(context_wrap(DF_AL_BAD))
assert len(df_list) == 2
assert 'Could not parse line' in str(exc)<|fim▁end|> | |
<|file_name|>size_of.rs<|end_file_name|><|fim▁begin|><|fim▁hole|> * 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 selectors;
use servo_arc::Arc;
use style;
use style::applicable_declarations::ApplicableDeclarationBlock;
use style::data::{ElementData, ElementStyles};
use style::gecko::selector_parser::{self, SelectorImpl};
use style::properties::ComputedValues;
use style::rule_tree::{RuleNode, StrongRuleNode};
use style::values::computed;
use style::values::specified;
size_of_test!(size_of_selector, selectors::parser::Selector<SelectorImpl>, 8);
size_of_test!(size_of_pseudo_element, selector_parser::PseudoElement, 24);
size_of_test!(size_of_component, selectors::parser::Component<SelectorImpl>, 32);
size_of_test!(size_of_pseudo_class, selector_parser::NonTSPseudoClass, 24);
// The size of this is critical to performance on the bloom-basic microbenchmark.
// When iterating over a large Rule array, we want to be able to fast-reject
// selectors (with the inline hashes) with as few cache misses as possible.
size_of_test!(test_size_of_rule, style::stylist::Rule, 32);
// Large pages generate tens of thousands of ComputedValues.
size_of_test!(test_size_of_cv, ComputedValues, 248);
size_of_test!(test_size_of_option_arc_cv, Option<Arc<ComputedValues>>, 8);
size_of_test!(test_size_of_option_rule_node, Option<StrongRuleNode>, 8);
size_of_test!(test_size_of_element_styles, ElementStyles, 16);
size_of_test!(test_size_of_element_data, ElementData, 24);
size_of_test!(test_size_of_property_declaration, style::properties::PropertyDeclaration, 32);
size_of_test!(test_size_of_application_declaration_block, ApplicableDeclarationBlock, 24);
// FIXME(bholley): This can shrink with a little bit of work.
// See https://github.com/servo/servo/issues/17280
size_of_test!(test_size_of_rule_node, RuleNode, 80);
// This is huge, but we allocate it on the stack and then never move it,
// we only pass `&mut SourcePropertyDeclaration` references around.
size_of_test!(test_size_of_parsed_declaration, style::properties::SourcePropertyDeclaration, 576);
size_of_test!(test_size_of_computed_image, computed::image::Image, 40);
size_of_test!(test_size_of_specified_image, specified::image::Image, 40);
// FIXME(bz): These can shrink if we move the None_ value inside the
// enum instead of paying an extra word for the Either discriminant.
size_of_test!(test_size_of_computed_image_layer, computed::image::ImageLayer,
if cfg!(rustc_has_pr45225) { 40 } else { 48 });
size_of_test!(test_size_of_specified_image_layer, specified::image::ImageLayer,
if cfg!(rustc_has_pr45225) { 40 } else { 48 });<|fim▁end|> | /* This Source Code Form is subject to the terms of the Mozilla Public |
<|file_name|>test_mangaPanda.py<|end_file_name|><|fim▁begin|>from unittest import TestCase
from mangopi.site.mangapanda import MangaPanda
class TestMangaPanda(TestCase):
SERIES = MangaPanda.series('gantz')
CHAPTERS = SERIES.chapters
def test_chapter_count(self):
self.assertEqual(len(TestMangaPanda.SERIES.chapters), 383)
<|fim▁hole|> def test_chapter_pages(self):
self.assertEqual(len(TestMangaPanda.CHAPTERS[0].pages), 43)
def test_for_image_url(self):
url = TestMangaPanda.CHAPTERS[0].pages[0].image.url
self.assertTrue(len(url) > 0)
self.assertEqual(url[:7], 'http://')<|fim▁end|> | def test_chapter_title(self):
self.assertEqual(TestMangaPanda.CHAPTERS[-2].title, 'Lightning Counterstrike')
|
<|file_name|>inline.js<|end_file_name|><|fim▁begin|>// jshint ignore: start
/* eslint-disable */
/**
* WordPress dependencies
*/
const { __ } = wp.i18n;
const { Component, createRef, useMemo, Fragment } = wp.element;
const {
ToggleControl,
withSpokenMessages,
} = wp.components;
const { LEFT, RIGHT, UP, DOWN, BACKSPACE, ENTER, ESCAPE } = wp.keycodes;
const { getRectangleFromRange } = wp.dom;
const { prependHTTP } = wp.url;
const {
create,
insert,
isCollapsed,
applyFormat,
getTextContent,
slice,
} = wp.richText;
const { URLPopover } = wp.blockEditor;
/**
* Internal dependencies
*/
import { createLinkFormat, isValidHref } from './utils';
import PositionedAtSelection from './positioned-at-selection';
import LinkEditor from './link-editor';
import LinkViewer from './link-viewer';
const stopKeyPropagation = ( event ) => event.stopPropagation();
function isShowingInput( props, state ) {
return props.addingLink || state.editLink;
}
const URLPopoverAtLink = ( { isActive, addingLink, value, resetOnMount, ...props } ) => {
const anchorRect = useMemo( () => {
const selection = window.getSelection();
const range = selection.rangeCount > 0 ? selection.getRangeAt( 0 ) : null;
if ( ! range ) {
return;
}
if ( addingLink ) {
return getRectangleFromRange( range );
}
let element = range.startContainer;
// If the caret is right before the element, select the next element.
element = element.nextElementSibling || element;
while ( element.nodeType !== window.Node.ELEMENT_NODE ) {
element = element.parentNode;
}
const closest = element.closest( 'a' );
if ( closest ) {
return closest.getBoundingClientRect();
}
}, [ isActive, addingLink, value.start, value.end ] );
if ( ! anchorRect ) {
return null;
}
resetOnMount( anchorRect );
return <URLPopover anchorRect={ anchorRect } { ...props } />;
};
class InlineLinkUI extends Component {
constructor() {
super( ...arguments );
this.editLink = this.editLink.bind( this );
this.submitLink = this.submitLink.bind( this );
this.onKeyDown = this.onKeyDown.bind( this );
this.onChangeInputValue = this.onChangeInputValue.bind( this );
this.setLinkTarget = this.setLinkTarget.bind( this );
this.setNoFollow = this.setNoFollow.bind( this );
this.setSponsored = this.setSponsored.bind( this );
this.onFocusOutside = this.onFocusOutside.bind( this );
this.resetState = this.resetState.bind( this );
this.autocompleteRef = createRef();
this.resetOnMount = this.resetOnMount.bind( this );
this.state = {
opensInNewWindow: false,
noFollow: false,
sponsored: false,
inputValue: '',
anchorRect: false,
};
}
static getDerivedStateFromProps( props, state ) {
const { activeAttributes: { url, target, rel } } = props;
const opensInNewWindow = target === '_blank';
if ( ! isShowingInput( props, state ) ) {
if ( url !== state.inputValue ) {
return { inputValue: url };
}
if ( opensInNewWindow !== state.opensInNewWindow ) {
return { opensInNewWindow };
}
if ( typeof rel === 'string' ) {
const noFollow = rel.split( ' ' ).includes( 'nofollow' );
const sponsored = rel.split( ' ' ).includes( 'sponsored' );
if ( noFollow !== state.noFollow ) {
return { noFollow };
}
if ( sponsored !== state.sponsored ) {
return { sponsored };
}
}
}
return null;
}
onKeyDown( event ) {
if ( [ LEFT, DOWN, RIGHT, UP, BACKSPACE, ENTER ].indexOf( event.keyCode ) > -1 ) {
// Stop the key event from propagating up to ObserveTyping.startTypingInTextField.
event.stopPropagation();
}
if ( [ ESCAPE ].indexOf( event.keyCode ) > -1 ) {
this.resetState();
}
}<|fim▁hole|> }
setLinkTarget( opensInNewWindow ) {
const { activeAttributes: { url = '' }, value, onChange } = this.props;
this.setState( { opensInNewWindow } );
// Apply now if URL is not being edited.
if ( ! isShowingInput( this.props, this.state ) ) {
const selectedText = getTextContent( slice( value ) );
onChange( applyFormat( value, createLinkFormat( {
url,
opensInNewWindow,
noFollow: this.state.noFollow,
sponsored: this.state.sponsored,
text: selectedText,
} ) ) );
}
}
setNoFollow( noFollow ) {
const { activeAttributes: { url = '' }, value, onChange } = this.props;
this.setState( { noFollow } );
// Apply now if URL is not being edited.
if ( ! isShowingInput( this.props, this.state ) ) {
const selectedText = getTextContent( slice( value ) );
onChange( applyFormat( value, createLinkFormat( {
url,
opensInNewWindow: this.state.opensInNewWindow,
noFollow,
sponsored: this.state.sponsored,
text: selectedText,
} ) ) );
}
}
setSponsored( sponsored ) {
const { activeAttributes: { url = '' }, value, onChange } = this.props;
this.setState( { sponsored } );
// Apply now if URL is not being edited.
if ( ! isShowingInput( this.props, this.state ) ) {
const selectedText = getTextContent( slice( value ) );
onChange( applyFormat( value, createLinkFormat( {
url,
opensInNewWindow: this.state.opensInNewWindow,
noFollow: this.state.noFollow,
sponsored,
text: selectedText,
} ) ) );
}
}
editLink( event ) {
this.setState( { editLink: true } );
event.preventDefault();
}
submitLink( event ) {
const { isActive, value, onChange, speak } = this.props;
const { inputValue, opensInNewWindow, noFollow, sponsored } = this.state;
const url = prependHTTP( inputValue );
const selectedText = getTextContent( slice( value ) );
const format = createLinkFormat( {
url,
opensInNewWindow,
noFollow,
sponsored,
text: selectedText,
} );
event.preventDefault();
if ( isCollapsed( value ) && ! isActive ) {
const toInsert = applyFormat( create( { text: url } ), format, 0, url.length );
onChange( insert( value, toInsert ) );
} else {
onChange( applyFormat( value, format ) );
}
this.resetState();
if ( ! isValidHref( url ) ) {
speak( __( 'Warning: the link has been inserted but could have errors. Please test it.', 'all-in-one-seo-pack' ), 'assertive' );
} else if ( isActive ) {
speak( __( 'Link edited.', 'all-in-one-seo-pack' ), 'assertive' );
} else {
speak( __( 'Link inserted.', 'all-in-one-seo-pack' ), 'assertive' );
}
}
onFocusOutside() {
// The autocomplete suggestions list renders in a separate popover (in a portal),
// so onClickOutside fails to detect that a click on a suggestion occured in the
// LinkContainer. Detect clicks on autocomplete suggestions using a ref here, and
// return to avoid the popover being closed.
const autocompleteElement = this.autocompleteRef.current;
if ( autocompleteElement && autocompleteElement.contains( event.target ) ) {
return;
}
this.resetState();
}
resetState() {
this.props.stopAddingLink();
this.setState( { editLink: false } );
}
resetOnMount( anchorRect ) {
if ( this.state.anchorRect !== anchorRect ) {
this.setState( { opensInNewWindow: false, noFollow: false, sponsored: false, anchorRect: anchorRect } );
}
}
render() {
const { isActive, activeAttributes: { url, target, rel }, addingLink, value } = this.props;
if ( ! isActive && ! addingLink ) {
return null;
}
const { inputValue, opensInNewWindow, noFollow, sponsored } = this.state;
const showInput = isShowingInput( this.props, this.state );
if ( ! opensInNewWindow && target === '_blank' ) {
this.setState( { opensInNewWindow: true } );
}
if ( typeof rel === 'string' ) {
const relNoFollow = rel.split( ' ' ).includes( 'nofollow' );
const relSponsored = rel.split( ' ' ).includes( 'sponsored' );
if ( relNoFollow !== noFollow ) {
this.setState( { noFollow: relNoFollow } );
}
if ( relSponsored !== sponsored ) {
this.setState( { sponsored: relSponsored } );
}
}
return (
<PositionedAtSelection
key={ `${ value.start }${ value.end }` /* Used to force rerender on selection change */ }
>
<URLPopoverAtLink
resetOnMount={ this.resetOnMount }
value={ value }
isActive={ isActive }
addingLink={ addingLink }
onFocusOutside={ this.onFocusOutside }
onClose={ () => {
if ( ! inputValue ) {
this.resetState();
}
} }
focusOnMount={ showInput ? 'firstElement' : false }
renderSettings={ () => (
<Fragment>
<ToggleControl
label={ __( 'Open in New Tab', 'all-in-one-seo-pack' ) }
checked={ opensInNewWindow }
onChange={ this.setLinkTarget }
/>
<ToggleControl
label={ __( 'Add "nofollow" to link', 'all-in-one-seo-pack' ) }
checked={ noFollow }
onChange={ this.setNoFollow }
/>
<ToggleControl
label={ __( 'Add "sponsored" to link', 'all-in-one-seo-pack' ) }
checked={ sponsored }
onChange={ this.setSponsored }
/>
</Fragment>
) }
>
{ showInput ? (
<LinkEditor
className="editor-format-toolbar__link-container-content block-editor-format-toolbar__link-container-content"
value={ inputValue }
onChangeInputValue={ this.onChangeInputValue }
onKeyDown={ this.onKeyDown }
onKeyPress={ stopKeyPropagation }
onSubmit={ this.submitLink }
autocompleteRef={ this.autocompleteRef }
/>
) : (
<LinkViewer
className="editor-format-toolbar__link-container-content block-editor-format-toolbar__link-container-content"
onKeyPress={ stopKeyPropagation }
url={ url }
onEditLinkClick={ this.editLink }
linkClassName={ isValidHref( prependHTTP( url ) ) ? undefined : 'has-invalid-link' }
/>
) }
</URLPopoverAtLink>
</PositionedAtSelection>
);
}
}
export default withSpokenMessages( InlineLinkUI );<|fim▁end|> |
onChangeInputValue( inputValue ) {
this.setState( { inputValue } ); |
<|file_name|>59275500.jsonp.js<|end_file_name|><|fim▁begin|><|fim▁hole|>jsonp({"cep":"59275500","cidade":"Ipiranga","uf":"RN","estado":"Rio Grande do Norte"});<|fim▁end|> | |
<|file_name|>helpers.go<|end_file_name|><|fim▁begin|>package stripedash
<|fim▁hole|> "strconv"
)
func Uint64ToDollars(i uint64) string {
d := []byte(strconv.FormatUint(i, 10))
// Cents only
if len(d) < 3 {
return fmt.Sprintf("0.%s", d)
}
// Dollars and cents
centStart := len(d) - 2
dollars := d[0:centStart]
cents := d[centStart:len(d)]
return fmt.Sprintf("%s.%s", string(dollars), string(cents))
}<|fim▁end|> | import (
"fmt" |
<|file_name|>repository.ts<|end_file_name|><|fim▁begin|>import { OcticonSymbol } from '../octicons'
import { Repository } from '../../models/repository'
import { CloningRepository } from '../../models/cloning-repository'
/**
* Determine the octicon to display for a given repository.
*/
export function iconForRepository(repository: Repository | CloningRepository) {
if (repository instanceof CloningRepository) {
return OcticonSymbol.desktopDownload
}
const gitHubRepo = repository.gitHubRepository
if (!gitHubRepo) {
return OcticonSymbol.deviceDesktop
}
<|fim▁hole|> if (gitHubRepo.private) {
return OcticonSymbol.lock
}
if (gitHubRepo.fork) {
return OcticonSymbol.repoForked
}
return OcticonSymbol.repo
}<|fim▁end|> | |
<|file_name|>coverageinfo.rs<|end_file_name|><|fim▁begin|>use crate::traits::*;
use rustc_middle::mir::coverage::*;
use rustc_middle::mir::Coverage;
use rustc_middle::mir::SourceScope;
use super::FunctionCx;
impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
pub fn codegen_coverage(&self, bx: &mut Bx, coverage: Coverage, scope: SourceScope) {
// Determine the instance that coverage data was originally generated for.
let scope_data = &self.mir.source_scopes[scope];
let instance = if let Some((inlined_instance, _)) = scope_data.inlined {
self.monomorphize(inlined_instance)
} else if let Some(inlined_scope) = scope_data.inlined_parent_scope {
self.monomorphize(self.mir.source_scopes[inlined_scope].inlined.unwrap().0)
} else {
self.instance
};
<|fim▁hole|> // If `set_function_source_hash()` returned true, the coverage map is enabled,
// so continue adding the counter.
if let Some(code_region) = code_region {
// Note: Some counters do not have code regions, but may still be referenced
// from expressions. In that case, don't add the counter to the coverage map,
// but do inject the counter intrinsic.
bx.add_coverage_counter(instance, id, code_region);
}
let coverageinfo = bx.tcx().coverageinfo(instance.def);
let fn_name = bx.get_pgo_func_name_var(instance);
let hash = bx.const_u64(function_source_hash);
let num_counters = bx.const_u32(coverageinfo.num_counters);
let index = bx.const_u32(id.zero_based_index());
debug!(
"codegen intrinsic instrprof.increment(fn_name={:?}, hash={:?}, num_counters={:?}, index={:?})",
fn_name, hash, num_counters, index,
);
bx.instrprof_increment(fn_name, hash, num_counters, index);
}
}
CoverageKind::Expression { id, lhs, op, rhs } => {
bx.add_coverage_counter_expression(instance, id, lhs, op, rhs, code_region);
}
CoverageKind::Unreachable => {
bx.add_coverage_unreachable(
instance,
code_region.expect("unreachable regions always have code regions"),
);
}
}
}
}<|fim▁end|> | let Coverage { kind, code_region } = coverage;
match kind {
CoverageKind::Counter { function_source_hash, id } => {
if bx.set_function_source_hash(instance, function_source_hash) { |
<|file_name|>language.ts<|end_file_name|><|fim▁begin|><|fim▁hole|>export type Language = 'fr' | 'en' | 'de' | 'ja' | 'ko' | 'zh' | 'ru';<|fim▁end|> | |
<|file_name|>ambig3.C<|end_file_name|><|fim▁begin|>// { dg-do assemble }
// Copyright (C) 2000 Free Software Foundation, Inc.
// Contributed by Nathan Sidwell 23 June 2000 <[email protected]><|fim▁hole|>
// Origin GNATS bug report 69 from Glenn Ammons <[email protected]>
//
// A base which derives a virtual base hides declarations in the virtual base,
// even if that virtual base is accessible via another path [10.2]/6. Make
// sure that non-virtual bases of the virtual base are also hidden, not matter
// what order bases are declared in.
struct A {int a;};
struct B : A {};
struct L1 : virtual B { int a; };
struct L2 : virtual A { int a; };
struct R1 : virtual B {};
struct R2 : virtual A {};
struct C1 : R1, L1 {};
struct C2 : R2, L2 {};
struct D1 : L1, R1 {};
struct D2 : L2, R2 {};
void fn (C1 *c1, D1 *d1, C2 *c2, D2 *d2)
{
c1->a = 1;
d1->a = 1;
c2->a = 1;
d2->a = 1;
}<|fim▁end|> | |
<|file_name|>test_qgsdefaultvalue.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsDefaultValue.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Matthias Kuhn'
__date__ = '26.9.2017'
__copyright__ = 'Copyright 2017, The QGIS Project'
import qgis # NOQA
from qgis.core import (QgsDefaultValue)
from qgis.testing import unittest
class TestQgsRasterColorRampShader(unittest.TestCase):
def testValid(self):
self.assertFalse(QgsDefaultValue())<|fim▁hole|>
def setGetExpression(self):
value = QgsDefaultValue('abc', False)
self.assertEqual(value.expression(), 'abc')
value.setExpression('def')
self.assertEqual(value.expression(), 'def')
def setGetApplyOnUpdate(self):
value = QgsDefaultValue('abc', False)
self.assertEqual(value.applyOnUpdate(), False)
value.setApplyOnUpdate(True)
self.assertEqual(value.applyOnUpdate(), True)
if __name__ == '__main__':
unittest.main()<|fim▁end|> | self.assertTrue(QgsDefaultValue('test'))
self.assertTrue(QgsDefaultValue('abc', True))
self.assertTrue(QgsDefaultValue('abc', False)) |
<|file_name|>battle_service.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from kubb_match.data.models import GridPosition, Round, Game
class BattleService(object):
def __init__(self):
pass
def create_games(self, positions):
games = []
nr = int(len(positions) / 5)
field = 1
for row in ('A', 'B', 'C', 'D', 'E'):
for x in range(1, nr + 1, 2):
print(row + str(x))
print(row + str(x + 1))
team1 = next((pos for pos in positions if pos.position == row + str(x)))
team2 = next((pos for pos in positions if pos.position == row + str(x + 1)))
game = Game(team1_id=team1.team_id, team2_id=team2.team_id, field=field)
games.append(game)
field += 1
return games
def calculate_next_round(self, round, final=False):
positions = self.calculate_positions(round)
new_round = Round()
new_round.positions = positions
if not final:
new_round.games = self.create_games(positions)
return new_round
def calculate_positions(self, round):
positions = []
losers = []
games = round.games
games.sort(key=lambda x: x.field, reverse=False)
for game in games:
if game.winner == game.team1_id:
grid_pos = self.position_winner(round, positions, game.team1_id, True)
positions.append(grid_pos)
losers.append(game.team2_id)
else:
grid_pos = self.position_winner(round, positions, game.team2_id, False)
positions.append(grid_pos)
losers.append(game.team1_id)
for loser_id in losers:
grid_pos = self.position_loser(round, positions, loser_id)
positions.append(grid_pos)
return positions
def position_winner(self, round, positions, winner_id, pos_1):
pos = next((pos for pos in round.positions if pos.team_id == winner_id))
key = pos.position
if key[0] == 'A':
key = key
row = key[0]
else:
row = self.move_row_up(key[0])
pos = int(key[1])<|fim▁hole|> key = row + str(pos)
#if key in [pos.position for pos in positions]:
# pos = pos + 1 if pos_1 else pos - 1
# key = row + str(pos)
pos = int(key[1])
while key in [pos.position for pos in positions]:
pos += 1
if pos > 8:
pos -= 8
key = row + str(pos)
grid_pos = GridPosition(position=key, team_id=winner_id)
return grid_pos
def position_loser(self, round, positions, loser_id):
pos = next((pos for pos in round.positions if pos.team_id == loser_id))
key = pos.position
if key[0] == 'E':
row = 'E'
pos = int(key[1])
while key in [pos.position for pos in positions]:
pos += 1
if pos > 8:
pos -= 8
key = row + str(pos)
else:
row = self.move_row_down(key[0])
pos = int(key[1]) + 2
if pos > 8:
pos -= 8
key = row + str(pos)
while key in [pos.position for pos in positions]:
pos += 1
if pos > 8:
pos -= 8
key = row + str(pos)
grid_pos = GridPosition(position=key, team_id=loser_id)
return grid_pos
@staticmethod
def move_row_up(row):
return chr(ord(row) - 1)
@staticmethod
def move_row_down(row):
return chr(ord(row) + 1)<|fim▁end|> | |
<|file_name|>matching.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/. */
//! High-level interface to CSS selector matching.
#![allow(unsafe_code)]
#![deny(missing_docs)]
use context::{ElementCascadeInputs, QuirksMode, SelectorFlagsMap};
use context::{SharedStyleContext, StyleContext};
use data::ElementData;
use dom::TElement;
use invalidation::element::restyle_hints::RestyleHint;
use properties::ComputedValues;
use rule_tree::{CascadeLevel, StrongRuleNode};
use selector_parser::{PseudoElement, RestyleDamage};
use selectors::matching::ElementSelectorFlags;
use servo_arc::{Arc, ArcBorrow};
use style_resolver::ResolvedElementStyles;
use traversal_flags::TraversalFlags;
/// Represents the result of comparing an element's old and new style.
#[derive(Debug)]
pub struct StyleDifference {
/// The resulting damage.
pub damage: RestyleDamage,
/// Whether any styles changed.
pub change: StyleChange,
}
impl StyleDifference {
/// Creates a new `StyleDifference`.
pub fn new(damage: RestyleDamage, change: StyleChange) -> Self {
StyleDifference {
change: change,
damage: damage,
}
}
}
/// Represents whether or not the style of an element has changed.
#[derive(Clone, Copy, Debug)]
pub enum StyleChange {
/// The style hasn't changed.
Unchanged,
/// The style has changed.
Changed {
/// Whether only reset structs changed.
reset_only: bool,
},
}
/// Whether or not newly computed values for an element need to be cascade
/// to children.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum ChildCascadeRequirement {
/// Old and new computed values were the same, or we otherwise know that
/// we won't bother recomputing style for children, so we can skip cascading
/// the new values into child elements.
CanSkipCascade = 0,
/// The same as `MustCascadeChildren`, but we only need to actually
/// recascade if the child inherits any explicit reset style.
MustCascadeChildrenIfInheritResetStyle = 1,
/// Old and new computed values were different, so we must cascade the
/// new values to children.
MustCascadeChildren = 2,
/// The same as `MustCascadeChildren`, but for the entire subtree. This is
/// used to handle root font-size updates needing to recascade the whole
/// document.
MustCascadeDescendants = 3,
}
impl ChildCascadeRequirement {
/// Whether we can unconditionally skip the cascade.
pub fn can_skip_cascade(&self) -> bool {
matches!(*self, ChildCascadeRequirement::CanSkipCascade)
}
}
/// Determines which styles are being cascaded currently.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CascadeVisitedMode {
/// Cascade the regular, unvisited styles.
Unvisited,
/// Cascade the styles used when an element's relevant link is visited. A
/// "relevant link" is the element being matched if it is a link or the
/// nearest ancestor link.
Visited,
}
impl CascadeVisitedMode {
/// Returns whether the cascade should filter to only visited dependent
/// properties based on the cascade mode.
pub fn visited_dependent_only(&self) -> bool {
*self == CascadeVisitedMode::Visited
}
}
trait PrivateMatchMethods: TElement {
/// If there is no transition rule in the ComputedValues, it returns None.
#[cfg(feature = "gecko")]
fn get_after_change_style(
&self,
context: &mut StyleContext<Self>,
primary_style: &Arc<ComputedValues>
) -> Option<Arc<ComputedValues>> {
use context::CascadeInputs;
use style_resolver::{PseudoElementResolution, StyleResolverForElement};
use stylist::RuleInclusion;
let rule_node = primary_style.rules();
let without_transition_rules =
context.shared.stylist.rule_tree().remove_transition_rule_if_applicable(rule_node);
if without_transition_rules == *rule_node {
// We don't have transition rule in this case, so return None to let
// the caller use the original ComputedValues.
return None;
}
// FIXME(bug 868975): We probably need to transition visited style as
// well.
let inputs =
CascadeInputs {
rules: Some(without_transition_rules),
visited_rules: primary_style.visited_rules().cloned()
};
// Actually `PseudoElementResolution` doesn't really matter.
let style =
StyleResolverForElement::new(*self, context, RuleInclusion::All, PseudoElementResolution::IfApplicable)
.cascade_style_and_visited_with_default_parents(inputs);
Some(style.0)
}
#[cfg(feature = "gecko")]
fn needs_animations_update(
&self,
context: &mut StyleContext<Self>,
old_values: Option<&Arc<ComputedValues>>,
new_values: &ComputedValues,
) -> bool {
use properties::longhands::display::computed_value as display;
let new_box_style = new_values.get_box();
let has_new_animation_style = new_box_style.specifies_animations();
let has_animations = self.has_css_animations();
old_values.map_or(has_new_animation_style, |old| {
let old_box_style = old.get_box();
let old_display_style = old_box_style.clone_display();
let new_display_style = new_box_style.clone_display();
// If the traverse is triggered by CSS rule changes, we need to
// try to update all CSS animations on the element if the element
// has or will have CSS animation style regardless of whether the
// animation is running or not.
// TODO: We should check which @keyframes changed/added/deleted
// and update only animations corresponding to those @keyframes.
(context.shared.traversal_flags.contains(TraversalFlags::ForCSSRuleChanges) &&
(has_new_animation_style || has_animations)) ||
!old_box_style.animations_equals(new_box_style) ||
(old_display_style == display::T::none &&
new_display_style != display::T::none &&
has_new_animation_style) ||
(old_display_style != display::T::none &&
new_display_style == display::T::none &&
has_animations)
})
}
/// Create a SequentialTask for resolving descendants in a SMIL display property
/// animation if the display property changed from none.
#[cfg(feature = "gecko")]
fn handle_display_change_for_smil_if_needed(
&self,
context: &mut StyleContext<Self>,
old_values: Option<&ComputedValues>,
new_values: &ComputedValues,
restyle_hints: RestyleHint
) {
use context::PostAnimationTasks;
use properties::longhands::display::computed_value as display;
if !restyle_hints.intersects(RestyleHint::RESTYLE_SMIL) {
return;
}
let display_changed_from_none = old_values.map_or(false, |old| {
let old_display_style = old.get_box().clone_display();
let new_display_style = new_values.get_box().clone_display();
old_display_style == display::T::none &&
new_display_style != display::T::none
});
if display_changed_from_none {
// When display value is changed from none to other, we need to
// traverse descendant elements in a subsequent normal
// traversal (we can't traverse them in this animation-only restyle
// since we have no way to know whether the decendants
// need to be traversed at the beginning of the animation-only
// restyle).
let task = ::context::SequentialTask::process_post_animation(
*self,
PostAnimationTasks::DISPLAY_CHANGED_FROM_NONE_FOR_SMIL,
);
context.thread_local.tasks.push(task);
}
}
#[cfg(feature = "gecko")]
fn process_animations(&self,
context: &mut StyleContext<Self>,
old_values: &mut Option<Arc<ComputedValues>>,
new_values: &mut Arc<ComputedValues>,
restyle_hint: RestyleHint,
important_rules_changed: bool) {
use context::UpdateAnimationsTasks;
if context.shared.traversal_flags.for_animation_only() {
self.handle_display_change_for_smil_if_needed(
context,
old_values.as_ref().map(|v| &**v),
new_values,
restyle_hint,
);
return;
}
// Bug 868975: These steps should examine and update the visited styles
// in addition to the unvisited styles.
let mut tasks = UpdateAnimationsTasks::empty();
if self.needs_animations_update(context, old_values.as_ref(), new_values) {
tasks.insert(UpdateAnimationsTasks::CSS_ANIMATIONS);
}
let before_change_style = if self.might_need_transitions_update(old_values.as_ref().map(|s| &**s),
new_values) {
let after_change_style = if self.has_css_transitions() {
self.get_after_change_style(context, new_values)
} else {
None
};
// In order to avoid creating a SequentialTask for transitions which
// may not be updated, we check it per property to make sure Gecko
// side will really update transition.
let needs_transitions_update = {
// We borrow new_values here, so need to add a scope to make
// sure we release it before assigning a new value to it.
let after_change_style_ref =
after_change_style.as_ref().unwrap_or(&new_values);
self.needs_transitions_update(old_values.as_ref().unwrap(),
after_change_style_ref)
};
if needs_transitions_update {
if let Some(values_without_transitions) = after_change_style {
*new_values = values_without_transitions;
}
tasks.insert(UpdateAnimationsTasks::CSS_TRANSITIONS);
// We need to clone old_values into SequentialTask, so we can use it later.
old_values.clone()
} else {
None
}
} else {
None
};
if self.has_animations() {
tasks.insert(UpdateAnimationsTasks::EFFECT_PROPERTIES);
if important_rules_changed {
tasks.insert(UpdateAnimationsTasks::CASCADE_RESULTS);
}
}
if !tasks.is_empty() {
let task = ::context::SequentialTask::update_animations(*self,
before_change_style,
tasks);
context.thread_local.tasks.push(task);
}
}
#[cfg(feature = "servo")]
fn process_animations(&self,
context: &mut StyleContext<Self>,
old_values: &mut Option<Arc<ComputedValues>>,
new_values: &mut Arc<ComputedValues>,
_restyle_hint: RestyleHint,
_important_rules_changed: bool) {
use animation;
use dom::TNode;
let possibly_expired_animations =
&mut context.thread_local.current_element_info.as_mut().unwrap()
.possibly_expired_animations;
let shared_context = context.shared;
if let Some(ref mut old) = *old_values {
self.update_animations_for_cascade(shared_context, old,
possibly_expired_animations,
&context.thread_local.font_metrics_provider);
}
let new_animations_sender = &context.thread_local.new_animations_sender;
let this_opaque = self.as_node().opaque();
// Trigger any present animations if necessary.
animation::maybe_start_animations(&shared_context,
new_animations_sender,
this_opaque, &new_values);
// Trigger transitions if necessary. This will reset `new_values` back
// to its old value if it did trigger a transition.
if let Some(ref values) = *old_values {
animation::start_transitions_if_applicable(
new_animations_sender,
this_opaque,
&**values,
new_values,
&shared_context.timer,
&possibly_expired_animations);
}
}
/// Computes and applies non-redundant damage.
fn accumulate_damage_for(
&self,
shared_context: &SharedStyleContext,
skip_applying_damage: bool,
damage: &mut RestyleDamage,
old_values: &ComputedValues,
new_values: &ComputedValues,
pseudo: Option<&PseudoElement>,
) -> ChildCascadeRequirement {
debug!("accumulate_damage_for: {:?}", self);
// Don't accumulate damage if we're in a forgetful traversal.
if shared_context.traversal_flags.contains(TraversalFlags::Forgetful) {
debug!(" > forgetful traversal");
return ChildCascadeRequirement::MustCascadeChildren;
}
let difference =
self.compute_style_difference(old_values, new_values, pseudo);
if !skip_applying_damage {
*damage |= difference.damage;
}
debug!(" > style difference: {:?}", difference);
// We need to cascade the children in order to ensure the correct
// propagation of inherited computed value flags.
if old_values.flags.inherited() != new_values.flags.inherited() {
debug!(" > flags changed: {:?} != {:?}", old_values.flags, new_values.flags);
return ChildCascadeRequirement::MustCascadeChildren;
}
match difference.change {
StyleChange::Unchanged => ChildCascadeRequirement::CanSkipCascade,
StyleChange::Changed { reset_only } => {
// If inherited properties changed, the best we can do is
// cascade the children.
if !reset_only {
return ChildCascadeRequirement::MustCascadeChildren
}
let old_display = old_values.get_box().clone_display();
let new_display = new_values.get_box().clone_display();
// Blockification of children may depend on our display value,
// so we need to actually do the recascade. We could potentially
// do better, but it doesn't seem worth it.
if old_display.is_item_container() != new_display.is_item_container() {
return ChildCascadeRequirement::MustCascadeChildren
}
// Line break suppression may also be affected if the display
// type changes from ruby to non-ruby.
#[cfg(feature = "gecko")]
{
if old_display.is_ruby_type() != new_display.is_ruby_type() {
return ChildCascadeRequirement::MustCascadeChildren
}
}
// Children with justify-items: auto may depend on our
// justify-items property value.
//
// Similarly, we could potentially do better, but this really
// seems not common enough to care about.
#[cfg(feature = "gecko")]
{
use values::specified::align::AlignFlags;
let old_justify_items =
old_values.get_position().clone_justify_items();
let new_justify_items =
new_values.get_position().clone_justify_items();
let was_legacy_justify_items =
old_justify_items.computed.0.contains(AlignFlags::LEGACY);
let is_legacy_justify_items =
new_justify_items.computed.0.contains(AlignFlags::LEGACY);
if is_legacy_justify_items != was_legacy_justify_items {
return ChildCascadeRequirement::MustCascadeChildren;
}
if was_legacy_justify_items &&
old_justify_items.computed != new_justify_items.computed {
return ChildCascadeRequirement::MustCascadeChildren;
}
}
// We could prove that, if our children don't inherit reset
// properties, we can stop the cascade.
ChildCascadeRequirement::MustCascadeChildrenIfInheritResetStyle
}
}
}
#[cfg(feature = "servo")]
fn update_animations_for_cascade(&self,
context: &SharedStyleContext,
style: &mut Arc<ComputedValues>,
possibly_expired_animations: &mut Vec<::animation::PropertyAnimation>,
font_metrics: &::font_metrics::FontMetricsProvider) {
use animation::{self, Animation};
use dom::TNode;
// Finish any expired transitions.
let this_opaque = self.as_node().opaque();
animation::complete_expired_transitions(this_opaque, style, context);
// Merge any running transitions into the current style, and cancel them.
let had_running_animations = context.running_animations
.read()
.get(&this_opaque)
.is_some();
if had_running_animations {
let mut all_running_animations = context.running_animations.write();
for running_animation in all_running_animations.get_mut(&this_opaque).unwrap() {
// This shouldn't happen frequently, but under some
// circumstances mainly huge load or debug builds, the
// constellation might be delayed in sending the
// `TickAllAnimations` message to layout.
//
// Thus, we can't assume all the animations have been already
// updated by layout, because other restyle due to script might
// be triggered by layout before the animation tick.
//
// See #12171 and the associated PR for an example where this
// happened while debugging other release panic.
if !running_animation.is_expired() {
animation::update_style_for_animation(context,
running_animation,
style,
font_metrics);
if let Animation::Transition(_, _, ref frame, _) = *running_animation {
possibly_expired_animations.push(frame.property_animation.clone())
}
}
}
}
}
}
impl<E: TElement> PrivateMatchMethods for E {}
/// The public API that elements expose for selector matching.
pub trait MatchMethods : TElement {
/// Returns the closest parent element that doesn't have a display: contents
/// style (and thus generates a box).
///
/// This is needed to correctly handle blockification of flex and grid
/// items.
///
/// Returns itself if the element has no parent. In practice this doesn't
/// happen because the root element is blockified per spec, but it could
/// happen if we decide to not blockify for roots of disconnected subtrees,
/// which is a kind of dubious beahavior.
fn layout_parent(&self) -> Self {
let mut current = self.clone();
loop {
current = match current.traversal_parent() {
Some(el) => el,
None => return current,
};
let is_display_contents =
current.borrow_data().unwrap().styles.primary().is_display_contents();
if !is_display_contents {
return current;
}
}
}
/// Updates the styles with the new ones, diffs them, and stores the restyle
/// damage.
fn finish_restyle(
&self,
context: &mut StyleContext<Self>,
data: &mut ElementData,
mut new_styles: ResolvedElementStyles,
important_rules_changed: bool,
) -> ChildCascadeRequirement {
use dom::TNode;
use std::cmp;
self.process_animations(
context,
&mut data.styles.primary,
&mut new_styles.primary.style.0,
data.hint,
important_rules_changed,
);
// First of all, update the styles.
let old_styles = data.set_styles(new_styles);
// Propagate the "can be fragmented" bit. It would be nice to<|fim▁hole|> let layout_parent =
self.inheritance_parent().map(|e| e.layout_parent());
let layout_parent_data =
layout_parent.as_ref().and_then(|e| e.borrow_data());
let layout_parent_style =
layout_parent_data.as_ref().map(|d| d.styles.primary());
if let Some(ref p) = layout_parent_style {
let can_be_fragmented =
p.is_multicol() ||
layout_parent.as_ref().unwrap().as_node().can_be_fragmented();
unsafe { self.as_node().set_can_be_fragmented(can_be_fragmented); }
}
}
let new_primary_style = data.styles.primary.as_ref().unwrap();
let mut cascade_requirement = ChildCascadeRequirement::CanSkipCascade;
if self.is_root() && !self.is_native_anonymous() {
let device = context.shared.stylist.device();
let new_font_size = new_primary_style.get_font().clone_font_size();
if old_styles.primary.as_ref().map_or(true, |s| s.get_font().clone_font_size() != new_font_size) {
debug_assert!(self.owner_doc_matches_for_testing(device));
device.set_root_font_size(new_font_size.size());
// If the root font-size changed since last time, and something
// in the document did use rem units, ensure we recascade the
// entire tree.
if device.used_root_font_size() {
cascade_requirement = ChildCascadeRequirement::MustCascadeDescendants;
}
}
}
if context.shared.stylist.quirks_mode() == QuirksMode::Quirks {
if self.is_html_document_body_element() {
// NOTE(emilio): We _could_ handle dynamic changes to it if it
// changes and before we reach our children the cascade stops,
// but we don't track right now whether we use the document body
// color, and nobody else handles that properly anyway.
let device = context.shared.stylist.device();
// Needed for the "inherit from body" quirk.
let text_color = new_primary_style.get_color().clone_color();
device.set_body_text_color(text_color);
}
}
// Don't accumulate damage if we're in a forgetful traversal.
if context.shared.traversal_flags.contains(TraversalFlags::Forgetful) {
return ChildCascadeRequirement::MustCascadeChildren;
}
// Also, don't do anything if there was no style.
let old_primary_style = match old_styles.primary {
Some(s) => s,
None => return ChildCascadeRequirement::MustCascadeChildren,
};
cascade_requirement = cmp::max(
cascade_requirement,
self.accumulate_damage_for(
context.shared,
data.skip_applying_damage(),
&mut data.damage,
&old_primary_style,
new_primary_style,
None,
)
);
if data.styles.pseudos.is_empty() && old_styles.pseudos.is_empty() {
// This is the common case; no need to examine pseudos here.
return cascade_requirement;
}
let pseudo_styles =
old_styles.pseudos.as_array().iter().zip(
data.styles.pseudos.as_array().iter());
for (i, (old, new)) in pseudo_styles.enumerate() {
match (old, new) {
(&Some(ref old), &Some(ref new)) => {
self.accumulate_damage_for(
context.shared,
data.skip_applying_damage(),
&mut data.damage,
old,
new,
Some(&PseudoElement::from_eager_index(i)),
);
}
(&None, &None) => {},
_ => {
// It's possible that we're switching from not having
// ::before/::after at all to having styles for them but not
// actually having a useful pseudo-element. Check for that
// case.
let pseudo = PseudoElement::from_eager_index(i);
let new_pseudo_should_exist =
new.as_ref().map_or(false,
|s| pseudo.should_exist(s));
let old_pseudo_should_exist =
old.as_ref().map_or(false,
|s| pseudo.should_exist(s));
if new_pseudo_should_exist != old_pseudo_should_exist {
data.damage |= RestyleDamage::reconstruct();
return cascade_requirement;
}
}
}
}
cascade_requirement
}
/// Applies selector flags to an element, deferring mutations of the parent
/// until after the traversal.
///
/// TODO(emilio): This is somewhat inefficient, because it doesn't take
/// advantage of us knowing that the traversal is sequential.
fn apply_selector_flags(&self,
map: &mut SelectorFlagsMap<Self>,
element: &Self,
flags: ElementSelectorFlags) {
// Handle flags that apply to the element.
let self_flags = flags.for_self();
if !self_flags.is_empty() {
if element == self {
// If this is the element we're styling, we have exclusive
// access to the element, and thus it's fine inserting them,
// even from the worker.
unsafe { element.set_selector_flags(self_flags); }
} else {
// Otherwise, this element is an ancestor of the current element
// we're styling, and thus multiple children could write to it
// if we did from here.
//
// Instead, we can read them, and post them if necessary as a
// sequential task in order for them to be processed later.
if !element.has_selector_flags(self_flags) {
map.insert_flags(*element, self_flags);
}
}
}
// Handle flags that apply to the parent.
let parent_flags = flags.for_parent();
if !parent_flags.is_empty() {
if let Some(p) = element.parent_element() {
if !p.has_selector_flags(parent_flags) {
map.insert_flags(p, parent_flags);
}
}
}
}
/// Updates the rule nodes without re-running selector matching, using just
/// the rule tree.
///
/// Returns true if an !important rule was replaced.
fn replace_rules(
&self,
replacements: RestyleHint,
context: &mut StyleContext<Self>,
cascade_inputs: &mut ElementCascadeInputs,
) -> bool {
let mut result = false;
result |= self.replace_rules_internal(
replacements,
context,
CascadeVisitedMode::Unvisited,
cascade_inputs,
);
result |= self.replace_rules_internal(
replacements,
context,
CascadeVisitedMode::Visited,
cascade_inputs
);
result
}
/// Updates the rule nodes without re-running selector matching, using just
/// the rule tree, for a specific visited mode.
///
/// Returns true if an !important rule was replaced.
fn replace_rules_internal(
&self,
replacements: RestyleHint,
context: &mut StyleContext<Self>,
cascade_visited: CascadeVisitedMode,
cascade_inputs: &mut ElementCascadeInputs,
) -> bool {
use properties::PropertyDeclarationBlock;
use shared_lock::Locked;
debug_assert!(replacements.intersects(RestyleHint::replacements()) &&
(replacements & !RestyleHint::replacements()).is_empty());
let stylist = &context.shared.stylist;
let guards = &context.shared.guards;
let primary_rules =
match cascade_visited {
CascadeVisitedMode::Unvisited => cascade_inputs.primary.rules.as_mut(),
CascadeVisitedMode::Visited => cascade_inputs.primary.visited_rules.as_mut(),
};
let primary_rules = match primary_rules {
Some(r) => r,
None => return false,
};
let replace_rule_node = |level: CascadeLevel,
pdb: Option<ArcBorrow<Locked<PropertyDeclarationBlock>>>,
path: &mut StrongRuleNode| -> bool {
let mut important_rules_changed = false;
let new_node = stylist.rule_tree()
.update_rule_at_level(level,
pdb,
path,
guards,
&mut important_rules_changed);
if let Some(n) = new_node {
*path = n;
}
important_rules_changed
};
if !context.shared.traversal_flags.for_animation_only() {
let mut result = false;
if replacements.contains(RestyleHint::RESTYLE_STYLE_ATTRIBUTE) {
let style_attribute = self.style_attribute();
result |= replace_rule_node(CascadeLevel::StyleAttributeNormal,
style_attribute,
primary_rules);
result |= replace_rule_node(CascadeLevel::StyleAttributeImportant,
style_attribute,
primary_rules);
// FIXME(emilio): Still a hack!
self.unset_dirty_style_attribute();
}
return result;
}
// Animation restyle hints are processed prior to other restyle
// hints in the animation-only traversal.
//
// Non-animation restyle hints will be processed in a subsequent
// normal traversal.
if replacements.intersects(RestyleHint::for_animations()) {
debug_assert!(context.shared.traversal_flags.for_animation_only());
if replacements.contains(RestyleHint::RESTYLE_SMIL) {
replace_rule_node(CascadeLevel::SMILOverride,
self.get_smil_override(),
primary_rules);
}
let replace_rule_node_for_animation = |level: CascadeLevel,
primary_rules: &mut StrongRuleNode| {
let animation_rule = self.get_animation_rule_by_cascade(level);
replace_rule_node(level,
animation_rule.as_ref().map(|a| a.borrow_arc()),
primary_rules);
};
// Apply Transition rules and Animation rules if the corresponding restyle hint
// is contained.
if replacements.contains(RestyleHint::RESTYLE_CSS_TRANSITIONS) {
replace_rule_node_for_animation(CascadeLevel::Transitions,
primary_rules);
}
if replacements.contains(RestyleHint::RESTYLE_CSS_ANIMATIONS) {
replace_rule_node_for_animation(CascadeLevel::Animations,
primary_rules);
}
}
false
}
/// Given the old and new style of this element, and whether it's a
/// pseudo-element, compute the restyle damage used to determine which
/// kind of layout or painting operations we'll need.
fn compute_style_difference(
&self,
old_values: &ComputedValues,
new_values: &ComputedValues,
pseudo: Option<&PseudoElement>
) -> StyleDifference {
debug_assert!(pseudo.map_or(true, |p| p.is_eager()));
RestyleDamage::compute_style_difference(old_values, new_values)
}
}
impl<E: TElement> MatchMethods for E {}<|fim▁end|> | // encapsulate this better.
if cfg!(feature = "servo") { |
<|file_name|>launcher.go<|end_file_name|><|fim▁begin|>// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2017 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* 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 userd
import (
"bytes"
"fmt"
"net/url"
"os"
"os/exec"
"regexp"
"syscall"
"time"
"github.com/godbus/dbus"
"github.com/snapcore/snapd/i18n"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/osutil/sys"
"github.com/snapcore/snapd/release"
"github.com/snapcore/snapd/strutil"
"github.com/snapcore/snapd/usersession/userd/ui"
)
const launcherIntrospectionXML = `
<interface name="org.freedesktop.DBus.Peer">
<method name='Ping'>
</method>
<method name='GetMachineId'>
<arg type='s' name='machine_uuid' direction='out'/>
</method>
</interface>
<interface name='io.snapcraft.Launcher'>
<method name='OpenURL'>
<arg type='s' name='url' direction='in'/>
</method>
<method name="OpenFile">
<arg type="s" name="parent_window" direction="in"/>
<arg type="h" name="fd" direction="in"/>
</method>
</interface>`
// allowedURLSchemes are those that can be passed to xdg-open so that it may
// launch the handler for the url scheme on behalf of the snap (and therefore
// outside of the calling snap's confinement). Historically we've been
// conservative about adding url schemes but the thinking was refined in
// https://github.com/snapcore/snapd/pull/7731#pullrequestreview-362900171
//
// The current criteria for adding url schemes is:
// * understanding and documenting the scheme in this file
// * the scheme itself does not cause xdg-open to open files (eg, file:// or
// matching '^[[:alpha:]+\.\-]+:' (from xdg-open source))
// * verifying that the recipient of the url (ie, what xdg-open calls) won't
// process file paths/etc that can be leveraged to break out of the sandbox
// (but understanding how the url can drive the recipient application is
// important)
//
// This code uses golang's net/url.Parse() which will help ensure the url is
// ok before passing to xdg-open. xdg-open itself properly quotes the url so
// shell metacharacters are blocked.
var (
allowedURLSchemes = []string{
// apt: the scheme allows specifying a package for xdg-open to pass to an
// apt-handling application, like gnome-software, apturl, etc which are all
// protected by policykit
// - scheme: apt:<name of package>
// - https://github.com/snapcore/snapd/pull/7731
"apt",
// help: the scheme allows for specifying a help URL. This code ensures that
// the url is parseable
// - scheme: help://topic
// - https://github.com/snapcore/snapd/pull/6493
"help",
// http/https: the scheme allows specifying a web URL. This code ensures that<|fim▁hole|> "https",
// mailto: the scheme allows for specifying an email address
// - scheme: mailto:[email protected]
"mailto",
// msteams: the scheme is a thin wrapper around https.
// - scheme: msteams:...
// - https://github.com/snapcore/snapd/pull/8761
"msteams",
// TODO: document slack URL scheme.
"slack",
// snap: the scheme allows specifying a package for xdg-open to pass to a
// snap-handling installer application, like snap-store, etc which are
// protected by policykit/snap login
// - https://github.com/snapcore/snapd/pull/5181
"snap",
// zoommtg: the scheme is a modified web url scheme
// - scheme: https://medium.com/zoom-developer-blog/zoom-url-schemes-748b95fd9205
// (eg, zoommtg://zoom.us/...)
// - https://github.com/snapcore/snapd/pull/8304
"zoommtg",
// zoomphonecall: another zoom URL scheme, for dialing phone numbers
// - https://github.com/snapcore/snapd/pull/8910
"zoomphonecall",
// zoomus: alternative name for zoommtg
// - https://github.com/snapcore/snapd/pull/8910
"zoomus",
}
)
// Launcher implements the 'io.snapcraft.Launcher' DBus interface.
type Launcher struct {
conn *dbus.Conn
}
// Interface returns the name of the interface this object implements
func (s *Launcher) Interface() string {
return "io.snapcraft.Launcher"
}
// ObjectPath returns the path that the object is exported as
func (s *Launcher) ObjectPath() dbus.ObjectPath {
return "/io/snapcraft/Launcher"
}
// IntrospectionData gives the XML formatted introspection description
// of the DBus service.
func (s *Launcher) IntrospectionData() string {
return launcherIntrospectionXML
}
func makeAccessDeniedError(err error) *dbus.Error {
return &dbus.Error{
Name: "org.freedesktop.DBus.Error.AccessDenied",
Body: []interface{}{err.Error()},
}
}
func checkOnClassic() *dbus.Error {
if !release.OnClassic {
return makeAccessDeniedError(fmt.Errorf("not supported on Ubuntu Core"))
}
return nil
}
// see https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#file-naming
var validDesktopFileName = regexp.MustCompile(`^[A-Za-z-_][A-Za-z0-9-_]*(\.[A-Za-z-_][A-Za-z0-9-_]*)*\.desktop$`)
func schemeHasHandler(scheme string) (bool, error) {
cmd := exec.Command("xdg-mime", "query", "default", "x-scheme-handler/"+scheme)
// TODO: consider using Output() in case xdg-mime starts logging to
// stderr
out, err := cmd.CombinedOutput()
if err != nil {
return false, osutil.OutputErr(out, err)
}
out = bytes.TrimSpace(out)
// if the output is a valid desktop file we have a handler for the given
// scheme
return validDesktopFileName.Match(out), nil
}
// OpenURL implements the 'OpenURL' method of the 'io.snapcraft.Launcher'
// DBus interface. Before the provided url is passed to xdg-open the scheme is
// validated against a list of allowed schemes. All other schemes are denied.
func (s *Launcher) OpenURL(addr string, sender dbus.Sender) *dbus.Error {
logger.Debugf("open url: %q", addr)
if err := checkOnClassic(); err != nil {
return err
}
u, err := url.Parse(addr)
if err != nil {
return &dbus.ErrMsgInvalidArg
}
if u.Scheme == "" {
return makeAccessDeniedError(fmt.Errorf("cannot open URL without a scheme"))
}
isAllowed := strutil.ListContains(allowedURLSchemes, u.Scheme)
if !isAllowed {
// scheme is not listed in our allowed schemes list, perform
// fallback and check whether the local system has a handler for
// it
isAllowed, err = schemeHasHandler(u.Scheme)
if err != nil {
logger.Noticef("cannot obtain scheme handler for %q: %v", u.Scheme, err)
}
}
if !isAllowed {
return makeAccessDeniedError(fmt.Errorf("Supplied URL scheme %q is not allowed", u.Scheme))
}
if err := exec.Command("xdg-open", addr).Run(); err != nil {
return dbus.MakeFailedError(fmt.Errorf("cannot open supplied URL"))
}
return nil
}
// fdToFilename determines the path associated with an open file descriptor.
//
// The file descriptor cannot be opened using O_PATH and must refer to
// a regular file or to a directory. The symlink at /proc/self/fd/<fd>
// is read to determine the filename. The descriptor is also fstat'ed
// and the resulting device number and inode number are compared to
// stat on the path determined earlier. The numbers must match.
func fdToFilename(fd int) (string, error) {
flags, err := sys.FcntlGetFl(fd)
if err != nil {
return "", err
}
// File descriptors opened with O_PATH do not imply access to
// the file in question.
if flags&sys.O_PATH != 0 {
return "", fmt.Errorf("cannot use file descriptors opened using O_PATH")
}
// Determine the file name associated with the passed file descriptor.
filename, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", fd))
if err != nil {
return "", err
}
var fileStat, fdStat syscall.Stat_t
if err := syscall.Stat(filename, &fileStat); err != nil {
return "", err
}
if err := syscall.Fstat(fd, &fdStat); err != nil {
return "", err
}
// Sanity check to ensure we've got the right file
if fdStat.Dev != fileStat.Dev || fdStat.Ino != fileStat.Ino {
return "", fmt.Errorf("cannot determine file name")
}
fileType := fileStat.Mode & syscall.S_IFMT
if fileType != syscall.S_IFREG && fileType != syscall.S_IFDIR {
return "", fmt.Errorf("cannot open anything other than regular files or directories")
}
return filename, nil
}
func (s *Launcher) OpenFile(parentWindow string, clientFd dbus.UnixFD, sender dbus.Sender) *dbus.Error {
// godbus transfers ownership of this file descriptor to us
fd := int(clientFd)
defer syscall.Close(fd)
if err := checkOnClassic(); err != nil {
return err
}
filename, err := fdToFilename(fd)
if err != nil {
return dbus.MakeFailedError(err)
}
snap, err := snapFromSender(s.conn, sender)
if err != nil {
return dbus.MakeFailedError(err)
}
dialog, err := ui.New()
if err != nil {
return dbus.MakeFailedError(err)
}
answeredYes := dialog.YesNo(
i18n.G("Allow opening file?"),
fmt.Sprintf(i18n.G("Allow snap %q to open file %q?"), snap, filename),
&ui.DialogOptions{
Timeout: 5 * 60 * time.Second,
Footer: i18n.G("This dialog will close automatically after 5 minutes of inactivity."),
},
)
if !answeredYes {
return dbus.MakeFailedError(fmt.Errorf("permission denied"))
}
if err = exec.Command("xdg-open", filename).Run(); err != nil {
return dbus.MakeFailedError(fmt.Errorf("cannot open supplied URL"))
}
return nil
}<|fim▁end|> | // the url is parseable
// - scheme: http(s)://example.com
"http", |
<|file_name|>decode_test.rs<|end_file_name|><|fim▁begin|>#[cfg(test)]
mod tests {
use crate::arch::arch_tests::common::tests::setup_tests;
use crate::utils::bit_utils::*;
#[test]
fn test_decode_absolute() {
let mut cpu = setup_tests();
cpu.memory.store(cpu.registers.pc + 1, 0xcd);
cpu.memory.store(cpu.registers.pc + 2, 0xab);
let (addr, ilen) = decode_absolute!(&cpu);
assert_eq!(ilen, 3);
assert_eq!(addr, 0xabcd);
}
#[test]
fn test_decode_immediate() {
let mut cpu = setup_tests();
cpu.memory.store(cpu.registers.pc + 1, 0xcd);
let (addr, ilen) = decode_immediate!(&cpu);
assert_eq!(ilen, 2);
assert_eq!(addr, 0xcd);
}
#[test]
fn test_decode_zeropage() {
let mut cpu = setup_tests();
cpu.memory.store(cpu.registers.pc + 1, 0xcd);
let (addr, ilen) = decode_zeropage!(&cpu);
assert_eq!(ilen, 2);
assert_eq!(addr, 0xcd);
}
#[test]
fn test_decode_absolute_indexed() {
let mut cpu = setup_tests();
cpu.memory.store(cpu.registers.pc + 1, 0xcd);
cpu.memory.store(cpu.registers.pc + 2, 0xab);
let (addr, ilen) = decode_absolute_indexed!(&cpu, 0x10);
assert_eq!(ilen, 3);
assert_eq!(addr, 0xabdd);
}
#[test]
fn test_decode_absolute_indexed_wrapping() {
let mut cpu = setup_tests();
cpu.memory.store(cpu.registers.pc + 1, 0xfe);
cpu.memory.store(cpu.registers.pc + 2, 0xff);
let (addr, ilen) = decode_absolute_indexed!(&cpu, 0x10);
assert_eq!(ilen, 3);
assert_eq!(addr, 0x000e);
}
#[test]
fn test_decode_zeropage_indexed() {
let mut cpu = setup_tests();
cpu.memory.store(cpu.registers.pc + 1, 0xcd);
let (addr, ilen) = decode_zeropage_indexed!(&cpu, 0x10);
assert_eq!(ilen, 2);
assert_eq!(addr, 0xdd);
}
#[test]
fn test_decode_zeropage_indexed_wrapping() {
let mut cpu = setup_tests();
cpu.memory.store(cpu.registers.pc + 1, 0xfe);
let (addr, ilen) = decode_zeropage_indexed!(&cpu, 0x10);
assert_eq!(ilen, 2);
assert_eq!(addr, 0x0e);
}
#[test]
fn test_decode_indexed_indirect() {
let mut cpu = setup_tests();
cpu.memory.store(cpu.registers.pc + 1, 0xcd);
cpu.memory.store(0xdd, 0xcd);
cpu.memory.store(0xde, 0xab);
cpu.registers.x_reg = 0x10;
let (addr, ilen) = decode_indexed_indirect!(&cpu);
assert_eq!(ilen, 2);
assert_eq!(addr, 0xabcd);
}
#[test]
fn test_decode_indexed_indirect_wrapping() {
let mut cpu = setup_tests();
cpu.memory.store(cpu.registers.pc + 1, 0xff);
cpu.memory.store(0x0f, 0xcd);
cpu.memory.store(0x10, 0xab);
cpu.registers.x_reg = 0x10;
let (addr, ilen) = decode_indexed_indirect!(&cpu);
assert_eq!(ilen, 2);
assert_eq!(addr, 0xabcd);
}
#[test]
fn test_decode_indirect_indexed() {
let mut cpu = setup_tests();
cpu.memory.store(cpu.registers.pc + 1, 0xcd);
cpu.memory.store(0xcd, 0xcd);
cpu.memory.store(0xce, 0xab);
cpu.registers.y_reg = 0x10;
let (addr, ilen) = decode_indirect_indexed!(&cpu);
assert_eq!(ilen, 2);
assert_eq!(addr, 0xabdd);
}
<|fim▁hole|> #[test]
fn test_decode_indirect_indexed_wrapping() {
let mut cpu = setup_tests();
cpu.memory.store(cpu.registers.pc + 1, 0xcd);
cpu.memory.store(0xcd, 0xfe);
cpu.memory.store(0xce, 0xff);
cpu.registers.y_reg = 0x10;
let (addr, ilen) = decode_indirect_indexed!(&cpu);
assert_eq!(ilen, 2);
assert_eq!(addr, 0x000e);
}
}<|fim▁end|> | |
<|file_name|>analysis.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""This module contains some functions for EM analysis.
"""
__author__ = 'Wenzhi Mao'
__all__ = ['genPvalue', 'calcPcutoff', 'showPcutoff', 'transCylinder',
'showMRCConnection', 'showMRCConnectionEach', 'gaussian3D']
def interpolationball(matrix, index, step, r, **kwargs):
"""Interpolation the value by the radius(ball).
The Inverse distance weighting is used to weight each value."""
from numpy import array, arange, floor, ceil
position = index * step
w = []
v = []
for i in arange(ceil(index[0] - (r / step[0])) // 1, floor(index[0] + (r / step[0])) // 1 + 1):
for j in arange(ceil(index[1] - (r / step[1])) // 1, floor(index[1] + (r / step[1])) // 1 + 1):
for k in arange(ceil(index[2] - (r / step[2])) // 1, floor(index[2] + (r / step[2])) // 1 + 1):
if (((index[0] - i) * step[0]) ** 2 + ((index[1] - j) * step[1]) ** 2 + ((index[2] - k) * step[2]) ** 2) <= r ** 2:
w.append(1.0 / ((((index[0] - i) * step[0]) ** 2 + (
(index[1] - j) * step[1]) ** 2 + ((index[2] - k) * step[2]) ** 2) ** 2) ** .5)
v.append(matrix[i, j, k])
w = array(w)
v = array(v)
w = w / w.sum()
return (w * v).sum()
def interpolationcube(m, p, way, *kwargs):
"""Interpolation the value by the smallest box.
The Inverse distance weighting or Trilinear interpolation is
used to weight each value."""
from numpy import array
if way == 'idw':
tt = array([[[0, 0], [0, 0]], [[0, 0], [0, 0]]], dtype=float)
tt[0, :, :] += p[0] ** 2
tt[1, :, :] += (1 - p[0]) ** 2
tt[:, 0, :] += p[1] ** 2
tt[:, 1, :] += (1 - p[1]) ** 2
tt[:, :, 0] += p[2] ** 2
tt[:, :, 1] += (1 - p[2]) ** 2
tt = tt ** .5
tt = 1. / tt
tt = tt / tt.sum()
elif way == 'interpolation':
tt = array([[[1, 1], [1, 1]], [[1, 1], [1, 1]]], dtype=float)
tt[0, :, :] *= 1 - p[0]
tt[1, :, :] *= p[0]
tt[:, 0, :] *= 1 - p[1]
tt[:, 1, :] *= p[1]
tt[:, :, 0] *= 1 - p[2]
tt[:, :, 1] *= p[2]
if m.shape != (2, 2, 2):
return -999999999999
else:
return (tt * m).sum()
def genPvalue(
pdb, mrc, sample=None, method=('cube', 'interpolation'), sampleradius=3.0,
assumenorm=False, **kwargs):
"""This function assign p-value for pdb structure in mrc. sample is used to get the population values.
`method` must be a tuple or list.
There are 2 methods now: `cube` and `ball`.
For the `cube` method, you should provide either ('cube','interpolation') or ('cube','idw').
`idw` stand for `Inverse distance weighting`, and it is the default option.
For the `ball` method, you should provide the radius(A) like ('ball',3).
`sample` should be a `prody.AtomGroup` or a `numpy` n*3 array or `None` to indicate all data to sample.
`assumenorm` is set to be `False` in default which will get the sample p-value. If it is set
to `True`, the p-value will be the norm-p-value.
The p-value will be set to the beta in the pdb.
"""
from ..IO.output import printError, printInfo
from .mrc import MRC as MRCclass
from ..Application.algorithm import binarySearch
from prody import AtomGroup as pdbclass
from prody.atomic.selection import Selection as selectionclass
from numpy import ndarray, zeros_like, array, floor, ceil, rint
from scipy.stats import norm
if isinstance(method, (tuple, list)):
if len(method) == 0:
printError("The method is not valid.")
return None
if method[0].lower() == 'cube':
if len(method) == 1:
way = 'idw'
method = 'cube'
elif method[1].lower() in ['interpolation', 'idw']:
way = method[1].lower()
method = 'cube'
else:
printError("The method[1] is not valid.")
printError(
"Only 'idw' or 'interpolation' supported for 'cube'.")
return None
elif method[0].lower() == 'ball':
if len(method) < 2:
printError("The radius must provide for the `ball` method.")
try:
way = float(eval(str(method[1])))
except:
printError(
"Only numbers are support as the second option for `ball`.")
return None
if way <= 0:
printError("Radius must be positive.")
return None
else:
method = 'ball'
elif isinstance(method, (str)):
if method.lower() == 'cube':
method = 'cube'
way = 'idw'
else:
printError("Only `cube` support no option format.")
return None
else:
printError("The method must be tuple or list")
return None
if not isinstance(mrc, MRCclass):
printError("Only mbio.MRC class supported for `mrc`.")
return None
if not isinstance(pdb, (pdbclass, selectionclass)):
printError("Only prody.AtomGroup class supported for `pdb`.")
return None
if type(sample) == type(None):
sample = None
elif isinstance(sample, ndarray):
if not (sample.shape == (3,) or (len(sample.shape) == 2 and sample.shape[1] == 3)):
printError("The sample coordinates must has 3 columns.")
return None
if sample.shape == (3,):
sample = array([sample])
elif isinstance(sample, pdbclass):
sample = sample.getCoords()
printInfo("Getting the sample set.")
mark = zeros_like(mrc.data)
grid = array(mrc.getGridCoords())
gridstart = array([grid[0, 0], grid[1, 0], grid[2, 0]])
step = mrc.getGridSteps()
if type(sample) == type(None):
findset = mrc.data.flatten()
else:
tempindex = array(
rint(array(((sample - grid[:, 0]) / step), dtype=float)), dtype=int)
ballindex = ([], [], [])
for i in xrange(int(floor(-sampleradius / step[0])), int(ceil(sampleradius / step[0]) + 1)):
for j in xrange(int(floor(-sampleradius / step[1])), int(ceil(sampleradius / step[1]) + 1)):
for k in xrange(int(floor(-sampleradius / step[2])), int(ceil(sampleradius / step[2]) + 1)):
if (i * step[0]) ** 2 + (j * step[1]) ** 2 + (k * step[2]) ** 2 <= sampleradius ** 2:
ballindex[0].append(i)
ballindex[1].append(j)
ballindex[2].append(k)
ballindex = [array(i, dtype=int) for i in ballindex]
k = array([[len(grid[0])], [len(grid[1])], [len(grid[2])]])
for i in xrange(len(sample)):
t = array([ballindex[0] + tempindex[i][0], ballindex[1] +
tempindex[i][1], ballindex[2] + tempindex[i][2]])
t = t[:, (t >= 0).all(0) & (t < k).all()]
mark[(t[0], t[1], t[2])] = 1
findset = mrc.data[mark != 0]
printInfo("Sorting the sample set.")
findset.sort(kind='quicksort')
findsetlength = len(findset)
if assumenorm:
mu = findset.mean()
sigma = (
((findset - findset.mean()) ** 2).sum() / (findsetlength - 1)) ** .5
else:
mu = sigma = 0.
printInfo("Interpolating the data and assigning p-value.")
beta = pdb.getBetas()
coor = pdb.getCoords()
if method == 'ball':
index = (coor - gridstart) / step
for i in xrange(len(coor)):
beta[i] = interpolationball(mrc.data, index[i], step, r=way)
if assumenorm:
beta[i] = norm.cdf(-(beta[i] - mu) / sigma)
else:
beta[i] = 1. - \
binarySearch(findset, beta[i]) * 1.0 / findsetlength
elif method == 'cube':
index = (coor - gridstart) // step
for i in xrange(len(coor)):
beta[i] = interpolationcube(mrc.data[index[i][0]:index[i][
0] + 2, index[i][1]:index[i][1] + 2, index[i][2]:index[i][2] + 2], coor[i] % array(step) / array(step), way)
if assumenorm:
beta[i] = norm.cdf(-(beta[i] - mu) / sigma)
else:
beta[i] = 1. - \
binarySearch(findset, beta[i]) * 1.0 / findsetlength
pdb.setBetas(beta)
return pdb
def chainsort(x, y):
"""Chain id sort function. A-Z then number."""
if x == y:
return cmp(0, 0)
elif x.isdigit() == y.isdigit() == True:
return cmp(float(x), float(y))
elif x.isdigit() == y.isdigit() == False:
return cmp(x, y)
elif x.isdigit():
return cmp(2, 1)
else:
return cmp(1, 2)
def calcPcutoff(data, scale=5.0, **kwargs):
"""This is a function to calculate the cutoff for high p-values.
`data` could be a `prody.AtomGroup` with p-values in the Beta, the
backbone average is calculated to perform analysis. It could also be raw
number array.
A linear regression is performed by the first half data and the sigma
is calculated.
Cutoff is set to be the first one accepted by `scale`*sigma in the
tail of data.
We suggest the cutoff is set for each chain. You need select atom and
then use this function."""
from ..IO.output import printError
from prody import AtomGroup as pdbclass
from prody.atomic.selection import Selection as selectionclass
from numpy import ndarray, array, arange
if isinstance(data, (pdbclass, selectionclass)):
data = [i for i in data.getHierView().iterResidues()]
# data.sort(cmp=lambda x,y:chainsort(x.getChid(),y.getChid()) if
# x.getChid()!=y.getChid() else cmp(x.getResnum(),y.getResnum()))
data = array([i.select('backbone').getBetas().mean() for i in data])
data.sort()
elif isinstance(data, ndarray):
data.sort()
else:
printError(
"The data format is not supported.(`prody.AtomGroup` or `numpy.ndarray`)")
return None
index = arange(len(data))
firsthalfdata = array(data[:len(data) // 2])
firsthalfindex = arange(len(firsthalfdata))
n = len(firsthalfdata)
# Regression the line
beta1 = ((firsthalfindex * firsthalfdata).sum() - n * firsthalfindex.mean() * firsthalfdata.mean()) / \
((firsthalfindex * firsthalfindex).sum() - n *
firsthalfindex.mean() * firsthalfindex.mean())
beta0 = firsthalfdata.mean() - beta1 * firsthalfindex.mean()
# Determine the RMSE
rmse = (
((firsthalfindex * beta1 + beta0 - firsthalfdata) ** 2).sum() / (n - 1)) ** .5
# Test the second half and get cutoff
tvalue = abs(index * beta1 + beta0 - data)
tbigset = (tvalue <= scale * rmse).nonzero()[0]
return data[max(tbigset)]
def showPcutoff(data, plot, scale=5.0, color=None, detail=False, **kwargs):
"""This is a function to plot the p-value cutoff.
`data` must be a `prody.AtomGroup` with p-values in the Beta, the
backbone average is calculated to perform analysis.
`color` could set to draw in specific color.
`detail` could be used to plot more detail information.
1 to plot the error bar. Provide color list.
2 to also plot sidechain information. Provide 2 colors.
A linear regression is performed by the first half data and the sigma
is calculated.
Cutoff is set to be the first one accepted by `scale`*sigma in the
tail of data.
We suggest the cutoff is set for each chain. You need select atom and
then use this function."""
from ..IO.output import printError, printInfo
from prody import AtomGroup as pdbclass
from prody.atomic.selection import Selection as selectionclass
from matplotlib.axes import Axes
from numpy import ndarray, array, arange
if isinstance(data, (pdbclass, selectionclass)):
data = [i for i in data.getHierView().iterResidues()]
data.sort(cmp=lambda x, y: chainsort(x.getChid(), y.getChid()) if x.getChid(
) != y.getChid() else cmp(x.getResnum(), y.getResnum()))
labelindex = array([i.getResnum() for i in data])
else:
printError("The data format is not supported.(`prody.AtomGroup`)")
return None
data1 = array([i.select('backbone').getBetas().mean() for i in data])
data1.sort()
index = arange(len(data1))
firsthalfdata = array(data1[:len(data1) // 2])
firsthalfindex = arange(len(firsthalfdata))
n = len(firsthalfdata)
# Regression the line
beta1 = ((firsthalfindex * firsthalfdata).sum() - n * firsthalfindex.mean() * firsthalfdata.mean()) / \
((firsthalfindex * firsthalfindex).sum() - n *
firsthalfindex.mean() * firsthalfindex.mean())
beta0 = firsthalfdata.mean() - beta1 * firsthalfindex.mean()
# Determine the RMSE
rmse = (
((firsthalfindex * beta1 + beta0 - firsthalfdata) ** 2).sum() / (n - 1)) ** .5
# Test the second half and get cutoff
tvalue = abs(index * beta1 + beta0 - data1)
tbigset = (tvalue <= scale * rmse).nonzero()[0]
cutoff = data1[max(tbigset)]
if isinstance(plot, Axes):
if detail <= 0:
if type(color) != type(None):
plot.plot(labelindex, array(
[i.select('backbone').getBetas().mean() for i in data]), '-', c=color, zorder=10)
else:
plot.plot(labelindex, array(
[i.select('backbone').getBetas().mean() for i in data]), '-', zorder=10)
plot.plot(
list(plot.get_xlim()), [cutoff, cutoff], '--', c='grey', alpha=0.8, zorder=5)
dd = array([i.select('backbone').getBetas().mean() for i in data])
for i in xrange(len(dd) - 2):
if (dd[i:i + 3] > cutoff).all():
plot.plot(
labelindex[i:i + 3], dd[i:i + 3], '.-', c='red', zorder=11)
elif dd[i] > cutoff:
plot.plot(
labelindex[i:i + 1], dd[i:i + 1], '.-', c='red', zorder=11)
x = plot.get_xlim()
y = plot.get_ylim()
if detail != -1:
plot.text(
x[1] - 0.05 * (x[1] - x[0]), y[1] - 0.05 * (y[1] - y[0]),
"cutoff=%.3f" % (cutoff), va='top', multialignment='left', ha='right')
elif detail > 0:
if detail == 2:
dd = array([i.select('not backbone').getBetas().mean()
for i in data])
yerr3 = dd - \
array([i.select('not backbone').getBetas().min()
for i in data])
yerr4 = array(
[i.select('not backbone').getBetas().max() for i in data]) - dd
if type(color) != type(None):
plot.plot(
labelindex, dd, '-', c=color[1], zorder=10, alpha=0.5)
plot.errorbar(labelindex, dd, yerr=[
yerr3, yerr4], capsize=0, elinewidth=0.2, c=color[1], zorder=1)
else:
plot.plot(labelindex, dd, '-', zorder=10, alpha=0.5)
plot.errorbar(
labelindex, dd, yerr=[yerr3, yerr4], capsize=0, elinewidth=0.1, zorder=1)
if type(color) != type(None):
plot.plot(labelindex, array(
[i.select('backbone').getBetas().mean() for i in data]), '-', c=color[0], zorder=10)
else:
plot.plot(labelindex, array(
[i.select('backbone').getBetas().mean() for i in data]), '-', zorder=10)
plot.plot(
list(plot.get_xlim()), [cutoff, cutoff], '--', c='grey', alpha=0.8, zorder=5)
dd = array([i.select('backbone').getBetas().mean() for i in data])
for i in xrange(len(dd) - 2):
if (dd[i:i + 3] > cutoff).all():
plot.plot(
labelindex[i:i + 3], dd[i:i + 3], '.-', c='red', zorder=11)
elif dd[i] > cutoff:
plot.plot(
labelindex[i:i + 1], dd[i:i + 1], '.-', c='red', zorder=11)
yerr1 = dd - \
array([i.select('backbone').getBetas().min() for i in data])
yerr2 = array([i.select('backbone').getBetas().max()
for i in data]) - dd
if type(color) != type(None):
plot.errorbar(labelindex, dd, yerr=[
yerr1, yerr2], capsize=0, elinewidth=0.2, c=color[0], zorder=2)
else:
plot.errorbar(
labelindex, dd, yerr=[yerr1, yerr2], capsize=0, elinewidth=0.2, zorder=2)
x = plot.get_xlim()
y = plot.get_ylim()
plot.text(x[1] - 0.05 * (x[1] - x[0]), y[1] - 0.05 * (y[1] - y[0]),
"cutoff=%.3f" % (cutoff), va='top', multialignment='left', ha='right')
else:
try:
if detail <= 0:
if type(color) != type(None):
plot[0].plot(labelindex, array(
[i.select('backbone').getBetas().mean() for i in data]), '-', c=color, zorder=10)
plot[1].plot(data1, '-', c=color, zorder=10)
else:
plot[0].plot(labelindex, array(
[i.select('backbone').getBetas().mean() for i in data]), '-', zorder=10)
plot[1].plot(data1, '-', zorder=10)
plot[0].plot(
list(plot[0].get_xlim()), [cutoff, cutoff], '--', c='grey', alpha=0.8, zorder=5)
dd = array([i.select('backbone').getBetas().mean()
for i in data])
for i in xrange(len(dd) - 2):
if (dd[i:i + 3] > cutoff).all():
plot[0].plot(
labelindex[i:i + 3], dd[i:i + 3], '.-', c='red', zorder=11)
elif dd[i] > cutoff:
plot[0].plot(
labelindex[i:i + 1], dd[i:i + 1], '.-', c='red', zorder=11)
plot[1].plot(
plot[1].get_xlim(), [cutoff, cutoff], '--', c='grey', alpha=0.8, zorder=5)
plot[1].set_ylim(plot[0].get_ylim())
x = plot[1].get_xlim()
y = plot[1].get_ylim()
if detail != -1:
plot[1].text(
x[1] - 0.05 * (x[1] - x[0]), y[
1] - 0.05 * (y[1] - y[0]),
"cutoff=%.3f" % (cutoff), va='top', multialignment='left', ha='right')
elif detail > 0:
if detail == 2:
dd = array(
[i.select('not backbone').getBetas().mean() for i in data])
yerr3 = dd - \
array([i.select('not backbone').getBetas().min()
for i in data])
yerr4 = array(
[i.select('not backbone').getBetas().max() for i in data]) - dd
if type(color) != type(None):
plot[0].plot(
labelindex, dd, '-', c=color[1], zorder=10, alpha=0.5)
plot[0].errorbar(labelindex, dd, yerr=[
yerr3, yerr4], capsize=0, elinewidth=0.2, c=color[1], zorder=1)
else:
plot[0].plot(labelindex, dd, '-', zorder=10, alpha=0.5)
plot[0].errorbar(
labelindex, dd, yerr=[yerr3, yerr4], capsize=0, elinewidth=0.1, zorder=1)
if type(color) != type(None):
plot[0].plot(labelindex, array(
[i.select('backbone').getBetas().mean() for i in data]), '-', c=color[0], zorder=10)
plot[1].plot(data1, '-', c=color[0], zorder=10)
else:
plot[0].plot(labelindex, array(
[i.select('backbone').getBetas().mean() for i in data]), '-', zorder=10)
plot[1].plot(data1, '-', zorder=10)
plot[0].plot(
list(plot[0].get_xlim()), [cutoff, cutoff], '--', c='grey', alpha=0.8, zorder=5)
dd = array([i.select('backbone').getBetas().mean()
for i in data])
for i in xrange(len(dd) - 2):
if (dd[i:i + 3] > cutoff).all():
plot[0].plot(
labelindex[i:i + 3], dd[i:i + 3], '.-', c='red', zorder=11)
elif dd[i] > cutoff:
plot[0].plot(
labelindex[i:i + 1], dd[i:i + 1], '.-', c='red', zorder=11)
yerr1 = dd - \
array([i.select('backbone').getBetas().min()
for i in data])
yerr2 = array([i.select('backbone').getBetas().max()
for i in data]) - dd
if type(color) != type(None):
plot[0].errorbar(labelindex, dd, yerr=[
yerr1, yerr2], capsize=0, elinewidth=0.2, c=color[0], zorder=2)
else:
plot[0].errorbar(
labelindex, dd, yerr=[yerr1, yerr2], capsize=0, elinewidth=0.2, zorder=2)
plot[1].plot(
plot[1].get_xlim(), [cutoff, cutoff], '--', c='grey', alpha=0.8, zorder=5)
plot[1].set_ylim(plot[0].get_ylim())
x = plot[1].get_xlim()
y = plot[1].get_ylim()
plot[1].text(
x[1] - 0.05 * (x[1] - x[0]), y[1] - 0.05 * (y[1] - y[0]),
"cutoff=%.3f" % (cutoff), va='top', multialignment='left', ha='right')
except:
printError(
"The plot type wrong. Must be 1 or 2 `matplotlib.axes.Axes`.")
return None
def genPvalueSample(mrc, sample=None, sampleradius=3.0, **kwargs):
"""Given the `mrc` and a sample structure, return the sample set around the sample
structure with radius `sampleradius`.
"""
from ..IO.output import printError, printInfo
from .mrc import MRC as MRCclass
from prody import AtomGroup as pdbclass
from numpy import ndarray, zeros_like, array, floor, ceil, rint
if not isinstance(mrc, MRCclass):
printError("Only mbio.MRC class supported for `mrc`.")
return None
if type(sample) == type(None):
sample = None
elif isinstance(sample, ndarray):
if not (sample.shape == (3,) or (len(sample.shape) == 2 and sample.shape[1] == 3)):
printError("The sample coordinates must has 3 columns.")
return None
if sample.shape == (3,):
sample = array([sample])
elif isinstance(sample, pdbclass):
sample = sample.getCoords()
printInfo("Getting the sample set.")
mark = zeros_like(mrc.data)
grid = array(mrc.getGridCoords())
gridstart = array([grid[0, 0], grid[1, 0], grid[2, 0]])
step = mrc.getGridSteps()
if type(sample) == type(None):
findset = mrc.data.flatten()
else:
tempindex = array(
rint(array(((sample - grid[:, 0]) / step), dtype=float)), dtype=int)
ballindex = ([], [], [])
for i in xrange(int(floor(-sampleradius / step[0])), int(ceil(sampleradius / step[0]) + 1)):
for j in xrange(int(floor(-sampleradius / step[1])), int(ceil(sampleradius / step[1]) + 1)):
for k in xrange(int(floor(-sampleradius / step[2])), int(ceil(sampleradius / step[2]) + 1)):
if (i * step[0]) ** 2 + (j * step[1]) ** 2 + (k * step[2]) ** 2 <= sampleradius ** 2:
ballindex[0].append(i)
ballindex[1].append(j)
ballindex[2].append(k)
ballindex = [array(i, dtype=int) for i in ballindex]
k = array([[len(grid[0])], [len(grid[1])], [len(grid[2])]])
for i in xrange(len(sample)):
t = array([ballindex[0] + tempindex[i][0], ballindex[1] +
tempindex[i][1], ballindex[2] + tempindex[i][2]])
t = t[:, (t >= 0).all(0) & (t < k).all()]
mark[(t[0], t[1], t[2])] = 1
findset = mrc.data[mark != 0]
printInfo("Sorting the sample set.")
findset.sort(kind='quicksort')
return findset
def transCylinder(pdb, **kwargs):
"""Transfer the PDB fragment to Cylinder.
Given the PDB, extract the CA C N and generate the center, 3 directions of the cube
and the length."""
from ..IO.output import printInfo
from numpy.linalg import svd
from numpy import cross, array, ndarray
if not isinstance(pdb, ndarray):
p1 = pdb.select("name CA C N").copy()
if p1 is None:
printError("The pdb has no CA C or N in the backbone.")
return None
if p1.numAtoms() < 15:
printError("The atom number({0}) is not enough to perform calculation.".format(
p1.numAtoms()))
printError("The result is not reliable.")
data = p1.getCoords()
else:
data = pdb
datamean = data.mean(axis=0)
uu, dd, vv = svd(data - datamean)
cent = datamean
dirc1 = vv[0]
if abs((dirc1 ** 2).sum() ** .5 - 1) > 1e-10:
raise ValueError(
"length of dirc is not 1, is {0}".format((dirc1 ** 2).sum() ** .5))
if (data[-1] - data[0]).dot(dirc1) < 0:
dirc1 = -dirc1
rank = (data - cent).dot(dirc1)
rankrange = [rank.min(), rank.max()]
dirc2 = cent - cent.dot(dirc1) * dirc1
dirc2 = dirc2 / ((dirc2 ** 2).sum() ** .5)
dirc3 = cross(dirc1, dirc2, axis=0)
dirc3 = dirc3 / ((dirc3 ** 2).sum() ** .5)
dirc = array((dirc1, dirc2, dirc3))
return cent, dirc, rankrange
def showMRCConnection(mrc, cutoff=2, **kwargs):
"""Plot 3D plot of connected parts in different color for MRC."""
from matplotlib import pyplot as plt
from matplotlib import use as matplotlibuse
import mpl_toolkits.mplot3d.axes3d as p3
from mpl_toolkits.mplot3d import Axes3D
from ..Application.setting import getMatplotlibDisplay
from ..Application.plotting import setAxesEqual
from numpy import array
try:
if not getMatplotlibDisplay():
matplotlibuse('Agg')
except:
pass
fig = plt.figure(figsize=(6, 6), facecolor='white')
ax = p3.Axes3D(fig, aspect=1)
ax.w_xaxis.set_pane_color((0, 0, 0))
ax.w_yaxis.set_pane_color((0, 0, 0))<|fim▁hole|> ax.w_xaxis.line.set_lw(0)
ax.w_yaxis.line.set_lw(0)
ax.w_zaxis.line.set_lw(0)
classes = {}
step = mrc.getGridSteps()
cutoff = cutoff**2
for i, j, k in zip(*mrc.data.nonzero()):
if mrc.data[i, j, k] == 0:
continue
if mrc.data[i, j, k] not in classes.keys():
classes[mrc.data[i, j, k]] = [[i, j, k]]
else:
classes[mrc.data[i, j, k]].append([i, j, k])
for ty, i in zip(classes.keys(), xrange(len(classes))):
color = plt.cm.gist_ncar(i * 1. / len(classes) * .9)
pos = array(classes[ty])
ax.scatter(pos[:, 0] * step[0] + mrc.origin[0],
pos[:, 1] * step[1] + mrc.origin[1],
pos[:, 2] * step[2] + mrc.origin[2], lw=0, c=color, zorder=10)
if cutoff > 0:
for j in xrange(len(pos)):
for k in xrange(j):
if (((pos[j] - pos[k]) * step)**2).sum() <= cutoff:
ax.plot(pos[[j, k], 0] * step[0] + mrc.origin[0],
pos[[j, k], 1] * step[1] + mrc.origin[1],
pos[[j, k], 2] * step[2] + mrc.origin[2], lw=3, c=color, zorder=10)
del pos
ax.set_xlabel('X', fontsize=15)
ax.set_ylabel('Y', fontsize=15)
ax.set_zlabel('Z', fontsize=15)
setAxesEqual(ax)
del classes
del ax
# plt.ion()
# try:
# if getMatplotlibDisplay():
# plt.show()
# except:
# pass
return fig
def showMRCConnectionEach(mrc, cutoff=2, path=None, **kwargs):
"""Plot 3D plot of connected parts in different color for MRC."""
from matplotlib import pyplot as plt
from matplotlib import use as matplotlibuse
import mpl_toolkits.mplot3d.axes3d as p3
from mpl_toolkits.mplot3d import Axes3D
from ..Application.setting import getMatplotlibDisplay
from ..Application.plotting import setAxesEqual
from numpy import array
import os
try:
if not getMatplotlibDisplay():
matplotlibuse('Agg')
except:
pass
if path is None:
path = os.getcwd()
fig = plt.figure(figsize=(6, 6), facecolor='white')
ax = p3.Axes3D(fig, aspect=1)
ax.w_xaxis.set_pane_color((0, 0, 0))
ax.w_yaxis.set_pane_color((0, 0, 0))
ax.w_zaxis.set_pane_color((0, 0, 0))
ax.w_xaxis.line.set_lw(0)
ax.w_yaxis.line.set_lw(0)
ax.w_zaxis.line.set_lw(0)
classes = {}
step = mrc.getGridSteps()
grid = mrc.getGridCoords()
cutoff = cutoff**2
for i, j, k in zip(*mrc.data.nonzero()):
if mrc.data[i, j, k] == 0:
continue
if mrc.data[i, j, k] not in classes.keys():
classes[mrc.data[i, j, k]] = [[i, j, k]]
else:
classes[mrc.data[i, j, k]].append([i, j, k])
sca = ax.scatter([60, 240], [60, 240], [60, 240], lw=0, zorder=10)
plt.ion()
ax.set_xlabel('X', fontsize=15)
ax.set_ylabel('Y', fontsize=15)
ax.set_zlabel('Z', fontsize=15)
setAxesEqual(ax)
for ty, i in zip(classes.keys(), xrange(len(classes))):
color = plt.cm.gist_ncar(i * 1. / len(classes) * .9)
pos = array(classes[ty])
sca._offsets3d = pos[:, 0] * step[0] + mrc.origin[0], pos[:, 1] * \
step[1] + mrc.origin[1], pos[:, 2] * step[2] + mrc.origin[2]
sca._facecolor3d = color
del pos
plt.savefig(os.path.join(path, str(i) + '.png'))
del classes
del ax
return fig
def testfit(pos, step):
from numpy import array, diag
from numpy.linalg import svd
data = array(pos) * step
datamean = data.mean(axis=0)
uu, dd, vv = svd(data - datamean, full_matrices=False)
d = dd**2
dd[0] = 0
if (((uu.dot(diag(dd)).dot(vv))**2).sum(1)**.5 > 4).any():
return 2
elif d[0] / d.sum() > .6:
return 1
else:
return 0
# Old 3
# if (((uu.dot(diag(dd)).dot(vv))**2).sum(1)**.5<6).sum()*1./data.shape[0]>.9:
# return 1
# else:
# return 2
# Old 2
# if d[0]/d.sum() <.8:
# return 2
# else:
# return 1
# Old 1
# if len(pos)>30:
# return 2
# else:
# return 1
def mrcSegment(mrc, percentage=0.001, cutoff=3, autostop=False, **kwargs):
"""Segment the MRC with the top `percentage` points.
Only two points closer than the cutoff will be taken as connected."""
from numpy import floor, ceil, argsort, zeros, zeros_like, array, unique
from ..IO.output import printUpdateInfo, finishUpdate, printInfo
from .mrc import MRC
maxnum = int(percentage * mrc.data.size)
args = argsort(mrc.data.ravel())[:mrc.data.size - maxnum - 1:-1]
pos = zeros((maxnum, 3), dtype=int)
pos[:, 0] = args // (mrc.data.shape[1] * mrc.data.shape[2])
pos[:, 1] = args % (mrc.data.shape[1] *
mrc.data.shape[2]) // mrc.data.shape[2]
pos[:, 2] = args % (mrc.data.shape[2])
data = mrc.data.ravel()[args]
save = zeros_like(mrc.data, dtype=int)
save[[pos[:, 0], pos[:, 1], pos[:, 2]]] = -1
save1 = zeros_like(mrc.data, dtype=float)
origin = mrc.origin
grid = mrc.getGridSteps()
step = cutoff / grid
ranges = [xrange(int(floor(-step[i])), int(ceil(step[i]) +
int(step[i].is_integer()))) for i in xrange(3)]
cutoff2 = cutoff**2
classnum = 0
save1count = 0
classmp = {}
classmpreverse = {}
classcount = {}
classpos = {}
statuscount = [0, 0, 0]
for posnum in xrange(maxnum):
if posnum % 1000 == 0:
printUpdateInfo("Building {:10d}/{:10d}".format(posnum, maxnum))
temp = pos[posnum]
closeset = []
closetype = []
closenumber = 0
for i in ranges[0]:
for j in ranges[1]:
for k in ranges[2]:
if save[temp[0] + i, temp[1] + j, temp[2] + k] > 0 and (i * grid[0])**2 + (j * grid[1])**2 + (k * grid[2])**2 <= cutoff2:
closeset.append([temp + array([i, j, k])])
closetype.append(
classmp[save[temp[0] + i, temp[1] + j, temp[2] + k]])
closenumber += 1
if closenumber == 0:
classnum += 1
save[temp[0], temp[1], temp[2]] = classnum
classcount[classnum] = [1, 0]
statuscount[0] += 1
classmp[classnum] = classnum
classmpreverse[classnum] = [classnum]
classpos[classnum] = [pos[posnum]]
elif len(unique(closetype)) == 1:
typeclass = closetype[0]
save[temp[0], temp[1], temp[2]] = typeclass
orilen = classcount[typeclass][0]
classcount[typeclass][0] += 1
classpos[typeclass].append(pos[posnum])
if classcount[typeclass][1] == 0:
if classcount[typeclass][0] >= 10:
statuscount[0] -= 1
classcount[typeclass][1] = testfit(
classpos[typeclass], grid)
statuscount[classcount[typeclass][1]] += 1
elif classcount[typeclass][1] == 1:
statuscount[1] -= 1
classcount[typeclass][1] = testfit(classpos[typeclass], grid)
statuscount[classcount[typeclass][1]] += 1
if classcount[typeclass][1] == 2:
save1count += 1
tempposlist = classpos[typeclass]
for i in xrange(orilen):
save1[tempposlist[i][0], tempposlist[i]
[1], tempposlist[i][2]] = save1count
del tempposlist
else:
pass
del typeclass
else:
closetypesort = unique(closetype)
typeclass = closetypesort[0]
save[temp[0], temp[1], temp[2]] = typeclass
orilen = classcount[typeclass][0]
classcount[typeclass][0] += 1
classpos[typeclass].append(pos[posnum])
hasnocylinder = False
for i in closetypesort[1:]:
if classcount[i][1] == 2:
hasnocylinder = True
classcount[typeclass][0] += classcount[i][0]
classpos[typeclass] += classpos[i]
classmp[i] = typeclass
for j in classmpreverse[i]:
classmp[j] = typeclass
classmpreverse[typeclass] += classmpreverse[i]
classmpreverse.pop(i)
if classcount[typeclass][1] == 0:
if classcount[typeclass][0] >= 10:
statuscount[0] -= 1
classcount[typeclass][1] = testfit(
classpos[typeclass], grid) if not hasnocylinder else 2
statuscount[classcount[typeclass][1]] += 1
if classcount[typeclass][1] == 2:
for i in closetypesort[1:]:
if classcount[i][1] == 1:
save1count += 1
tempposlist = classpos[i]
for i in xrange(len(classpos[i])):
save1[tempposlist[i][0], tempposlist[i][
1], tempposlist[i][2]] = save1count
del tempposlist
elif classcount[typeclass][1] == 1:
statuscount[1] -= 1
classcount[typeclass][1] = testfit(
classpos[typeclass], grid) if not hasnocylinder else 2
statuscount[classcount[typeclass][1]] += 1
if classcount[typeclass][1] == 2:
for i in closetypesort[1:]:
if classcount[i][1] == 1:
save1count += 1
tempposlist = classpos[i]
for i in xrange(len(classpos[i])):
save1[tempposlist[i][0], tempposlist[i]
[1], tempposlist[i][2]] = save1count
del tempposlist
save1count += 1
tempposlist = classpos[typeclass]
for i in xrange(orilen):
save1[tempposlist[i][0], tempposlist[i]
[1], tempposlist[i][2]] = save1count
del tempposlist
else:
pass
for i in closetypesort[1:]:
statuscount[classcount[i][1]] -= 1
classcount.pop(i)
classpos.pop(i)
del typeclass, closetypesort
del temp, closeset, closetype, closenumber
if autostop:
if statuscount[0] == 0 and statuscount[1] == 0:
finishUpdate()
printInfo('Autostop')
break
if statuscount[2] != 0 and statuscount[1] == 0:
finishUpdate()
printInfo('Autostop')
break
for i in classcount:
if classcount[i][1] == 1:
save1count += 1
tempposlist = classpos[i]
for i in xrange(len(tempposlist)):
save1[tempposlist[i][0], tempposlist[i]
[1], tempposlist[i][2]] = save1count
del classnum, save1count, classmp, classmpreverse, classcount, classpos
finishUpdate()
mrc1 = MRC()
for i in mrc.header.__dict__:
setattr(mrc1.header, i, getattr(mrc.header, i))
mrc1.data = save1
mrc1.update()
return mrc1
def gaussian3D(matrix, sigma, *args, **kwargs):
"""Gaussian 3D filter with specific sigma. The filter is ignored after 4*sigma.
The program is written in C(OpenMP) to perform quicker calculation than `scipy.ndimage`.
The boundary condition using wrap mode in scipy.
wrap:
7 8 9|1 2 3 4 5 6 7 8 9|1 2 3
"""
from ..IO.output import printError
from numpy import zeros_like
from .Cmrc_analysis_p import Cgaussian
if ~matrix.flags.contiguous:
matrix = matrix.copy()
result = zeros_like(matrix)
result = Cgaussian(matrix=matrix, sigma=sigma, result=result)
if isinstance(result, tuple):
if result[0] is None:
printError(result[1])
else:
printError("Get wrong return from C function.")
return None
return result<|fim▁end|> | ax.w_zaxis.set_pane_color((0, 0, 0)) |
<|file_name|>Target_Network.cpp<|end_file_name|><|fim▁begin|>//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
#include <nanoHAL.h><|fim▁hole|>bool Network_Interface_Bind(int index)
{
(void)index;
return true;
}
int Network_Interface_Open(int index)
{
HAL_Configuration_NetworkInterface networkConfiguration;
// load network interface configuration from storage
if(!ConfigurationManager_GetConfigurationBlock((void*)&networkConfiguration, DeviceConfigurationOption_Network, index))
{
// failed to load configuration
// FIXME output error?
return SOCK_SOCKET_ERROR;
}
_ASSERTE(networkConfiguration.StartupAddressMode > 0);
switch(index)
{
case 0:
{
// Open the network interface and set its config
// TODO / FIXME
// Return index to NetIF in its linked list, return 0 (probably right if only interface)
// This used by Network stack to hook in to status/address changes for events to users
// For now get the Netif number form original Chibios binding code
struct netif * nptr = nf_getNetif();
return nptr->num;
}
break;
}
return SOCK_SOCKET_ERROR;
}
bool Network_Interface_Close(int index)
{
switch(index)
{
case 0:
return true;
}
return false;
}<|fim▁end|> | #include <lwip/netif.h>
extern "C" struct netif * nf_getNetif();
|
<|file_name|>event_setting.rs<|end_file_name|><|fim▁begin|>// Copyright 2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT>
use gdk_sys;<|fim▁hole|>
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EventSetting(::Event);
event_wrapper!(EventSetting, GdkEventSetting);
event_subtype!(EventSetting, gdk_sys::GDK_SETTING);
impl EventSetting {
pub fn get_name(&self) -> Option<GString> {
unsafe { from_glib_none(self.as_ref().name) }
}
pub fn get_action(&self) -> ::SettingAction {
from_glib(self.as_ref().action)
}
}<|fim▁end|> | use glib::translate::*;
use glib::GString; |
<|file_name|>test_activity_stream.py<|end_file_name|><|fim▁begin|>from actstream.models import Action
from django.test import TestCase
from cyidentity.cyfullcontact.tests.util import create_sample_contact_info
<|fim▁hole|>class FullContactActivityStreamTestCase(TestCase):
def test_contact_create(self):
contact_info = create_sample_contact_info()
action = Action.objects.actor(contact_info).latest('timestamp')
self.assertEqual(action.verb, 'FullContact information was created')<|fim▁end|> | |
<|file_name|>addon-toolbars.stories.ts<|end_file_name|><|fim▁begin|>import { html } from 'lit';<|fim▁hole|>} as Meta;
const getCaptionForLocale = (locale: string) => {
switch (locale) {
case 'es':
return 'Hola!';
case 'fr':
return 'Bonjour !';
case 'zh':
return '你好!';
case 'kr':
return '안녕하세요!';
case 'en':
default:
return 'Hello';
}
};
export const Locale: Story = (args, { globals: { locale } }) => {
return html` <div>Your locale is '${locale}', so I say: ${getCaptionForLocale(locale)}</div> `;
};<|fim▁end|> | import { Story, Meta } from '@storybook/web-components';
export default {
title: 'Addons / Toolbars', |
<|file_name|>instr_vpsubusw.rs<|end_file_name|><|fim▁begin|>use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn vpsubusw_1() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM3)), operand3: Some(Direct(XMM7)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 225, 217, 199], OperandSize::Dword)
}
#[test]
fn vpsubusw_2() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: Some(IndirectDisplaced(EBX, 1622033599, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 233, 217, 171, 191, 68, 174, 96], OperandSize::Dword)
}
#[test]
fn vpsubusw_3() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM2)), operand3: Some(Direct(XMM3)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 233, 217, 211], OperandSize::Qword)
}
#[test]
fn vpsubusw_4() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM7)), operand3: Some(Indirect(RBX, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 193, 217, 27], OperandSize::Qword)
}
#[test]
fn vpsubusw_5() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(YMM7)), operand2: Some(Direct(YMM1)), operand3: Some(Direct(YMM5)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 245, 217, 253], OperandSize::Dword)
}
#[test]
fn vpsubusw_6() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(YMM6)), operand2: Some(Direct(YMM6)), operand3: Some(Indirect(EAX, Some(OperandSize::Ymmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 205, 217, 48], OperandSize::Dword)
}
#[test]
fn vpsubusw_7() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(YMM0)), operand2: Some(Direct(YMM2)), operand3: Some(Direct(YMM3)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 237, 217, 195], OperandSize::Qword)
}
#[test]
fn vpsubusw_8() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(YMM7)), operand2: Some(Direct(YMM7)), operand3: Some(IndirectScaledDisplaced(RDX, Four, 325913610, Some(OperandSize::Ymmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 197, 217, 60, 149, 10, 12, 109, 19], OperandSize::Qword)
}
#[test]
fn vpsubusw_9() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM2)), operand3: Some(Direct(XMM3)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: None }, &[98, 241, 109, 140, 217, 243], OperandSize::Dword)
}
#[test]
fn vpsubusw_10() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM7)), operand3: Some(IndirectDisplaced(EBX, 636600843, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 241, 69, 143, 217, 139, 11, 194, 241, 37], OperandSize::Dword)<|fim▁hole|>#[test]
fn vpsubusw_11() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM20)), operand3: Some(Direct(XMM9)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K4), broadcast: None }, &[98, 209, 93, 132, 217, 209], OperandSize::Qword)
}
#[test]
fn vpsubusw_12() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(XMM9)), operand2: Some(Direct(XMM21)), operand3: Some(IndirectScaledIndexed(RAX, RDX, Four, Some(OperandSize::Xmmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 113, 85, 135, 217, 12, 144], OperandSize::Qword)
}
#[test]
fn vpsubusw_13() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(YMM7)), operand2: Some(Direct(YMM0)), operand3: Some(Direct(YMM2)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K7), broadcast: None }, &[98, 241, 125, 175, 217, 250], OperandSize::Dword)
}
#[test]
fn vpsubusw_14() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(YMM5)), operand2: Some(Direct(YMM4)), operand3: Some(Indirect(EDI, Some(OperandSize::Ymmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None }, &[98, 241, 93, 173, 217, 47], OperandSize::Dword)
}
#[test]
fn vpsubusw_15() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(YMM2)), operand2: Some(Direct(YMM29)), operand3: Some(Direct(YMM1)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 241, 21, 161, 217, 209], OperandSize::Qword)
}
#[test]
fn vpsubusw_16() {
run_test(&Instruction { mnemonic: Mnemonic::VPSUBUSW, operand1: Some(Direct(YMM31)), operand2: Some(Direct(YMM5)), operand3: Some(IndirectScaledIndexedDisplaced(RDX, RCX, Eight, 685932004, Some(OperandSize::Ymmword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 97, 85, 169, 217, 188, 202, 228, 125, 226, 40], OperandSize::Qword)
}<|fim▁end|> | }
|
<|file_name|>base.py<|end_file_name|><|fim▁begin|>"""Kytos Napps Module."""
import json
import os
import re
import sys
import tarfile
import urllib
from abc import ABCMeta, abstractmethod
from pathlib import Path
from random import randint
from threading import Event, Thread
from kytos.core.events import KytosEvent
from kytos.core.logs import NAppLog
__all__ = ('KytosNApp',)
LOG = NAppLog()
class NApp:
"""Class to represent a NApp."""
# pylint: disable=too-many-arguments
def __init__(self, username=None, name=None, version=None,
repository=None, meta=False):
self.username = username
self.name = name
self.version = version if version else 'latest'
self.repository = repository
self.meta = meta
self.description = None
self.tags = []
self.enabled = False
self.napp_dependencies = []
def __str__(self):
return "{}/{}".format(self.username, self.name)
def __repr__(self):
return f"NApp({self.username}/{self.name})"
def __hash__(self):
return hash(self.id)
def __eq__(self, other):
"""Compare username/name strings."""
return isinstance(other, self.__class__) and self.id == other.id
@property
def id(self): # pylint: disable=invalid-name
"""username/name string."""
return str(self)
@property
def uri(self):
"""Return a unique identifier of this NApp."""
version = self.version if self.version else 'latest'
if not self._has_valid_repository():
return ""
# Use the next line after Diraol fix redirect using ":" for version
# return "{}/{}:{}".format(self.repository, self.id, version)
return "{}/{}-{}".format(self.repository, self.id, version)
@property
def package_url(self):
"""Return a fully qualified URL for a NApp package."""
if not self.uri:
return ""
return "{}.napp".format(self.uri)
@classmethod
def create_from_uri(cls, uri):
"""Return a new NApp instance from an unique identifier."""
regex = r'^(((https?://|file://)(.+))/)?(.+?)/(.+?)/?(:(.+))?$'
match = re.match(regex, uri)
if not match:
return None
return cls(username=match.groups()[4],
name=match.groups()[5],
version=match.groups()[7],
repository=match.groups()[1])
@classmethod
def create_from_json(cls, filename):
"""Return a new NApp instance from a metadata file."""
with open(filename, encoding='utf-8') as data_file:
data = json.loads(data_file.read())
return cls.create_from_dict(data)
@classmethod
def create_from_dict(cls, data):
"""Return a new NApp instance from metadata."""
napp = cls()
for attribute, value in data.items():
setattr(napp, attribute, value)
return napp
def as_json(self):
"""Dump all NApp attributes on a json format."""
return json.dumps(self.__dict__)
def match(self, pattern):
"""Whether a pattern is present on NApp id, description and tags."""
try:
pattern = '.*{}.*'.format(pattern)
pattern = re.compile(pattern, re.IGNORECASE)
strings = [self.id, self.description] + self.tags
return any(pattern.match(string) for string in strings)
except TypeError:
return False
def download(self):
"""Download NApp package from his repository.
Raises:
urllib.error.HTTPError: If download is not successful.
Returns:
str: Downloaded temp filename.
"""
if not self.package_url:
return None
package_filename = urllib.request.urlretrieve(self.package_url)[0]
extracted = self._extract(package_filename)
Path(package_filename).unlink()
self._update_repo_file(extracted)
return extracted
@staticmethod
def _extract(filename):
"""Extract NApp package to a temporary folder.
Return:
pathlib.Path: Temp dir with package contents.
"""
random_string = '{:0d}'.format(randint(0, 10**6))
tmp = '/tmp/kytos-napp-' + Path(filename).stem + '-' + random_string
os.mkdir(tmp)
with tarfile.open(filename, 'r:xz') as tar:
tar.extractall(tmp)
return Path(tmp)
def _has_valid_repository(self):
"""Whether this NApp has a valid repository or not."""
return all([self.username, self.name, self.repository])
def _update_repo_file(self, destination=None):
"""Create or update the file '.repo' inside NApp package."""
with open("{}/.repo".format(destination), 'w') as repo_file:
repo_file.write(self.repository + '\n')
class KytosNApp(Thread, metaclass=ABCMeta):
"""Base class for any KytosNApp to be developed."""
def __init__(self, controller, **kwargs):
"""Contructor of KytosNapps.
Go through all of the instance methods and selects those that have
the events attribute, then creates a dict containing the event_name
and the list of methods that are responsible for handling such event.
At the end, the setup method is called as a complement of the init
process.
"""
Thread.__init__(self, daemon=False)
self.controller = controller
self.username = None # loaded from json
self.name = None # loaded from json
self.meta = False # loaded from json
self._load_json()
# Force a listener with a private method.
self._listeners = {
'kytos/core.shutdown': [self._shutdown_handler],
'kytos/core.shutdown.' + self.napp_id: [self._shutdown_handler]}
self.__event = Event()
#: int: Seconds to sleep before next call to :meth:`execute`. If
#: negative, run :meth:`execute` only once.
self.__interval = -1
self.setup()
#: Add non-private methods that listen to events.
handler_methods = [getattr(self, method_name) for method_name in
dir(self) if method_name[0] != '_' and
callable(getattr(self, method_name)) and
hasattr(getattr(self, method_name), 'events')]
# Building the listeners dictionary
for method in handler_methods:
for event_name in method.events:
if event_name not in self._listeners:
self._listeners[event_name] = []
self._listeners[event_name].append(method)
@property
def napp_id(self):
"""username/name string."""
return "{}/{}".format(self.username, self.name)
def listeners(self):
"""Return all listeners registered."""
return list(self._listeners.keys())
def _load_json(self):
"""Update object attributes based on kytos.json."""
current_file = sys.modules[self.__class__.__module__].__file__
json_path = os.path.join(os.path.dirname(current_file), 'kytos.json')
with open(json_path, encoding='utf-8') as data_file:
data = json.loads(data_file.read())
for attribute, value in data.items():
setattr(self, attribute, value)
def execute_as_loop(self, interval):
"""Run :meth:`execute` within a loop. Call this method during setup.
By calling this method, the application does not need to worry about
loop details such as sleeping and stopping the loop when
:meth:`shutdown` is called. Just call this method during :meth:`setup`
and implement :meth:`execute` as a single execution.
Args:
interval (int): Seconds between each call to :meth:`execute`.
"""
self.__interval = interval
def run(self):
"""Call the execute method, looping as needed.
It should not be overriden.
"""
self.notify_loaded()
LOG.info("Running NApp: %s", self)
self.execute()
while self.__interval > 0 and not self.__event.is_set():
self.__event.wait(self.__interval)
self.execute()
def notify_loaded(self):
"""Inform this NApp has been loaded."""
name = f'{self.username}/{self.name}.loaded'
event = KytosEvent(name=name, content={})
self.controller.buffers.app.put(event)
# all listeners receive event
def _shutdown_handler(self, event): # pylint: disable=unused-argument
"""Listen shutdown event from kytos.
This method listens the kytos/core.shutdown event and call the shutdown
method from napp subclass implementation.
Paramters
event (:class:`KytosEvent`): event to be listened.
"""
if not self.__event.is_set():
self.__event.set()
self.shutdown()
@abstractmethod
def setup(self):
"""Replace the 'init' method for the KytosApp subclass.
The setup method is automatically called on the NApp __init__().
Users aren't supposed to call this method directly.
"""
@abstractmethod
def execute(self):
"""Execute in a loop until 'kytos/core.shutdown' is received.
The execute method is called by KytosNApp class.
Users shouldn't call this method directly.
"""
@abstractmethod
def shutdown(self):<|fim▁hole|>
The user implementation of this method should do the necessary routine
for the user App and also it is a good moment to break the loop of the
execute method if it is in a loop.
This methods is not going to be called directly, it is going to be
called by the _shutdown_handler method when a KytosShutdownEvent is
sent.
"""<|fim▁end|> | """Run before the app is unloaded and the controller, stopped. |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import React from 'react';
import ReactDOM from 'react-dom';
import Layout from './layout.js';
<|fim▁hole|><|fim▁end|> | document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(<Layout />, document.getElementById('main'));
}); |
<|file_name|>voter.py<|end_file_name|><|fim▁begin|># This file is part of VoltDB.
# Copyright (C) 2008-2018 VoltDB Inc.
#
# 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.<|fim▁hole|># 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.
# All the commands supported by the Voter application.
import os
@VOLT.Command(description = 'Build the Voter application and catalog.',
options = VOLT.BooleanOption('-C', '--conditional', 'conditional',
'only build when the catalog file is missing'))
def build(runner):
if not runner.opts.conditional or not os.path.exists('voter.jar'):
runner.java.compile('obj', 'src/voter/*.java', 'src/voter/procedures/*.java')
runner.call('volt.compile', '-c', 'obj', '-o', 'voter.jar', 'ddl.sql')
@VOLT.Command(description = 'Clean the Voter build output.')
def clean(runner):
runner.shell('rm', '-rfv', 'obj', 'debugoutput', 'voter.jar', 'voltdbroot')
@VOLT.Server('create',
description = 'Start the Voter VoltDB server.',
command_arguments = 'voter.jar',
classpath = 'obj')
def server(runner):
runner.call('build', '-C')
runner.go()
@VOLT.Java('voter.AsyncBenchmark', classpath = 'obj',
description = 'Run the Voter asynchronous benchmark.')
def async(runner):
runner.call('build', '-C')
runner.go()
@VOLT.Java('voter.SyncBenchmark', classpath = 'obj',
description = 'Run the Voter synchronous benchmark.')
def sync(runner):
runner.call('build', '-C')
runner.go()
@VOLT.Java('voter.JDBCBenchmark', classpath = 'obj',
description = 'Run the Voter JDBC benchmark.')
def jdbc(runner):
runner.call('build', '-C')
runner.go()
@VOLT.Java('voter.SimpleBenchmark', classpath = 'obj',
description = 'Run the Voter simple benchmark.')
def simple(runner):
runner.call('build', '-C')
runner.go()<|fim▁end|> | # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR |
<|file_name|>plot_current25.py<|end_file_name|><|fim▁begin|># ------------------------------------------------------
# current.py
#
# Plot a current field at fixed depth
# Modified from the spermplot example
#
# Bjørn Ådlandsvik <[email protected]>
# 2020-03-27
# ------------------------------------------------------
# -------------
# Imports<|fim▁hole|># -------------
import numpy as np
import matplotlib.pyplot as plt
from netCDF4 import Dataset
from roppy import SGrid
from roppy.mpl_util import landmask
from roppy.trajectories import curly_vectors
# -------------------------
# User settings
# ------------------------
ncfile = "data/ocean_avg_example.nc"
timeframe = 3 # Fourth time frame
# subgrid = (1,-1,1,-1) # whole grid except boundary cells
subgrid = (110, 170, 35, 90)
# Depth level [m]
z = 25
# Distance between vectors
stride = 2
# Speed level (isotachs)
speedlevels = np.linspace(0, 0.5, 6) # 0.0, 0.1, ...., 0.5
# Colormap for speed
speedcolors = "YlOrRd"
# --------------------
# Read the data
# --------------------
f = Dataset(ncfile)
grid = SGrid(f, subgrid=subgrid)
# Read 3D current for the subgrid
U0 = f.variables["u"][timeframe, :, grid.Ju, grid.Iu]
V0 = f.variables["v"][timeframe, :, grid.Jv, grid.Iv]
Mu = f.variables["mask_u"][grid.Ju, grid.Iu]
Mv = f.variables["mask_v"][grid.Jv, grid.Iv]
# f.close()
# ----------------------
# Handle the data
# ----------------------
# Interpolate to rho-points
U1 = 0.5 * (U0[:, :, :-1] + U0[:, :, 1:])
V1 = 0.5 * (V0[:, :-1, :] + V0[:, 1:, :])
# Interpolate to correct depth level
U = grid.zslice(U1, z)
V = grid.zslice(V1, z)
# Remove velocity at land and below bottom
U[grid.h < z] = np.nan
V[grid.h < z] = np.nan
# Compute the current speed
Speed = np.sqrt(U * U + V * V)
# Impose the stride
X = grid.X[::stride]
Y = grid.Y[::stride]
U = U[::stride, ::stride]
V = V[::stride, ::stride]
# --------------------
# Make the plot
# --------------------
# Contour plot of current speed
plt.contourf(grid.X, grid.Y, Speed, levels=speedlevels, cmap=speedcolors)
plt.colorbar()
# Make the vector plot
plt.quiver(X, Y, U, V, width=0.003)
# Plot green land mask
landmask(grid, "LightGreen")
# Set correct aspect ratio and axis limits
plt.axis("image")
plt.axis((grid.i0 + 0.5, grid.i1 - 1.5, grid.j0 + 0.5, grid.j1 - 1.5))
# Display the plot
plt.show()<|fim▁end|> | |
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>/*
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib 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.
*/
// TypeScript Version: 2.0
/* tslint:disable:max-line-length */
/* tslint:disable:max-file-line-count */
import base = require( '@stdlib/strided/base' );
import dispatch = require( '@stdlib/strided/dispatch' );
import dtypes = require( '@stdlib/strided/dtypes' );
/**
* Interface describing the `strided` namespace.
*/
interface Namespace {
/**
* Base strided.
*/
base: typeof base;
/**
* Returns a strided array function interface which performs multiple dispatch and supports alternative indexing semantics.
*
* @param fcns - list of strided array functions
* @param types - one-dimensional list of strided array argument data types
* @param data - strided array function data (e.g., callbacks)
* @param nargs - total number of strided array function interface arguments (including data types, strides, and offsets)
* @param nin - number of input strided arrays
* @param nout - number of output strided arrays
* @throws first argument must be either a function or an array of functions
* @throws second argument must be an array-like object
* @throws third argument must be an array-like object or `null`
* @throws third and first arguments must have the same number of elements
* @throws fourth argument must be a positive integer
* @throws fifth argument must be a nonnegative integer
* @throws sixth argument must be a nonnegative integer
* @throws fourth argument must be compatible with the specified number of input and output arrays
* @throws number of types must match the number of functions times the total number of array arguments for each function
* @throws interface must accept at least one strided input and/or output array
* @returns strided array function interface
*
* @example
* var unary = require( `@stdlib/strided/base/unary` ).ndarray;
* var abs = require( `@stdlib/math/base/special/abs` );
* var Float64Array = require( `@stdlib/array/float64` );
*
* var types = [
* 'float64', 'float64'
* ];
*
* var data = [
* abs
* ];
*
* var strided = ns.dispatch( unary, types, data, 9, 1, 1 );
*
* // ...
*
* var x = new Float64Array( [ -1.0, -2.0, -3.0, -4.0, -5.0 ] );
* var y = new Float64Array( [ 0.0, 0.0, 0.0, 0.0, 0.0 ] );
*
* strided( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0 );
* // y => <Float64Array>[ 1.0, 2.0, 3.0, 4.0, 5.0 ]
*/
dispatch: typeof dispatch;<|fim▁hole|> * @returns list of strided array data types
*
* @example
* var list = ns.dtypes();
* // returns [...]
*/
dtypes: typeof dtypes;
}
/**
* Strided.
*/
declare var ns: Namespace;
// EXPORTS //
export = ns;<|fim▁end|> |
/**
* Returns a list of strided array data types.
* |
<|file_name|>testcolor.py<|end_file_name|><|fim▁begin|>from colordetection import *
<|fim▁hole|><|fim▁end|> | topColors(992780587437103) |
<|file_name|>service.py<|end_file_name|><|fim▁begin|>import attr
from navmazing import NavigateToAttribute
from navmazing import NavigateToSibling
from cfme.common import Taggable
from cfme.common import TagPageView
from cfme.containers.provider import ContainerObjectAllBaseView
from cfme.containers.provider import ContainerObjectDetailsBaseView
from cfme.containers.provider import GetRandomInstancesMixin
from cfme.containers.provider import Labelable
from cfme.containers.provider import LoggingableView
from cfme.modeling.base import BaseCollection
from cfme.modeling.base import BaseEntity
from cfme.utils.appliance.implementations.ui import CFMENavigateStep
from cfme.utils.appliance.implementations.ui import navigator
from cfme.utils.providers import get_crud_by_name
class ServiceView(ContainerObjectAllBaseView, LoggingableView):
"""Container Nodes view"""
@property
def in_service(self):
"""Determine if the Service page is currently open"""
return (
self.logged_in_as_current_user and
self.navigation.currently_selected == ['Compute', 'Containers', 'Container Services']
)
class ServiceAllView(ServiceView):
"""Container Services All view"""
SUMMARY_TEXT = "Container Services"<|fim▁hole|>
@property
def is_displayed(self):
return self.in_service and super().is_displayed
class ServiceDetailsView(ContainerObjectDetailsBaseView):
"""Container Services Details view"""
SUMMARY_TEXT = "Container Services"
@attr.s
class Service(BaseEntity, Taggable, Labelable):
PLURAL = 'Container Services'
all_view = ServiceAllView
details_view = ServiceDetailsView
name = attr.ib()
project_name = attr.ib()
provider = attr.ib()
@attr.s
class ServiceCollection(GetRandomInstancesMixin, BaseCollection):
"""Collection object for :py:class:`Service`."""
ENTITY = Service
def all(self):
# container_services table has ems_id, join with ext_mgmgt_systems on id for provider name
# Then join with container_projects on the id for the project
service_table = self.appliance.db.client['container_services']
ems_table = self.appliance.db.client['ext_management_systems']
project_table = self.appliance.db.client['container_projects']
service_query = (
self.appliance.db.client.session
.query(service_table.name, project_table.name, ems_table.name)
.join(ems_table, service_table.ems_id == ems_table.id)
.join(project_table, service_table.container_project_id == project_table.id))
provider = None
# filtered
if self.filters.get('provider'):
provider = self.filters.get('provider')
service_query = service_query.filter(ems_table.name == provider.name)
services = []
for name, project_name, ems_name in service_query.all():
services.append(self.instantiate(name=name, project_name=project_name,
provider=provider or get_crud_by_name(ems_name)))
return services
@navigator.register(ServiceCollection, 'All')
class All(CFMENavigateStep):
prerequisite = NavigateToAttribute('appliance.server', 'LoggedIn')
VIEW = ServiceAllView
def step(self, *args, **kwargs):
self.prerequisite_view.navigation.select('Compute', 'Containers', 'Container Services')
def resetter(self, *args, **kwargs):
# Reset view and selection
self.view.toolbar.view_selector.select("List View")
self.view.paginator.reset_selection()
@navigator.register(Service, 'Details')
class Details(CFMENavigateStep):
prerequisite = NavigateToAttribute('parent', 'All')
VIEW = ServiceDetailsView
def step(self, *args, **kwargs):
search_visible = self.prerequisite_view.entities.search.is_displayed
self.prerequisite_view.entities.get_entity(name=self.obj.name,
project_name=self.obj.project_name,
surf_pages=not search_visible,
use_search=search_visible).click()
@navigator.register(Service, 'EditTags')
class EditTags(CFMENavigateStep):
VIEW = TagPageView
prerequisite = NavigateToSibling('Details')
def step(self, *args, **kwargs):
self.prerequisite_view.toolbar.policy.item_select('Edit Tags')<|fim▁end|> | |
<|file_name|>test_cancel.py<|end_file_name|><|fim▁begin|># This file is part of the Trezor project.
#
# Copyright (C) 2012-2018 SatoshiLabs and contributors
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
#
# This library 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 License along with this library.
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
import pytest
import trezorlib.messages as m
from .conftest import setup_client
@setup_client()
@pytest.mark.parametrize(
"message",
[
m.Ping(message="hello", button_protection=True),
m.GetAddress(
address_n=[0],
coin_name="Bitcoin",
script_type=m.InputScriptType.SPENDADDRESS,
show_display=True,
),
],
)
def test_cancel_message_via_cancel(client, message):
resp = client.call_raw(message)
assert isinstance(resp, m.ButtonRequest)
client.transport.write(m.ButtonAck())
client.transport.write(m.Cancel())
resp = client.transport.read()
assert isinstance(resp, m.Failure)
assert resp.code == m.FailureType.ActionCancelled
@setup_client()
@pytest.mark.parametrize(
"message",
[
m.Ping(message="hello", button_protection=True),
m.GetAddress(<|fim▁hole|> ),
],
)
def test_cancel_message_via_initialize(client, message):
resp = client.call_raw(message)
assert isinstance(resp, m.ButtonRequest)
client.transport.write(m.ButtonAck())
client.transport.write(m.Initialize())
resp = client.transport.read()
assert isinstance(resp, m.Features)<|fim▁end|> | address_n=[0],
coin_name="Bitcoin",
script_type=m.InputScriptType.SPENDADDRESS,
show_display=True, |
<|file_name|>en.js<|end_file_name|><|fim▁begin|>// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
<|fim▁hole|>CKEDITOR.plugins.setLang('GeSHi', 'en',
{
langGeSHi :
{
title: 'GeSHi',
label: 'Post syntax highlighted code',
langLbl: 'Select language'
}
});<|fim▁end|> | // along with this program. If not, see <http://www.gnu.org/licenses/>.
|
<|file_name|>webpack.node.config.js<|end_file_name|><|fim▁begin|>/* eslint-disable */
var webpack = require('webpack');
var path = require('path');
var nodeExternals = require('webpack-node-externals');
module.exports = {
entry: './index.js',
output: {
path: path.join(__dirname, '..', '..', 'build'),
filename: 'app.js'
},
resolve: {
modulesDirectories: ['shared', 'node_modules'],
extensions: ['', '.js', '.jsx', '.json']
},
externals: [nodeExternals()],
plugins: [
new webpack.BannerPlugin('require("source-map-support").install();', {
raw: true,
entryOnly: false
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development')
}
})
],
target: 'node',
node: { // webpack strangely doesn't do this when you set `target: 'node'`
console: false,
global: false,
process: false,
Buffer: false,
__filename: false,
__dirname: false,
setImmediate: false
},
devtool: 'sourcemap',
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loader: 'babel',
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['react', 'es2015', 'stage-0'],
plugins: ['transform-decorators-legacy', ['react-transform', {
transforms: [
{
transform: 'react-transform-catch-errors',
imports: ['react', 'redbox-react']
}
]
}]]
}
},
{<|fim▁hole|> test: /\.(woff|woff2|ttf|eot|svg|png|jpg|jpeg|gif)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url'
}
]
}
};<|fim▁end|> | test: /\.(css|less)$/,
loader: 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!less'
},
{ |
<|file_name|>borrowck-move-by-capture-ok.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>// 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.
#![allow(unknown_features)]
#![feature(box_syntax)]
#![feature(unboxed_closures)]
pub fn main() {
let bar: Box<_> = box 3;
let h = || -> int { *bar };
assert_eq!(h(), 3);
}<|fim▁end|> | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at |
<|file_name|>game.rs<|end_file_name|><|fim▁begin|>use shogi::{Color, Position, TimeControl};
use std::time::Instant;
#[derive(Debug)]
pub struct Game {
pub black_player: String,
pub white_player: String,
pub pos: Position,
pub time: TimeControl,
pub turn_start_time: Instant,
}
#[derive(Debug, Clone)]
pub struct GameResult {
pub winner: Option<Color>,
pub reason: GameOverReason,
}
impl GameResult {
pub fn new(winner: Option<Color>, reason: GameOverReason) -> GameResult {
GameResult { winner, reason }
}<|fim▁hole|> Resign,
IllegalMove,
OutOfTime,
MaxPly,
DeclareWinning,
}
impl Game {
pub fn new(initial_time: TimeControl) -> Game {
Game {
black_player: String::new(),
white_player: String::new(),
pos: Position::new(),
time: initial_time,
turn_start_time: Instant::now(),
}
}
}<|fim▁end|> | }
#[derive(Debug, Clone, Copy)]
pub enum GameOverReason { |
<|file_name|>commandpipe_test.py<|end_file_name|><|fim▁begin|># Ant-FS
#
# Copyright (c) 2012, Gustav Tiger <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import array
from ant.fs.commandpipe import parse, CreateFile<|fim▁hole|> # Test create file
data = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09]
request = CreateFile(len(data), 0x80, [0x04, 0x00, 0x00], [0x00, 0xff, 0xff])
print request
print request.get()
# Test create file response
response_data = array.array('B', [2, 0, 0, 0, 4, 0, 0, 0, 128, 4, 123, 0, 103, 0, 0, 0])
response = parse(response_data)
assert response.get_request_id() == 0x04
assert response.get_response() == 0x00
assert response.get_data_type() == 0x80 #FIT
assert response.get_identifier() == array.array('B', [4, 123, 0])
assert response.get_index() == 103<|fim▁end|> |
def main():
|
<|file_name|>revert_osiris.py<|end_file_name|><|fim▁begin|>from __future__ import print_function
import httplib2
import io
import os
import sys
import time
import dateutil.parser
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaIoBaseDownload
import pprint
#Change these to the day of the osiris infestation
YEAR_OF_INFECTION=2017
MONTH_OF_INFECTION=01
DAY_OF_INFECTION=01<|fim▁hole|>
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/drive'
#YOU NEED TO SET UP AN APPLICATION ON GOOGLE AND GENERATE A KEY AND CREATE THIS FILE
CLIENT_SECRET_FILE = 'revert_osiris.json'
APPLICATION_NAME = 'Revert Osiris'
#copy pasta form gdrive API help examples
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'drive-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
pp = pprint.PrettyPrinter()
#grab first batch of possible infected files
results = service.files().list(pageSize=1,
fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
next_page = results.get('nextPageToken', None)
bad_files = []
done = False
next_page = None
while True:
results = service.files().list(pageToken=next_page, pageSize=100,
fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
break
else:
for item in items:
#Only act on files with osiris in the name.
if 'osiris' in item['name']:
bad_files.append(item)
next_page = results.get('nextPageToken', None)
print("Found {} bad files".format(len(bad_files)))
#Download a backup of all files just in case
for bad_item in bad_files:
revisions = service.revisions().list(fileId=bad_item['id'], fields='*').execute()
assert(len(revisions['revisions']) >= 2)
dt = dateutil.parser.parse(revisions['revisions'][-1]['modifiedTime'])
if dt.day == DAY_OF_INFECTION and dt.month = MONTH_OF_INFECTION and dt.year == YEAR_OF_INFECTION:
print("Last revision dates from virus day")
else:
print("Skipping {}, datastamp on file isn't from virus day")
continue
dt = dateutil.parser.parse(revisions['revisions'][-2]['modifiedTime'])
print("Date of second to last revision is: {}".format(dt))
request = service.revisions().get_media(fileId=bad_item['id'],
revisionId=revisions['revisions'][-2]['id'])
#Filenames are not unique in gdrive so append with file ID as well
new_filename = os.path.join('backup',
revisions['revisions'][-2]['originalFilename'] + '_' + bad_item['id'])
#If we are re-running script see if we already downloaded this file
if os.path.isfile(new_filename):
print("File {} already backed up, skipping".format(new_filename))
continue
fh = io.FileIO(new_filename, 'wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print("Download {}".format(int(status.progress() * 100)) )
count = 0
for bad_item in bad_files:
count = count + 1
#Do in batches just to be kind of safe.
if count > 50:
break
file_id = bad_item['id']
revisions = service.revisions().list(fileId=file_id, fields='*').execute()
if len(revisions['revisions']) < 2:
print("File has only 1 revision, skipping: {}".format(bad_item))
continue
file_meta = service.files().get(fileId=file_id, fields='*').execute()
dt_last = dateutil.parser.parse(revisions['revisions'][-1]['modifiedTime'])
dt_2nd_last = dateutil.parser.parse(revisions['revisions'][-2]['modifiedTime'])
if dt_last.day == DAY_OF_INFECTION and dt_last.month == MONTH_OF_INFECTION and dt_last.year == YEAR_OF_INFECTION:
print("Last revision dates from virus day")
else:
print("Skipping {}, datestamp on file isn't from virus day")
continue
orig_file_name = file_meta['originalFilename']
target_rev_name = revisions['revisions'][-2]['originalFilename']
#If the 2nd to last revision is also osiris, we can't simply revert
if 'osiris' in target_rev_name:
print("2nd to last rev filename has osiris in the name, skipping: ({})".format(target_rev_name))
#print out some debug info so we can figure out what we have multipe revisions with osiris
pp.pprint(file_meta)
print(' ')
pp.pprint(revisions)
continue
print("{}: {} revisions found".format(target_rev_name, len(revisions['revisions'])) )
#THESE ARE THE REALLY DANGEROUS STEPS, ONLY UNCOMMMENT IF YOU KNOW WHAT YOU ARE DOING!!!
rev_id_to_delete = revisions['revisions'][-1]['id']
print("service.revisions().delete(fileId={}, revisionId={}).execute()".format(file_id, rev_id_to_delete))
#del_rev = service.revisions().delete(fileId=file_id, revisionId=rev_id_to_delete).execute()
update_body = { 'name': target_rev_name }
print("service.files().update(fileId={}, body={}).execute()".format(file_id, update_body))
#update_name = service.files().update(fileId=file_id, body=update_body).execute()
if __name__ == '__main__':
main()<|fim▁end|> | |
<|file_name|>test_soup.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""Tests of Beautiful Soup as a whole."""
from pdb import set_trace
import logging
import unittest
import sys
import tempfile
from bs4 import (
BeautifulSoup,
BeautifulStoneSoup,
)
from bs4.builder import (
TreeBuilder,
ParserRejectedMarkup,
)
from bs4.element import (
CharsetMetaAttributeValue,
Comment,
ContentMetaAttributeValue,
SoupStrainer,
NamespacedAttribute,
Tag,
NavigableString,
)
import bs4.dammit
from bs4.dammit import (
EntitySubstitution,
UnicodeDammit,
EncodingDetector,
)
from bs4.testing import (
default_builder,
SoupTest,
skipIf,
)
import warnings
try:
from bs4.builder import LXMLTreeBuilder, LXMLTreeBuilderForXML
LXML_PRESENT = True
except ImportError as e:
LXML_PRESENT = False
PYTHON_3_PRE_3_2 = (sys.version_info[0] == 3 and sys.version_info < (3,2))
class TestConstructor(SoupTest):
def test_short_unicode_input(self):
data = "<h1>éé</h1>"
soup = self.soup(data)
self.assertEqual("éé", soup.h1.string)
def test_embedded_null(self):
data = "<h1>foo\0bar</h1>"
soup = self.soup(data)
self.assertEqual("foo\0bar", soup.h1.string)
def test_exclude_encodings(self):
utf8_data = "Räksmörgås".encode("utf-8")
soup = self.soup(utf8_data, exclude_encodings=["utf-8"])
self.assertEqual("windows-1252", soup.original_encoding)
def test_custom_builder_class(self):
# Verify that you can pass in a custom Builder class and
# it'll be instantiated with the appropriate keyword arguments.
class Mock(object):
def __init__(self, **kwargs):
self.called_with = kwargs
self.is_xml = True
self.store_line_numbers = False
self.cdata_list_attributes = []
self.preserve_whitespace_tags = []
self.string_containers = {}
def initialize_soup(self, soup):
pass
def feed(self, markup):
self.fed = markup
def reset(self):
pass
def ignore(self, ignore):
pass
set_up_substitutions = can_be_empty_element = ignore
def prepare_markup(self, *args, **kwargs):
yield "prepared markup", "original encoding", "declared encoding", "contains replacement characters"
kwargs = dict(
var="value",
# This is a deprecated BS3-era keyword argument, which
# will be stripped out.
convertEntities=True,
)
with warnings.catch_warnings(record=True):
soup = BeautifulSoup('', builder=Mock, **kwargs)
assert isinstance(soup.builder, Mock)
self.assertEqual(dict(var="value"), soup.builder.called_with)
self.assertEqual("prepared markup", soup.builder.fed)
# You can also instantiate the TreeBuilder yourself. In this
# case, that specific object is used and any keyword arguments<|fim▁hole|> # to the BeautifulSoup constructor are ignored.
builder = Mock(**kwargs)
with warnings.catch_warnings(record=True) as w:
soup = BeautifulSoup(
'', builder=builder, ignored_value=True,
)
msg = str(w[0].message)
assert msg.startswith("Keyword arguments to the BeautifulSoup constructor will be ignored.")
self.assertEqual(builder, soup.builder)
self.assertEqual(kwargs, builder.called_with)
def test_parser_markup_rejection(self):
# If markup is completely rejected by the parser, an
# explanatory ParserRejectedMarkup exception is raised.
class Mock(TreeBuilder):
def feed(self, *args, **kwargs):
raise ParserRejectedMarkup("Nope.")
def prepare_markup(self, *args, **kwargs):
# We're going to try two different ways of preparing this markup,
# but feed() will reject both of them.
yield markup, None, None, False
yield markup, None, None, False
import re
self.assertRaisesRegex(
ParserRejectedMarkup,
"The markup you provided was rejected by the parser. Trying a different parser or a different encoding may help.",
BeautifulSoup, '', builder=Mock,
)
def test_cdata_list_attributes(self):
# Most attribute values are represented as scalars, but the
# HTML standard says that some attributes, like 'class' have
# space-separated lists as values.
markup = '<a id=" an id " class=" a class "></a>'
soup = self.soup(markup)
# Note that the spaces are stripped for 'class' but not for 'id'.
a = soup.a
self.assertEqual(" an id ", a['id'])
self.assertEqual(["a", "class"], a['class'])
# TreeBuilder takes an argument called 'mutli_valued_attributes' which lets
# you customize or disable this. As always, you can customize the TreeBuilder
# by passing in a keyword argument to the BeautifulSoup constructor.
soup = self.soup(markup, builder=default_builder, multi_valued_attributes=None)
self.assertEqual(" a class ", soup.a['class'])
# Here are two ways of saying that `id` is a multi-valued
# attribute in this context, but 'class' is not.
for switcheroo in ({'*': 'id'}, {'a': 'id'}):
with warnings.catch_warnings(record=True) as w:
# This will create a warning about not explicitly
# specifying a parser, but we'll ignore it.
soup = self.soup(markup, builder=None, multi_valued_attributes=switcheroo)
a = soup.a
self.assertEqual(["an", "id"], a['id'])
self.assertEqual(" a class ", a['class'])
def test_replacement_classes(self):
# Test the ability to pass in replacements for element classes
# which will be used when building the tree.
class TagPlus(Tag):
pass
class StringPlus(NavigableString):
pass
class CommentPlus(Comment):
pass
soup = self.soup(
"<a><b>foo</b>bar</a><!--whee-->",
element_classes = {
Tag: TagPlus,
NavigableString: StringPlus,
Comment: CommentPlus,
}
)
# The tree was built with TagPlus, StringPlus, and CommentPlus objects,
# rather than Tag, String, and Comment objects.
assert all(
isinstance(x, (TagPlus, StringPlus, CommentPlus))
for x in soup.recursiveChildGenerator()
)
def test_alternate_string_containers(self):
# Test the ability to customize the string containers for
# different types of tags.
class PString(NavigableString):
pass
class BString(NavigableString):
pass
soup = self.soup(
"<div>Hello.<p>Here is <b>some <i>bolded</i></b> text",
string_containers = {
'b': BString,
'p': PString,
}
)
# The string before the <p> tag is a regular NavigableString.
assert isinstance(soup.div.contents[0], NavigableString)
# The string inside the <p> tag, but not inside the <i> tag,
# is a PString.
assert isinstance(soup.p.contents[0], PString)
# Every string inside the <b> tag is a BString, even the one that
# was also inside an <i> tag.
for s in soup.b.strings:
assert isinstance(s, BString)
# Now that parsing was complete, the string_container_stack
# (where this information was kept) has been cleared out.
self.assertEqual([], soup.string_container_stack)
class TestWarnings(SoupTest):
def _no_parser_specified(self, s, is_there=True):
v = s.startswith(BeautifulSoup.NO_PARSER_SPECIFIED_WARNING[:80])
self.assertTrue(v)
def test_warning_if_no_parser_specified(self):
with warnings.catch_warnings(record=True) as w:
soup = self.soup("<a><b></b></a>")
msg = str(w[0].message)
self._assert_no_parser_specified(msg)
def test_warning_if_parser_specified_too_vague(self):
with warnings.catch_warnings(record=True) as w:
soup = self.soup("<a><b></b></a>", "html")
msg = str(w[0].message)
self._assert_no_parser_specified(msg)
def test_no_warning_if_explicit_parser_specified(self):
with warnings.catch_warnings(record=True) as w:
soup = self.soup("<a><b></b></a>", "html.parser")
self.assertEqual([], w)
def test_parseOnlyThese_renamed_to_parse_only(self):
with warnings.catch_warnings(record=True) as w:
soup = self.soup("<a><b></b></a>", parseOnlyThese=SoupStrainer("b"))
msg = str(w[0].message)
self.assertTrue("parseOnlyThese" in msg)
self.assertTrue("parse_only" in msg)
self.assertEqual(b"<b></b>", soup.encode())
def test_fromEncoding_renamed_to_from_encoding(self):
with warnings.catch_warnings(record=True) as w:
utf8 = b"\xc3\xa9"
soup = self.soup(utf8, fromEncoding="utf8")
msg = str(w[0].message)
self.assertTrue("fromEncoding" in msg)
self.assertTrue("from_encoding" in msg)
self.assertEqual("utf8", soup.original_encoding)
def test_unrecognized_keyword_argument(self):
self.assertRaises(
TypeError, self.soup, "<a>", no_such_argument=True)
class TestWarnings(SoupTest):
def test_disk_file_warning(self):
filehandle = tempfile.NamedTemporaryFile()
filename = filehandle.name
try:
with warnings.catch_warnings(record=True) as w:
soup = self.soup(filename)
msg = str(w[0].message)
self.assertTrue("looks like a filename" in msg)
finally:
filehandle.close()
# The file no longer exists, so Beautiful Soup will no longer issue the warning.
with warnings.catch_warnings(record=True) as w:
soup = self.soup(filename)
self.assertEqual(0, len(w))
def test_url_warning_with_bytes_url(self):
with warnings.catch_warnings(record=True) as warning_list:
soup = self.soup(b"http://www.crummybytes.com/")
# Be aware this isn't the only warning that can be raised during
# execution..
self.assertTrue(any("looks like a URL" in str(w.message)
for w in warning_list))
def test_url_warning_with_unicode_url(self):
with warnings.catch_warnings(record=True) as warning_list:
# note - this url must differ from the bytes one otherwise
# python's warnings system swallows the second warning
soup = self.soup("http://www.crummyunicode.com/")
self.assertTrue(any("looks like a URL" in str(w.message)
for w in warning_list))
def test_url_warning_with_bytes_and_space(self):
with warnings.catch_warnings(record=True) as warning_list:
soup = self.soup(b"http://www.crummybytes.com/ is great")
self.assertFalse(any("looks like a URL" in str(w.message)
for w in warning_list))
def test_url_warning_with_unicode_and_space(self):
with warnings.catch_warnings(record=True) as warning_list:
soup = self.soup("http://www.crummyuncode.com/ is great")
self.assertFalse(any("looks like a URL" in str(w.message)
for w in warning_list))
class TestSelectiveParsing(SoupTest):
def test_parse_with_soupstrainer(self):
markup = "No<b>Yes</b><a>No<b>Yes <c>Yes</c></b>"
strainer = SoupStrainer("b")
soup = self.soup(markup, parse_only=strainer)
self.assertEqual(soup.encode(), b"<b>Yes</b><b>Yes <c>Yes</c></b>")
class TestEntitySubstitution(unittest.TestCase):
"""Standalone tests of the EntitySubstitution class."""
def setUp(self):
self.sub = EntitySubstitution
def test_simple_html_substitution(self):
# Unicode characters corresponding to named HTML entites
# are substituted, and no others.
s = "foo\u2200\N{SNOWMAN}\u00f5bar"
self.assertEqual(self.sub.substitute_html(s),
"foo∀\N{SNOWMAN}õbar")
def test_smart_quote_substitution(self):
# MS smart quotes are a common source of frustration, so we
# give them a special test.
quotes = b"\x91\x92foo\x93\x94"
dammit = UnicodeDammit(quotes)
self.assertEqual(self.sub.substitute_html(dammit.markup),
"‘’foo“”")
def test_xml_converstion_includes_no_quotes_if_make_quoted_attribute_is_false(self):
s = 'Welcome to "my bar"'
self.assertEqual(self.sub.substitute_xml(s, False), s)
def test_xml_attribute_quoting_normally_uses_double_quotes(self):
self.assertEqual(self.sub.substitute_xml("Welcome", True),
'"Welcome"')
self.assertEqual(self.sub.substitute_xml("Bob's Bar", True),
'"Bob\'s Bar"')
def test_xml_attribute_quoting_uses_single_quotes_when_value_contains_double_quotes(self):
s = 'Welcome to "my bar"'
self.assertEqual(self.sub.substitute_xml(s, True),
"'Welcome to \"my bar\"'")
def test_xml_attribute_quoting_escapes_single_quotes_when_value_contains_both_single_and_double_quotes(self):
s = 'Welcome to "Bob\'s Bar"'
self.assertEqual(
self.sub.substitute_xml(s, True),
'"Welcome to "Bob\'s Bar""')
def test_xml_quotes_arent_escaped_when_value_is_not_being_quoted(self):
quoted = 'Welcome to "Bob\'s Bar"'
self.assertEqual(self.sub.substitute_xml(quoted), quoted)
def test_xml_quoting_handles_angle_brackets(self):
self.assertEqual(
self.sub.substitute_xml("foo<bar>"),
"foo<bar>")
def test_xml_quoting_handles_ampersands(self):
self.assertEqual(self.sub.substitute_xml("AT&T"), "AT&T")
def test_xml_quoting_including_ampersands_when_they_are_part_of_an_entity(self):
self.assertEqual(
self.sub.substitute_xml("ÁT&T"),
"&Aacute;T&T")
def test_xml_quoting_ignoring_ampersands_when_they_are_part_of_an_entity(self):
self.assertEqual(
self.sub.substitute_xml_containing_entities("ÁT&T"),
"ÁT&T")
def test_quotes_not_html_substituted(self):
"""There's no need to do this except inside attribute values."""
text = 'Bob\'s "bar"'
self.assertEqual(self.sub.substitute_html(text), text)
class TestEncodingConversion(SoupTest):
# Test Beautiful Soup's ability to decode and encode from various
# encodings.
def setUp(self):
super(TestEncodingConversion, self).setUp()
self.unicode_data = '<html><head><meta charset="utf-8"/></head><body><foo>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</foo></body></html>'
self.utf8_data = self.unicode_data.encode("utf-8")
# Just so you know what it looks like.
self.assertEqual(
self.utf8_data,
b'<html><head><meta charset="utf-8"/></head><body><foo>Sacr\xc3\xa9 bleu!</foo></body></html>')
def test_ascii_in_unicode_out(self):
# ASCII input is converted to Unicode. The original_encoding
# attribute is set to 'utf-8', a superset of ASCII.
chardet = bs4.dammit.chardet_dammit
logging.disable(logging.WARNING)
try:
def noop(str):
return None
# Disable chardet, which will realize that the ASCII is ASCII.
bs4.dammit.chardet_dammit = noop
ascii = b"<foo>a</foo>"
soup_from_ascii = self.soup(ascii)
unicode_output = soup_from_ascii.decode()
self.assertTrue(isinstance(unicode_output, str))
self.assertEqual(unicode_output, self.document_for(ascii.decode()))
self.assertEqual(soup_from_ascii.original_encoding.lower(), "utf-8")
finally:
logging.disable(logging.NOTSET)
bs4.dammit.chardet_dammit = chardet
def test_unicode_in_unicode_out(self):
# Unicode input is left alone. The original_encoding attribute
# is not set.
soup_from_unicode = self.soup(self.unicode_data)
self.assertEqual(soup_from_unicode.decode(), self.unicode_data)
self.assertEqual(soup_from_unicode.foo.string, 'Sacr\xe9 bleu!')
self.assertEqual(soup_from_unicode.original_encoding, None)
def test_utf8_in_unicode_out(self):
# UTF-8 input is converted to Unicode. The original_encoding
# attribute is set.
soup_from_utf8 = self.soup(self.utf8_data)
self.assertEqual(soup_from_utf8.decode(), self.unicode_data)
self.assertEqual(soup_from_utf8.foo.string, 'Sacr\xe9 bleu!')
def test_utf8_out(self):
# The internal data structures can be encoded as UTF-8.
soup_from_unicode = self.soup(self.unicode_data)
self.assertEqual(soup_from_unicode.encode('utf-8'), self.utf8_data)
@skipIf(
PYTHON_3_PRE_3_2,
"Bad HTMLParser detected; skipping test of non-ASCII characters in attribute name.")
def test_attribute_name_containing_unicode_characters(self):
markup = '<div><a \N{SNOWMAN}="snowman"></a></div>'
self.assertEqual(self.soup(markup).div.encode("utf8"), markup.encode("utf8"))
class TestUnicodeDammit(unittest.TestCase):
"""Standalone tests of UnicodeDammit."""
def test_unicode_input(self):
markup = "I'm already Unicode! \N{SNOWMAN}"
dammit = UnicodeDammit(markup)
self.assertEqual(dammit.unicode_markup, markup)
def test_smart_quotes_to_unicode(self):
markup = b"<foo>\x91\x92\x93\x94</foo>"
dammit = UnicodeDammit(markup)
self.assertEqual(
dammit.unicode_markup, "<foo>\u2018\u2019\u201c\u201d</foo>")
def test_smart_quotes_to_xml_entities(self):
markup = b"<foo>\x91\x92\x93\x94</foo>"
dammit = UnicodeDammit(markup, smart_quotes_to="xml")
self.assertEqual(
dammit.unicode_markup, "<foo>‘’“”</foo>")
def test_smart_quotes_to_html_entities(self):
markup = b"<foo>\x91\x92\x93\x94</foo>"
dammit = UnicodeDammit(markup, smart_quotes_to="html")
self.assertEqual(
dammit.unicode_markup, "<foo>‘’“”</foo>")
def test_smart_quotes_to_ascii(self):
markup = b"<foo>\x91\x92\x93\x94</foo>"
dammit = UnicodeDammit(markup, smart_quotes_to="ascii")
self.assertEqual(
dammit.unicode_markup, """<foo>''""</foo>""")
def test_detect_utf8(self):
utf8 = b"Sacr\xc3\xa9 bleu! \xe2\x98\x83"
dammit = UnicodeDammit(utf8)
self.assertEqual(dammit.original_encoding.lower(), 'utf-8')
self.assertEqual(dammit.unicode_markup, 'Sacr\xe9 bleu! \N{SNOWMAN}')
def test_convert_hebrew(self):
hebrew = b"\xed\xe5\xec\xf9"
dammit = UnicodeDammit(hebrew, ["iso-8859-8"])
self.assertEqual(dammit.original_encoding.lower(), 'iso-8859-8')
self.assertEqual(dammit.unicode_markup, '\u05dd\u05d5\u05dc\u05e9')
def test_dont_see_smart_quotes_where_there_are_none(self):
utf_8 = b"\343\202\261\343\203\274\343\202\277\343\202\244 Watch"
dammit = UnicodeDammit(utf_8)
self.assertEqual(dammit.original_encoding.lower(), 'utf-8')
self.assertEqual(dammit.unicode_markup.encode("utf-8"), utf_8)
def test_ignore_inappropriate_codecs(self):
utf8_data = "Räksmörgås".encode("utf-8")
dammit = UnicodeDammit(utf8_data, ["iso-8859-8"])
self.assertEqual(dammit.original_encoding.lower(), 'utf-8')
def test_ignore_invalid_codecs(self):
utf8_data = "Räksmörgås".encode("utf-8")
for bad_encoding in ['.utf8', '...', 'utF---16.!']:
dammit = UnicodeDammit(utf8_data, [bad_encoding])
self.assertEqual(dammit.original_encoding.lower(), 'utf-8')
def test_exclude_encodings(self):
# This is UTF-8.
utf8_data = "Räksmörgås".encode("utf-8")
# But if we exclude UTF-8 from consideration, the guess is
# Windows-1252.
dammit = UnicodeDammit(utf8_data, exclude_encodings=["utf-8"])
self.assertEqual(dammit.original_encoding.lower(), 'windows-1252')
# And if we exclude that, there is no valid guess at all.
dammit = UnicodeDammit(
utf8_data, exclude_encodings=["utf-8", "windows-1252"])
self.assertEqual(dammit.original_encoding, None)
def test_encoding_detector_replaces_junk_in_encoding_name_with_replacement_character(self):
detected = EncodingDetector(
b'<?xml version="1.0" encoding="UTF-\xdb" ?>')
encodings = list(detected.encodings)
assert 'utf-\N{REPLACEMENT CHARACTER}' in encodings
def test_detect_html5_style_meta_tag(self):
for data in (
b'<html><meta charset="euc-jp" /></html>',
b"<html><meta charset='euc-jp' /></html>",
b"<html><meta charset=euc-jp /></html>",
b"<html><meta charset=euc-jp/></html>"):
dammit = UnicodeDammit(data, is_html=True)
self.assertEqual(
"euc-jp", dammit.original_encoding)
def test_last_ditch_entity_replacement(self):
# This is a UTF-8 document that contains bytestrings
# completely incompatible with UTF-8 (ie. encoded with some other
# encoding).
#
# Since there is no consistent encoding for the document,
# Unicode, Dammit will eventually encode the document as UTF-8
# and encode the incompatible characters as REPLACEMENT
# CHARACTER.
#
# If chardet is installed, it will detect that the document
# can be converted into ISO-8859-1 without errors. This happens
# to be the wrong encoding, but it is a consistent encoding, so the
# code we're testing here won't run.
#
# So we temporarily disable chardet if it's present.
doc = b"""\357\273\277<?xml version="1.0" encoding="UTF-8"?>
<html><b>\330\250\330\252\330\261</b>
<i>\310\322\321\220\312\321\355\344</i></html>"""
chardet = bs4.dammit.chardet_dammit
logging.disable(logging.WARNING)
try:
def noop(str):
return None
bs4.dammit.chardet_dammit = noop
dammit = UnicodeDammit(doc)
self.assertEqual(True, dammit.contains_replacement_characters)
self.assertTrue("\ufffd" in dammit.unicode_markup)
soup = BeautifulSoup(doc, "html.parser")
self.assertTrue(soup.contains_replacement_characters)
finally:
logging.disable(logging.NOTSET)
bs4.dammit.chardet_dammit = chardet
def test_byte_order_mark_removed(self):
# A document written in UTF-16LE will have its byte order marker stripped.
data = b'\xff\xfe<\x00a\x00>\x00\xe1\x00\xe9\x00<\x00/\x00a\x00>\x00'
dammit = UnicodeDammit(data)
self.assertEqual("<a>áé</a>", dammit.unicode_markup)
self.assertEqual("utf-16le", dammit.original_encoding)
def test_detwingle(self):
# Here's a UTF8 document.
utf8 = ("\N{SNOWMAN}" * 3).encode("utf8")
# Here's a Windows-1252 document.
windows_1252 = (
"\N{LEFT DOUBLE QUOTATION MARK}Hi, I like Windows!"
"\N{RIGHT DOUBLE QUOTATION MARK}").encode("windows_1252")
# Through some unholy alchemy, they've been stuck together.
doc = utf8 + windows_1252 + utf8
# The document can't be turned into UTF-8:
self.assertRaises(UnicodeDecodeError, doc.decode, "utf8")
# Unicode, Dammit thinks the whole document is Windows-1252,
# and decodes it into "☃☃☃“Hi, I like Windows!”☃☃☃"
# But if we run it through fix_embedded_windows_1252, it's fixed:
fixed = UnicodeDammit.detwingle(doc)
self.assertEqual(
"☃☃☃“Hi, I like Windows!”☃☃☃", fixed.decode("utf8"))
def test_detwingle_ignores_multibyte_characters(self):
# Each of these characters has a UTF-8 representation ending
# in \x93. \x93 is a smart quote if interpreted as
# Windows-1252. But our code knows to skip over multibyte
# UTF-8 characters, so they'll survive the process unscathed.
for tricky_unicode_char in (
"\N{LATIN SMALL LIGATURE OE}", # 2-byte char '\xc5\x93'
"\N{LATIN SUBSCRIPT SMALL LETTER X}", # 3-byte char '\xe2\x82\x93'
"\xf0\x90\x90\x93", # This is a CJK character, not sure which one.
):
input = tricky_unicode_char.encode("utf8")
self.assertTrue(input.endswith(b'\x93'))
output = UnicodeDammit.detwingle(input)
self.assertEqual(output, input)
def test_find_declared_encoding(self):
# Test our ability to find a declared encoding inside an
# XML or HTML document.
#
# Even if the document comes in as Unicode, it may be
# interesting to know what encoding was claimed
# originally.
html_unicode = '<html><head><meta charset="utf-8"></head></html>'
html_bytes = html_unicode.encode("ascii")
xml_unicode= '<?xml version="1.0" encoding="ISO-8859-1" ?>'
xml_bytes = xml_unicode.encode("ascii")
m = EncodingDetector.find_declared_encoding
self.assertEqual(None, m(html_unicode, is_html=False))
self.assertEqual("utf-8", m(html_unicode, is_html=True))
self.assertEqual("utf-8", m(html_bytes, is_html=True))
self.assertEqual("iso-8859-1", m(xml_unicode))
self.assertEqual("iso-8859-1", m(xml_bytes))
# Normally, only the first few kilobytes of a document are checked for
# an encoding.
spacer = b' ' * 5000
self.assertEqual(None, m(spacer + html_bytes))
self.assertEqual(None, m(spacer + xml_bytes))
# But you can tell find_declared_encoding to search an entire
# HTML document.
self.assertEqual(
"utf-8",
m(spacer + html_bytes, is_html=True, search_entire_document=True)
)
# The XML encoding declaration has to be the very first thing
# in the document. We'll allow whitespace before the document
# starts, but nothing else.
self.assertEqual(
"iso-8859-1",
m(xml_bytes, search_entire_document=True)
)
self.assertEqual(
None, m(b'a' + xml_bytes, search_entire_document=True)
)
class TestNamedspacedAttribute(SoupTest):
def test_name_may_be_none_or_missing(self):
a = NamespacedAttribute("xmlns", None)
self.assertEqual(a, "xmlns")
a = NamespacedAttribute("xmlns")
self.assertEqual(a, "xmlns")
def test_attribute_is_equivalent_to_colon_separated_string(self):
a = NamespacedAttribute("a", "b")
self.assertEqual("a:b", a)
def test_attributes_are_equivalent_if_prefix_and_name_identical(self):
a = NamespacedAttribute("a", "b", "c")
b = NamespacedAttribute("a", "b", "c")
self.assertEqual(a, b)
# The actual namespace is not considered.
c = NamespacedAttribute("a", "b", None)
self.assertEqual(a, c)
# But name and prefix are important.
d = NamespacedAttribute("a", "z", "c")
self.assertNotEqual(a, d)
e = NamespacedAttribute("z", "b", "c")
self.assertNotEqual(a, e)
class TestAttributeValueWithCharsetSubstitution(unittest.TestCase):
def test_content_meta_attribute_value(self):
value = CharsetMetaAttributeValue("euc-jp")
self.assertEqual("euc-jp", value)
self.assertEqual("euc-jp", value.original_value)
self.assertEqual("utf8", value.encode("utf8"))
def test_content_meta_attribute_value(self):
value = ContentMetaAttributeValue("text/html; charset=euc-jp")
self.assertEqual("text/html; charset=euc-jp", value)
self.assertEqual("text/html; charset=euc-jp", value.original_value)
self.assertEqual("text/html; charset=utf8", value.encode("utf8"))<|fim▁end|> | |
<|file_name|>Devloader.py<|end_file_name|><|fim▁begin|>""" Here, we need some documentation...
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import os
import types
import threading
import time
import six
from DIRAC import gLogger
from DIRAC.Core.Utilities.DIRACSingleton import DIRACSingleton
@six.add_metaclass(DIRACSingleton)
class Devloader(object):
def __init__(self):
self.__log = gLogger.getSubLogger("Devloader")
self.__reloaded = False
self.__enabled = True
self.__reloadTask = False
self.__stuffToClose = []
self.__watchedFiles = []
self.__modifyTimes = {}
def addStuffToClose(self, stuff):
self.__stuffToClose.append(stuff)
@property
def enabled(self):
return self.__enabled
def watchFile(self, fp):
if os.path.isfile(fp):
self.__watchedFiles.append(fp)
return True
return False
def __restart(self):
self.__reloaded = True
for stuff in self.__stuffToClose:
try:
self.__log.always("Closing %s" % stuff)
sys.stdout.flush()
stuff.close()
except Exception:
gLogger.exception("Could not close %s" % stuff)
python = sys.executable
os.execl(python, python, * sys.argv)
def bootstrap(self):
if not self.__enabled:
return False
if self.__reloadTask:
return True
self.__reloadTask = threading.Thread(target=self.__reloadOnUpdate)
self.__reloadTask.setDaemon(1)
self.__reloadTask.start()
def __reloadOnUpdate(self):
while True:
time.sleep(1)
if self.__reloaded:
return
for modName in sys.modules:
modObj = sys.modules[modName]
if not isinstance(modObj, types.ModuleType):
continue<|fim▁hole|> if path.endswith(".pyc") or path.endswith(".pyo"):
path = path[:-1]
self.__checkFile(path)
for path in self.__watchedFiles:
self.__checkFile(path)
def __checkFile(self, path):
try:
modified = os.stat(path).st_mtime
except Exception:
return
if path not in self.__modifyTimes:
self.__modifyTimes[path] = modified
return
if self.__modifyTimes[path] != modified:
self.__log.always("File system changed (%s). Restarting..." % (path))
self.__restart()<|fim▁end|> | path = getattr(modObj, "__file__", None)
if not path:
continue |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>mod codec;
mod handshake;<|fim▁hole|>pub use self::codec::ApCodec;
pub use self::handshake::handshake;
use std::io::{self, ErrorKind};
use std::net::ToSocketAddrs;
use futures_util::{SinkExt, StreamExt};
use protobuf::{self, Message, ProtobufError};
use thiserror::Error;
use tokio::net::TcpStream;
use tokio_util::codec::Framed;
use url::Url;
use crate::authentication::Credentials;
use crate::protocol::keyexchange::{APLoginFailed, ErrorCode};
use crate::proxytunnel;
use crate::version;
pub type Transport = Framed<TcpStream, ApCodec>;
fn login_error_message(code: &ErrorCode) -> &'static str {
pub use ErrorCode::*;
match code {
ProtocolError => "Protocol error",
TryAnotherAP => "Try another AP",
BadConnectionId => "Bad connection id",
TravelRestriction => "Travel restriction",
PremiumAccountRequired => "Premium account required",
BadCredentials => "Bad credentials",
CouldNotValidateCredentials => "Could not validate credentials",
AccountExists => "Account exists",
ExtraVerificationRequired => "Extra verification required",
InvalidAppKey => "Invalid app key",
ApplicationBanned => "Application banned",
}
}
#[derive(Debug, Error)]
pub enum AuthenticationError {
#[error("Login failed with reason: {}", login_error_message(.0))]
LoginFailed(ErrorCode),
#[error("Authentication failed: {0}")]
IoError(#[from] io::Error),
}
impl From<ProtobufError> for AuthenticationError {
fn from(e: ProtobufError) -> Self {
io::Error::new(ErrorKind::InvalidData, e).into()
}
}
impl From<APLoginFailed> for AuthenticationError {
fn from(login_failure: APLoginFailed) -> Self {
Self::LoginFailed(login_failure.get_error_code())
}
}
pub async fn connect(addr: String, proxy: Option<&Url>) -> io::Result<Transport> {
let socket = if let Some(proxy_url) = proxy {
info!("Using proxy \"{}\"", proxy_url);
let socket_addr = proxy_url.socket_addrs(|| None).and_then(|addrs| {
addrs.into_iter().next().ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"Can't resolve proxy server address",
)
})
})?;
let socket = TcpStream::connect(&socket_addr).await?;
let uri = addr.parse::<http::Uri>().map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidData,
"Can't parse access point address",
)
})?;
let host = uri.host().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"The access point address contains no hostname",
)
})?;
let port = uri.port().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"The access point address contains no port",
)
})?;
proxytunnel::proxy_connect(socket, host, port.as_str()).await?
} else {
let socket_addr = addr.to_socket_addrs()?.next().ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"Can't resolve access point address",
)
})?;
TcpStream::connect(&socket_addr).await?
};
handshake(socket).await
}
pub async fn authenticate(
transport: &mut Transport,
credentials: Credentials,
device_id: &str,
) -> Result<Credentials, AuthenticationError> {
use crate::protocol::authentication::{APWelcome, ClientResponseEncrypted, CpuFamily, Os};
let mut packet = ClientResponseEncrypted::new();
packet
.mut_login_credentials()
.set_username(credentials.username);
packet
.mut_login_credentials()
.set_typ(credentials.auth_type);
packet
.mut_login_credentials()
.set_auth_data(credentials.auth_data);
packet
.mut_system_info()
.set_cpu_family(CpuFamily::CPU_UNKNOWN);
packet.mut_system_info().set_os(Os::OS_UNKNOWN);
packet
.mut_system_info()
.set_system_information_string(format!(
"librespot_{}_{}",
version::SHA_SHORT,
version::BUILD_ID
));
packet
.mut_system_info()
.set_device_id(device_id.to_string());
packet.set_version_string(version::VERSION_STRING.to_string());
let cmd = 0xab;
let data = packet.write_to_bytes().unwrap();
transport.send((cmd, data)).await?;
let (cmd, data) = transport.next().await.expect("EOF")?;
match cmd {
0xac => {
let welcome_data = APWelcome::parse_from_bytes(data.as_ref())?;
let reusable_credentials = Credentials {
username: welcome_data.get_canonical_username().to_owned(),
auth_type: welcome_data.get_reusable_auth_credentials_type(),
auth_data: welcome_data.get_reusable_auth_credentials().to_owned(),
};
Ok(reusable_credentials)
}
0xad => {
let error_data = APLoginFailed::parse_from_bytes(data.as_ref())?;
Err(error_data.into())
}
_ => {
let msg = format!("Received invalid packet: {}", cmd);
Err(io::Error::new(ErrorKind::InvalidData, msg).into())
}
}
}<|fim▁end|> | |
<|file_name|>dom_manipulation.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::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::event::{EventBubbles, EventCancelable, EventTask, SimpleEventTask};
use dom::eventtarget::EventTarget;
use dom::window::Window;
use script_runtime::{CommonScriptMsg, ScriptThreadEventCategory};
use script_thread::MainThreadScriptMsg;
use servo_atoms::Atom;
use std::fmt;
use std::result::Result;
use std::sync::mpsc::Sender;
use task::{TaskCanceller, TaskOnce};
use task_source::TaskSource;
#[derive(Clone, JSTraceable)]
pub struct DOMManipulationTaskSource(pub Sender<MainThreadScriptMsg>);
impl fmt::Debug for DOMManipulationTaskSource {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DOMManipulationTaskSource(...)")
}
}
impl TaskSource for DOMManipulationTaskSource {
fn queue_with_canceller<T>(
&self,
task: T,
canceller: &TaskCanceller,
) -> Result<(), ()>
where
T: TaskOnce + 'static,
{
let msg = MainThreadScriptMsg::Common(CommonScriptMsg::Task(
ScriptThreadEventCategory::ScriptEvent,
Box::new(canceller.wrap_task(task)),
));
self.0.send(msg).map_err(|_| ())
}
}
impl DOMManipulationTaskSource {
pub fn queue_event(&self,
target: &EventTarget,
name: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable,
window: &Window) {
let target = Trusted::new(target);
let task = EventTask {
target: target,
name: name,
bubbles: bubbles,
cancelable: cancelable,
};
let _ = self.queue(task, window.upcast());
}
<|fim▁hole|> pub fn queue_simple_event(&self, target: &EventTarget, name: Atom, window: &Window) {
let target = Trusted::new(target);
let _ = self.queue(SimpleEventTask { target, name }, window.upcast());
}
}<|fim▁end|> | |
<|file_name|>specialfunctions.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""This module defines some special functions
(originally defined in SpecialFunctions.h)."""
# Copyright (C) 2008-2014 Anders Logg
#
# This file is part of DOLFIN.
#
# DOLFIN 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.
#
# DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>.
#
# Modified by Johan Hake 2008-2009
# Modified by Garth N. Wells 2010
# Modified by Martin S. Alnaes 2013-2014
__all__ = ["MeshCoordinates", "FacetArea", "FacetNormal", "CellSize", "CellVolume",
'SpatialCoordinate', 'CellNormal', 'Circumradius', 'MinFacetEdgeLength', 'MaxFacetEdgeLength']
# Import UFL and SWIG-generated extension module (DOLFIN C++)
import ufl
import dolfin.cpp as cpp
# Local imports
from dolfin.functions.expression import Expression
def _mesh2domain(mesh):
"Deprecation mechanism for symbolic geometry."
if isinstance(mesh, ufl.Cell):
cpp.deprecation("Constructing geometry from a Cell", "1.4", "1.5",
"Pass mesh instead, for example use FacetNormal(mesh) instead of FacetNormal(triangle) or triangle.n")
return ufl.as_domain(mesh)
class MeshCoordinates(Expression, ufl.Coefficient, cpp.MeshCoordinates):
def __init__(self, mesh):
"Create function that evaluates to the mesh coordinates at each vertex."
cpp.MeshCoordinates.__init__(self, mesh)
self._ufl_element = ufl.VectorElement("Lagrange", mesh.ufl_domain(), 1)
ufl.Coefficient.__init__(self, self._ufl_element, count=self.id())
MeshCoordinates.__doc__ = cpp.MeshCoordinates.__doc__
class FacetArea(Expression, ufl.Coefficient, cpp.FacetArea):
def __init__(self, mesh):
"""
Create function that evaluates to the facet area/length on each facet.
*Arguments*
mesh
a :py:class:`Mesh <dolfin.cpp.Mesh>`.
*Example of usage*
.. code-block:: python
mesh = UnitSquare(4,4)
fa = FacetArea(mesh)
"""
cpp.FacetArea.__init__(self, mesh)
self._ufl_element = ufl.FiniteElement("Discontinuous Lagrange", mesh.ufl_domain(), 0)
ufl.Coefficient.__init__(self, self._ufl_element, count=self.id())
FacetArea.__doc__ = cpp.FacetArea.__doc__
# Simple definition of FacetNormal via UFL
def FacetNormal(mesh):
"""
Return symbolic facet normal for given mesh.
*Arguments*
mesh
a :py:class:`Mesh <dolfin.cpp.Mesh>`.
*Example of usage*
.. code-block:: python
mesh = UnitSquare(4,4)
n = FacetNormal(mesh)
"""
return ufl.FacetNormal(_mesh2domain(mesh))
# Simple definition of CellSize via UFL
def CellSize(mesh):
"""
Return function cell size for given mesh.
*Arguments*
mesh
a :py:class:`Mesh <dolfin.cpp.Mesh>`.
*Example of usage*
.. code-block:: python
mesh = UnitSquare(4,4)
h = CellSize(mesh)
"""
return 2.0*ufl.Circumradius(_mesh2domain(mesh))
# Simple definition of CellVolume via UFL
def CellVolume(mesh):
"""
Return symbolic cell volume for given mesh.
*Arguments*
mesh
a :py:class:`Mesh <dolfin.cpp.Mesh>`.
*Example of usage*
.. code-block:: python
mesh = UnitSquare(4,4)
vol = CellVolume(mesh)
"""
return ufl.CellVolume(_mesh2domain(mesh))
# Simple definition of SpatialCoordinate via UFL
def SpatialCoordinate(mesh):
"""
Return symbolic physical coordinates for given mesh.
*Arguments*
mesh
a :py:class:`Mesh <dolfin.cpp.Mesh>`.
*Example of usage*
.. code-block:: python
mesh = UnitSquare(4,4)
vol = SpatialCoordinate(mesh)
"""
return ufl.SpatialCoordinate(_mesh2domain(mesh))
# Simple definition of CellNormal via UFL
def CellNormal(mesh):
"""
Return symbolic cell normal for given manifold mesh.
*Arguments*
mesh
a :py:class:`Mesh <dolfin.cpp.Mesh>`.
*Example of usage*
.. code-block:: python
mesh = UnitSquare(4,4)<|fim▁hole|>
"""
return ufl.CellNormal(_mesh2domain(mesh))
# Simple definition of Circumradius via UFL
def Circumradius(mesh):
"""
Return symbolic cell circumradius for given mesh.
*Arguments*
mesh
a :py:class:`Mesh <dolfin.cpp.Mesh>`.
*Example of usage*
.. code-block:: python
mesh = UnitSquare(4,4)
vol = Circumradius(mesh)
"""
return ufl.Circumradius(_mesh2domain(mesh))
# Simple definition of MinFacetEdgeLength via UFL
def MinFacetEdgeLength(mesh):
"""
Return symbolic minimum facet edge length of a cell for given mesh.
*Arguments*
mesh
a :py:class:`Mesh <dolfin.cpp.Mesh>`.
*Example of usage*
.. code-block:: python
mesh = UnitSquare(4,4)
vol = MinFacetEdgeLength(mesh)
"""
return ufl.MinFacetEdgeLength(_mesh2domain(mesh))
# Simple definition of MaxFacetEdgeLength via UFL
def MaxFacetEdgeLength(mesh):
"""
Return symbolic maximum facet edge length of a cell for given mesh.
*Arguments*
mesh
a :py:class:`Mesh <dolfin.cpp.Mesh>`.
*Example of usage*
.. code-block:: python
mesh = UnitSquare(4,4)
vol = MaxFacetEdgeLength(mesh)
"""
return ufl.MaxFacetEdgeLength(_mesh2domain(mesh))<|fim▁end|> | vol = CellNormal(mesh) |
<|file_name|>app.js<|end_file_name|><|fim▁begin|>'use strict';
var consoleBaseUrl = window.location.href;
consoleBaseUrl = consoleBaseUrl.substring(0, consoleBaseUrl.indexOf("/console"));
consoleBaseUrl = consoleBaseUrl + "/console";
var configUrl = consoleBaseUrl + "/config";
var auth = {};
var resourceBundle;
var locale = 'en';
var module = angular.module('keycloak', [ 'keycloak.services', 'keycloak.loaders', 'ui.bootstrap', 'ui.select2', 'angularFileUpload', 'angularTreeview', 'pascalprecht.translate', 'ngCookies', 'ngSanitize', 'ui.ace']);
var resourceRequests = 0;
var loadingTimer = -1;
angular.element(document).ready(function () {
var keycloakAuth = new Keycloak(configUrl);
function whoAmI(success, error) {
var req = new XMLHttpRequest();
req.open('GET', consoleBaseUrl + "/whoami", true);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Authorization', 'bearer ' + keycloakAuth.token);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
var data = JSON.parse(req.responseText);
success(data);
} else {
error();
}
}
}
req.send();
}
function loadResourceBundle(success, error) {
var req = new XMLHttpRequest();
req.open('GET', consoleBaseUrl + '/messages.json?lang=' + locale, true);
req.setRequestHeader('Accept', 'application/json');
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
var data = JSON.parse(req.responseText);
success && success(data);
} else {
error && error();
}
}
}
req.send();
}
function hasAnyAccess(user) {
return user && user['realm_access'];
}
keycloakAuth.onAuthLogout = function() {
location.reload();
}
keycloakAuth.init({ onLoad: 'login-required' }).success(function () {
auth.authz = keycloakAuth;
if (auth.authz.idTokenParsed.locale) {
locale = auth.authz.idTokenParsed.locale;
}
auth.refreshPermissions = function(success, error) {
whoAmI(function(data) {
auth.user = data;
auth.loggedIn = true;
auth.hasAnyAccess = hasAnyAccess(data);
success();
}, function() {
error();
});
};
loadResourceBundle(function(data) {
resourceBundle = data;
auth.refreshPermissions(function () {
module.factory('Auth', function () {
return auth;
});
var injector = angular.bootstrap(document, ["keycloak"]);
injector.get('$translate')('consoleTitle').then(function (consoleTitle) {
document.title = consoleTitle;
});
});
});
}).error(function () {
window.location.reload();
});
});
module.factory('authInterceptor', function($q, Auth) {
return {
request: function (config) {
if (!config.url.match(/.html$/)) {
var deferred = $q.defer();
if (Auth.authz.token) {
Auth.authz.updateToken(5).success(function () {
config.headers = config.headers || {};
config.headers.Authorization = 'Bearer ' + Auth.authz.token;
deferred.resolve(config);
}).error(function () {
location.reload();
});
}
return deferred.promise;
} else {
return config;
}
}
};
});
module.config(['$translateProvider', function($translateProvider) {
$translateProvider.useSanitizeValueStrategy('sanitizeParameters');
$translateProvider.preferredLanguage(locale);
$translateProvider.translations(locale, resourceBundle);
}]);
module.config([ '$routeProvider', function($routeProvider) {
$routeProvider
.when('/create/realm', {
templateUrl : resourceUrl + '/partials/realm-create.html',
resolve : {
},
controller : 'RealmCreateCtrl'
})
.when('/realms/:realm', {
templateUrl : resourceUrl + '/partials/realm-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmDetailCtrl'
})
.when('/realms/:realm/login-settings', {
templateUrl : resourceUrl + '/partials/realm-login-settings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfo) {
return ServerInfo.delay;
}
},
controller : 'RealmLoginSettingsCtrl'
})
.when('/realms/:realm/theme-settings', {
templateUrl : resourceUrl + '/partials/realm-theme-settings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmThemeCtrl'
})
.when('/realms/:realm/cache-settings', {
templateUrl : resourceUrl + '/partials/realm-cache-settings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmCacheCtrl'
})
.when('/realms', {
templateUrl : resourceUrl + '/partials/realm-list.html',
controller : 'RealmListCtrl'
})
.when('/realms/:realm/token-settings', {
templateUrl : resourceUrl + '/partials/realm-tokens.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmTokenDetailCtrl'
})
.when('/realms/:realm/client-initial-access', {
templateUrl : resourceUrl + '/partials/client-initial-access.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clientInitialAccess : function(ClientInitialAccessLoader) {
return ClientInitialAccessLoader();
},
clientRegTrustedHosts : function(ClientRegistrationTrustedHostListLoader) {
return ClientRegistrationTrustedHostListLoader();
}
},
controller : 'ClientInitialAccessCtrl'
})
.when('/realms/:realm/client-initial-access/create', {
templateUrl : resourceUrl + '/partials/client-initial-access-create.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'ClientInitialAccessCreateCtrl'
})
.when('/realms/:realm/client-reg-trusted-hosts/create', {
templateUrl : resourceUrl + '/partials/client-reg-trusted-host-create.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clientRegTrustedHost : function() {
return {};
}
},
controller : 'ClientRegistrationTrustedHostDetailCtrl'
})
.when('/realms/:realm/client-reg-trusted-hosts/:hostname', {
templateUrl : resourceUrl + '/partials/client-reg-trusted-host-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clientRegTrustedHost : function(ClientRegistrationTrustedHostLoader) {
return ClientRegistrationTrustedHostLoader();
}
},
controller : 'ClientRegistrationTrustedHostDetailCtrl'
})
.when('/realms/:realm/keys-settings', {
templateUrl : resourceUrl + '/partials/realm-keys.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmKeysDetailCtrl'
})
.when('/realms/:realm/identity-provider-settings', {
templateUrl : resourceUrl + '/partials/realm-identity-provider.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
instance : function(IdentityProviderLoader) {
return {};
},
providerFactory : function(IdentityProviderFactoryLoader) {
return {};
},
authFlows : function(AuthenticationFlowsLoader) {
return {};
}
},
controller : 'RealmIdentityProviderCtrl'
})
.when('/create/identity-provider/:realm/:provider_id', {
templateUrl : function(params){ return resourceUrl + '/partials/realm-identity-provider-' + params.provider_id + '.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
instance : function(IdentityProviderLoader) {
return {};
},
providerFactory : function(IdentityProviderFactoryLoader) {
return new IdentityProviderFactoryLoader();
},
authFlows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
}
},
controller : 'RealmIdentityProviderCtrl'
})
.when('/realms/:realm/identity-provider-settings/provider/:provider_id/:alias', {
templateUrl : function(params){ return resourceUrl + '/partials/realm-identity-provider-' + params.provider_id + '.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
instance : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
providerFactory : function(IdentityProviderFactoryLoader) {
return IdentityProviderFactoryLoader();
},
authFlows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
}
},
controller : 'RealmIdentityProviderCtrl'
})
.when('/realms/:realm/identity-provider-settings/provider/:provider_id/:alias/export', {
templateUrl : resourceUrl + '/partials/realm-identity-provider-export.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
providerFactory : function(IdentityProviderFactoryLoader) {
return IdentityProviderFactoryLoader();
}
},
controller : 'RealmIdentityProviderExportCtrl'
})
.when('/realms/:realm/identity-provider-mappers/:alias/mappers', {
templateUrl : function(params){ return resourceUrl + '/partials/identity-provider-mappers.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
mapperTypes : function(IdentityProviderMapperTypesLoader) {
return IdentityProviderMapperTypesLoader();
},
mappers : function(IdentityProviderMappersLoader) {
return IdentityProviderMappersLoader();
}
},
controller : 'IdentityProviderMapperListCtrl'
})
.when('/realms/:realm/identity-provider-mappers/:alias/mappers/:mapperId', {
templateUrl : function(params){ return resourceUrl + '/partials/identity-provider-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
mapperTypes : function(IdentityProviderMapperTypesLoader) {
return IdentityProviderMapperTypesLoader();
},
mapper : function(IdentityProviderMapperLoader) {
return IdentityProviderMapperLoader();
}
},
controller : 'IdentityProviderMapperCtrl'
})
.when('/create/identity-provider-mappers/:realm/:alias', {
templateUrl : function(params){ return resourceUrl + '/partials/identity-provider-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
mapperTypes : function(IdentityProviderMapperTypesLoader) {
return IdentityProviderMapperTypesLoader();
}
},
controller : 'IdentityProviderMapperCreateCtrl'
})
.when('/realms/:realm/default-roles', {
templateUrl : resourceUrl + '/partials/realm-default-roles.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
}
},
controller : 'RealmDefaultRolesCtrl'
})
.when('/realms/:realm/smtp-settings', {
templateUrl : resourceUrl + '/partials/realm-smtp.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmSMTPSettingsCtrl'
})
.when('/realms/:realm/events', {
templateUrl : resourceUrl + '/partials/realm-events.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmEventsCtrl'
})
.when('/realms/:realm/admin-events', {
templateUrl : resourceUrl + '/partials/realm-events-admin.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmAdminEventsCtrl'
})
.when('/realms/:realm/events-settings', {
templateUrl : resourceUrl + '/partials/realm-events-config.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
eventsConfig : function(RealmEventsConfigLoader) {
return RealmEventsConfigLoader();
}
},
controller : 'RealmEventsConfigCtrl'
})
.when('/realms/:realm/partial-import', {
templateUrl : resourceUrl + '/partials/partial-import.html',
resolve : {
resourceName : function() { return 'users'},
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmImportCtrl'
})
.when('/create/user/:realm', {
templateUrl : resourceUrl + '/partials/user-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function() {
return {};
}
},
controller : 'UserDetailCtrl'
})
.when('/realms/:realm/users/:user', {
templateUrl : resourceUrl + '/partials/user-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
}
},
controller : 'UserDetailCtrl'
})
.when('/realms/:realm/users/:user/user-attributes', {
templateUrl : resourceUrl + '/partials/user-attributes.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
}
},
controller : 'UserDetailCtrl'
})
.when('/realms/:realm/users/:user/user-credentials', {
templateUrl : resourceUrl + '/partials/user-credentials.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
}
},
controller : 'UserCredentialsCtrl'
})
.when('/realms/:realm/users/:user/role-mappings', {
templateUrl : resourceUrl + '/partials/role-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function() {
return {};
}
},
controller : 'UserRoleMappingCtrl'
})
.when('/realms/:realm/users/:user/groups', {
templateUrl : resourceUrl + '/partials/user-group-membership.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
groups : function(GroupListLoader) {
return GroupListLoader();
}
},
controller : 'UserGroupMembershipCtrl'
})
.when('/realms/:realm/users/:user/sessions', {
templateUrl : resourceUrl + '/partials/user-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
sessions : function(UserSessionsLoader) {
return UserSessionsLoader();
}
},
controller : 'UserSessionsCtrl'
})
.when('/realms/:realm/users/:user/federated-identity', {
templateUrl : resourceUrl + '/partials/user-federated-identity-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
federatedIdentities : function(UserFederatedIdentityLoader) {
return UserFederatedIdentityLoader();
}
},
controller : 'UserFederatedIdentityCtrl'
})
.when('/create/federated-identity/:realm/:user', {
templateUrl : resourceUrl + '/partials/user-federated-identity-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
federatedIdentities : function(UserFederatedIdentityLoader) {
return UserFederatedIdentityLoader();
}
},
controller : 'UserFederatedIdentityAddCtrl'
})
.when('/realms/:realm/users/:user/consents', {
templateUrl : resourceUrl + '/partials/user-consents.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
userConsents : function(UserConsentsLoader) {
return UserConsentsLoader();
}
},
controller : 'UserConsentsCtrl'
})
.when('/realms/:realm/users/:user/offline-sessions/:client', {
templateUrl : resourceUrl + '/partials/user-offline-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
offlineSessions : function(UserOfflineSessionsLoader) {
return UserOfflineSessionsLoader();
}
},
controller : 'UserOfflineSessionsCtrl'
})
.when('/realms/:realm/users', {
templateUrl : resourceUrl + '/partials/user-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'UserListCtrl'
})
.when('/create/role/:realm', {
templateUrl : resourceUrl + '/partials/role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
role : function() {
return {};
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'RoleDetailCtrl'
})
.when('/realms/:realm/roles/:role', {
templateUrl : resourceUrl + '/partials/role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
role : function(RoleLoader) {
return RoleLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'RoleDetailCtrl'
})
.when('/realms/:realm/roles', {
templateUrl : resourceUrl + '/partials/role-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
}
},
controller : 'RoleListCtrl'
})
.when('/realms/:realm/groups', {
templateUrl : resourceUrl + '/partials/group-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
groups : function(GroupListLoader) {
return GroupListLoader();
}
},
controller : 'GroupListCtrl'
})
.when('/create/group/:realm/parent/:parentId', {
templateUrl : resourceUrl + '/partials/create-group.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
parentId : function($route) {
return $route.current.params.parentId;
}
},
controller : 'GroupCreateCtrl'
})
.when('/realms/:realm/groups/:group', {
templateUrl : resourceUrl + '/partials/group-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
}
},
controller : 'GroupDetailCtrl'
})
.when('/realms/:realm/groups/:group/attributes', {
templateUrl : resourceUrl + '/partials/group-attributes.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
}
},
controller : 'GroupDetailCtrl'
})
.when('/realms/:realm/groups/:group/members', {
templateUrl : resourceUrl + '/partials/group-members.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
}
},
controller : 'GroupMembersCtrl'
})
.when('/realms/:realm/groups/:group/role-mappings', {
templateUrl : resourceUrl + '/partials/group-role-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function() {
return {};
}
},
controller : 'GroupRoleMappingCtrl'
})
.when('/realms/:realm/default-groups', {
templateUrl : resourceUrl + '/partials/default-groups.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
groups : function(GroupListLoader) {
return GroupListLoader();
}
},
controller : 'DefaultGroupsCtrl'
})
.when('/create/role/:realm/clients/:client', {
templateUrl : resourceUrl + '/partials/client-role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
role : function() {
return {};
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientRoleDetailCtrl'
})
.when('/realms/:realm/clients/:client/roles/:role', {
templateUrl : resourceUrl + '/partials/client-role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
role : function(ClientRoleLoader) {
return ClientRoleLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientRoleDetailCtrl'
})
.when('/realms/:realm/clients/:client/mappers', {
templateUrl : resourceUrl + '/partials/client-mappers.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientProtocolMapperListCtrl'
})
.when('/realms/:realm/clients/:client/add-mappers', {
templateUrl : resourceUrl + '/partials/client-mappers-add.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'AddBuiltinProtocolMapperCtrl'
})
.when('/realms/:realm/clients/:client/mappers/:id', {
templateUrl : resourceUrl + '/partials/client-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
mapper : function(ClientProtocolMapperLoader) {
return ClientProtocolMapperLoader();
}
},
controller : 'ClientProtocolMapperCtrl'
})
.when('/create/client/:realm/:client/mappers', {
templateUrl : resourceUrl + '/partials/client-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientProtocolMapperCreateCtrl'
})
.when('/realms/:realm/client-templates/:template/mappers', {
templateUrl : resourceUrl + '/partials/client-template-mappers.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateProtocolMapperListCtrl'
})
.when('/realms/:realm/client-templates/:template/add-mappers', {
templateUrl : resourceUrl + '/partials/client-template-mappers-add.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateAddBuiltinProtocolMapperCtrl'
})
.when('/realms/:realm/client-templates/:template/mappers/:id', {
templateUrl : resourceUrl + '/partials/client-template-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
mapper : function(ClientTemplateProtocolMapperLoader) {
return ClientTemplateProtocolMapperLoader();
}
},
controller : 'ClientTemplateProtocolMapperCtrl'
})
.when('/create/client-template/:realm/:template/mappers', {
templateUrl : resourceUrl + '/partials/client-template-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
}
},
controller : 'ClientTemplateProtocolMapperCreateCtrl'
})
.when('/realms/:realm/clients/:client/sessions', {
templateUrl : resourceUrl + '/partials/client-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
sessionCount : function(ClientSessionCountLoader) {
return ClientSessionCountLoader();
}
},
controller : 'ClientSessionsCtrl'
})
.when('/realms/:realm/clients/:client/offline-access', {
templateUrl : resourceUrl + '/partials/client-offline-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
offlineSessionCount : function(ClientOfflineSessionCountLoader) {
return ClientOfflineSessionCountLoader();
}
},
controller : 'ClientOfflineSessionsCtrl'
})
.when('/realms/:realm/clients/:client/credentials', {
templateUrl : resourceUrl + '/partials/client-credentials.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
clientAuthenticatorProviders : function(ClientAuthenticatorProvidersLoader) {
return ClientAuthenticatorProvidersLoader();
},
clientConfigProperties: function(PerClientAuthenticationConfigDescriptionLoader) {
return PerClientAuthenticationConfigDescriptionLoader();
}
},
controller : 'ClientCredentialsCtrl'
})
.when('/realms/:realm/clients/:client/credentials/client-jwt/:keyType/import/:attribute', {
templateUrl : resourceUrl + '/partials/client-credentials-jwt-key-import.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "jwt-credentials";
}
},
controller : 'ClientCertificateImportCtrl'
})
.when('/realms/:realm/clients/:client/credentials/client-jwt/:keyType/export/:attribute', {
templateUrl : resourceUrl + '/partials/client-credentials-jwt-key-export.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "jwt-credentials";
}
},
controller : 'ClientCertificateExportCtrl'
})
.when('/realms/:realm/clients/:client/identity-provider', {
templateUrl : resourceUrl + '/partials/client-identity-provider.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientIdentityProviderCtrl'
})
.when('/realms/:realm/clients/:client/clustering', {
templateUrl : resourceUrl + '/partials/client-clustering.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientClusteringCtrl'
})
.when('/register-node/realms/:realm/clients/:client/clustering', {
templateUrl : resourceUrl + '/partials/client-clustering-node.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientClusteringNodeCtrl'
})
.when('/realms/:realm/clients/:client/clustering/:node', {
templateUrl : resourceUrl + '/partials/client-clustering-node.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientClusteringNodeCtrl'
})
.when('/realms/:realm/clients/:client/saml/keys', {
templateUrl : resourceUrl + '/partials/client-saml-keys.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientSamlKeyCtrl'
})
.when('/realms/:realm/clients/:client/saml/:keyType/import/:attribute', {
templateUrl : resourceUrl + '/partials/client-saml-key-import.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "saml";
}
},
controller : 'ClientCertificateImportCtrl'
})
.when('/realms/:realm/clients/:client/saml/:keyType/export/:attribute', {
templateUrl : resourceUrl + '/partials/client-saml-key-export.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "saml";
}
},
controller : 'ClientCertificateExportCtrl'
})
.when('/realms/:realm/clients/:client/roles', {
templateUrl : resourceUrl + '/partials/client-role-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
roles : function(ClientRoleListLoader) {
return ClientRoleListLoader();
}
},
controller : 'ClientRoleListCtrl'
})
.when('/realms/:realm/clients/:client/revocation', {
templateUrl : resourceUrl + '/partials/client-revocation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientRevocationCtrl'
})
.when('/realms/:realm/clients/:client/scope-mappings', {
templateUrl : resourceUrl + '/partials/client-scope-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientScopeMappingCtrl'
})
.when('/realms/:realm/clients/:client/installation', {
templateUrl : resourceUrl + '/partials/client-installation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientInstallationCtrl'
})
.when('/realms/:realm/clients/:client/service-account-roles', {
templateUrl : resourceUrl + '/partials/client-service-account-roles.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(ClientServiceAccountUserLoader) {
return ClientServiceAccountUserLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'UserRoleMappingCtrl'
})
.when('/create/client/:realm', {
templateUrl : resourceUrl + '/partials/create-client.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function() {
return {};
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'CreateClientCtrl'
})
.when('/realms/:realm/clients/:client', {
templateUrl : resourceUrl + '/partials/client-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientDetailCtrl'
})
.when('/create/client-template/:realm', {
templateUrl : resourceUrl + '/partials/client-template-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
template : function() {
return {};
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateDetailCtrl'
})
.when('/realms/:realm/client-templates/:template', {
templateUrl : resourceUrl + '/partials/client-template-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateDetailCtrl'
})
.when('/realms/:realm/client-templates/:template/scope-mappings', {
templateUrl : resourceUrl + '/partials/client-template-scope-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientTemplateScopeMappingCtrl'
})
.when('/realms/:realm/clients', {
templateUrl : resourceUrl + '/partials/client-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientListCtrl'
})
.when('/realms/:realm/client-templates', {
templateUrl : resourceUrl + '/partials/client-template-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateListCtrl'
})
.when('/import/client/:realm', {
templateUrl : resourceUrl + '/partials/client-import.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientImportCtrl'
})
.when('/', {
templateUrl : resourceUrl + '/partials/home.html',
controller : 'HomeCtrl'
})
.when('/mocks/:realm', {
templateUrl : resourceUrl + '/partials/realm-detail_mock.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmDetailCtrl'
})
.when('/realms/:realm/sessions/revocation', {
templateUrl : resourceUrl + '/partials/session-revocation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmRevocationCtrl'
})
.when('/realms/:realm/sessions/realm', {
templateUrl : resourceUrl + '/partials/session-realm.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
stats : function(RealmClientSessionStatsLoader) {
return RealmClientSessionStatsLoader();
}
},
controller : 'RealmSessionStatsCtrl'
})
.when('/create/user-storage/:realm/providers/:provider', {
templateUrl : resourceUrl + '/partials/user-storage-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {
};
},
providerId : function($route) {
return $route.current.params.provider;
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'GenericUserStorageCtrl'
})
.when('/realms/:realm/user-storage/providers/:provider/:componentId', {
templateUrl : resourceUrl + '/partials/user-storage-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(ComponentLoader) {
return ComponentLoader();
},
providerId : function($route) {
return $route.current.params.provider;
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'GenericUserStorageCtrl'
})
.when('/realms/:realm/user-federation', {
templateUrl : resourceUrl + '/partials/user-federation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'UserFederationCtrl'
})
.when('/realms/:realm/user-federation/providers/ldap/:instance', {
templateUrl : resourceUrl + '/partials/federated-ldap.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
}
},
controller : 'LDAPCtrl'
})
.when('/create/user-federation/:realm/providers/ldap', {
templateUrl : resourceUrl + '/partials/federated-ldap.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {};
}
},
controller : 'LDAPCtrl'
})
.when('/realms/:realm/user-federation/providers/kerberos/:instance', {
templateUrl : resourceUrl + '/partials/federated-kerberos.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
providerFactory : function() {
return { id: "kerberos" };
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/create/user-federation/:realm/providers/kerberos', {
templateUrl : resourceUrl + '/partials/federated-kerberos.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {};
},
providerFactory : function() {
return { id: "kerberos" };
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/create/user-federation/:realm/providers/:provider', {
templateUrl : resourceUrl + '/partials/federated-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {
};
},
providerFactory : function(UserFederationFactoryLoader) {
return UserFederationFactoryLoader();
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/realms/:realm/user-federation/providers/:provider/:instance', {
templateUrl : resourceUrl + '/partials/federated-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
providerFactory : function(UserFederationFactoryLoader) {
return UserFederationFactoryLoader();
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/realms/:realm/user-federation/providers/:provider/:instance/mappers', {
templateUrl : function(params){ return resourceUrl + '/partials/federated-mappers.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
provider : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
mapperTypes : function(UserFederationMapperTypesLoader) {
return UserFederationMapperTypesLoader();
},
mappers : function(UserFederationMappersLoader) {
return UserFederationMappersLoader();
}
},
controller : 'UserFederationMapperListCtrl'
})
.when('/realms/:realm/user-federation/providers/:provider/:instance/mappers/:mapperId', {
templateUrl : function(params){ return resourceUrl + '/partials/federated-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
provider : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
mapperTypes : function(UserFederationMapperTypesLoader) {
return UserFederationMapperTypesLoader();
},
mapper : function(UserFederationMapperLoader) {
return UserFederationMapperLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'UserFederationMapperCtrl'
})
.when('/create/user-federation-mappers/:realm/:provider/:instance', {
templateUrl : function(params){ return resourceUrl + '/partials/federated-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
provider : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
mapperTypes : function(UserFederationMapperTypesLoader) {
return UserFederationMapperTypesLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'UserFederationMapperCreateCtrl'
})
.when('/realms/:realm/defense/headers', {
templateUrl : resourceUrl + '/partials/defense-headers.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'DefenseHeadersCtrl'
})
.when('/realms/:realm/defense/brute-force', {
templateUrl : resourceUrl + '/partials/brute-force.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmBruteForceCtrl'
})
.when('/realms/:realm/protocols', {
templateUrl : resourceUrl + '/partials/protocol-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ProtocolListCtrl'
})
.when('/realms/:realm/authentication/flows', {
templateUrl : resourceUrl + '/partials/authentication-flows.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
},
selectedFlow : function() {
return null;
}
},
controller : 'AuthenticationFlowsCtrl'
})
.when('/realms/:realm/authentication/flow-bindings', {
templateUrl : resourceUrl + '/partials/authentication-flow-bindings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
},
serverInfo : function(ServerInfo) {
return ServerInfo.delay;
}
},
controller : 'RealmFlowBindingCtrl'
})
.when('/realms/:realm/authentication/flows/:flow', {
templateUrl : resourceUrl + '/partials/authentication-flows.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
},
selectedFlow : function($route) {
return $route.current.params.flow;
}
},
controller : 'AuthenticationFlowsCtrl'
})
.when('/realms/:realm/authentication/flows/:flow/create/execution/:topFlow', {
templateUrl : resourceUrl + '/partials/create-execution.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
topFlow: function($route) {
return $route.current.params.topFlow;
},
parentFlow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
formActionProviders : function(AuthenticationFormActionProvidersLoader) {
return AuthenticationFormActionProvidersLoader();
},
authenticatorProviders : function(AuthenticatorProvidersLoader) {
return AuthenticatorProvidersLoader();
},
clientAuthenticatorProviders : function(ClientAuthenticatorProvidersLoader) {
return ClientAuthenticatorProvidersLoader();
}
},
controller : 'CreateExecutionCtrl'
})
.when('/realms/:realm/authentication/flows/:flow/create/flow/execution/:topFlow', {
templateUrl : resourceUrl + '/partials/create-flow-execution.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
topFlow: function($route) {
return $route.current.params.topFlow;
},
parentFlow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
formProviders : function(AuthenticationFormProvidersLoader) {
return AuthenticationFormProvidersLoader();
}
},
controller : 'CreateExecutionFlowCtrl'
})
.when('/realms/:realm/authentication/create/flow', {
templateUrl : resourceUrl + '/partials/create-flow.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'CreateFlowCtrl'
})
.when('/realms/:realm/authentication/required-actions', {
templateUrl : resourceUrl + '/partials/required-actions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
unregisteredRequiredActions : function(UnregisteredRequiredActionsListLoader) {
return UnregisteredRequiredActionsListLoader();
}
},
controller : 'RequiredActionsCtrl'
})
.when('/realms/:realm/authentication/password-policy', {
templateUrl : resourceUrl + '/partials/password-policy.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmPasswordPolicyCtrl'
})
.when('/realms/:realm/authentication/otp-policy', {
templateUrl : resourceUrl + '/partials/otp-policy.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfo) {
return ServerInfo.delay;
}
},
controller : 'RealmOtpPolicyCtrl'
})
.when('/realms/:realm/authentication/flows/:flow/config/:provider/:config', {
templateUrl : resourceUrl + '/partials/authenticator-config.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
configType : function(AuthenticationConfigDescriptionLoader) {
return AuthenticationConfigDescriptionLoader();
},
config : function(AuthenticationConfigLoader) {
return AuthenticationConfigLoader();
}
},
controller : 'AuthenticationConfigCtrl'
})
.when('/create/authentication/:realm/flows/:flow/execution/:executionId/provider/:provider', {
templateUrl : resourceUrl + '/partials/authenticator-config.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
configType : function(AuthenticationConfigDescriptionLoader) {
return AuthenticationConfigDescriptionLoader();
},
execution : function(ExecutionIdLoader) {
return ExecutionIdLoader();
}
},
controller : 'AuthenticationConfigCreateCtrl'
})
.when('/server-info', {
templateUrl : resourceUrl + '/partials/server-info.html',
resolve : {
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ServerInfoCtrl'
})
.when('/server-info/providers', {
templateUrl : resourceUrl + '/partials/server-info-providers.html',
resolve : {
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ServerInfoCtrl'
})
.when('/logout', {
templateUrl : resourceUrl + '/partials/home.html',
controller : 'LogoutCtrl'
})
.when('/notfound', {
templateUrl : resourceUrl + '/partials/notfound.html'
})
.when('/forbidden', {
templateUrl : resourceUrl + '/partials/forbidden.html'
})
.otherwise({
templateUrl : resourceUrl + '/partials/pagenotfound.html'
});
} ]);
module.config(function($httpProvider) {
$httpProvider.interceptors.push('errorInterceptor');
var spinnerFunction = function(data, headersGetter) {
if (resourceRequests == 0) {
loadingTimer = window.setTimeout(function() {
$('#loading').show();
loadingTimer = -1;
}, 500);
}
resourceRequests++;
return data;
};
$httpProvider.defaults.transformRequest.push(spinnerFunction);
$httpProvider.interceptors.push('spinnerInterceptor');
$httpProvider.interceptors.push('authInterceptor');
});
module.factory('spinnerInterceptor', function($q, $window, $rootScope, $location) {
return {
response: function(response) {
resourceRequests--;
if (resourceRequests == 0) {
if(loadingTimer != -1) {
window.clearTimeout(loadingTimer);
loadingTimer = -1;
}
$('#loading').hide();
}
return response;
},
responseError: function(response) {
resourceRequests--;
if (resourceRequests == 0) {
if(loadingTimer != -1) {
window.clearTimeout(loadingTimer);
loadingTimer = -1;
}
$('#loading').hide();
}
return $q.reject(response);
}
};
});
module.factory('errorInterceptor', function($q, $window, $rootScope, $location, Notifications, Auth) {
return {
response: function(response) {
return response;
},
responseError: function(response) {
if (response.status == 401) {
Auth.authz.logout();
} else if (response.status == 403) {
$location.path('/forbidden');
} else if (response.status == 404) {
$location.path('/notfound');
} else if (response.status) {
if (response.data && response.data.errorMessage) {
Notifications.error(response.data.errorMessage);
} else {
Notifications.error("An unexpected server error has occurred");
}
}
return $q.reject(response);
}
};
});
// collapsable form fieldsets
module.directive('collapsable', function() {
return function(scope, element, attrs) {
element.click(function() {
$(this).toggleClass('collapsed');
$(this).find('.toggle-icons').toggleClass('kc-icon-collapse').toggleClass('kc-icon-expand');
$(this).find('.toggle-icons').text($(this).text() == "Icon: expand" ? "Icon: collapse" : "Icon: expand");
$(this).parent().find('.form-group').toggleClass('hidden');
});
}
});
// collapsable form fieldsets
module.directive('uncollapsed', function() {
return function(scope, element, attrs) {
element.prepend('<i class="toggle-class fa fa-angle-down"></i> ');
element.click(function() {
$(this).find('.toggle-class').toggleClass('fa-angle-down').toggleClass('fa-angle-right');
$(this).parent().find('.form-group').toggleClass('hidden');
});
}
});
// collapsable form fieldsets
module.directive('collapsed', function() {
return function(scope, element, attrs) {
element.prepend('<i class="toggle-class fa fa-angle-right"></i> ');
element.parent().find('.form-group').toggleClass('hidden');
element.click(function() {
$(this).find('.toggle-class').toggleClass('fa-angle-down').toggleClass('fa-angle-right');
$(this).parent().find('.form-group').toggleClass('hidden');
});
}
});
/**
* Directive for presenting an ON-OFF switch for checkbox.
* Usage: <input ng-model="mmm" name="nnn" id="iii" onoffswitch [on-text="ooo" off-text="fff"] />
*/
module.directive('onoffswitch', function() {
return {
restrict: "EA",
replace: true,
scope: {
name: '@',
id: '@',
ngModel: '=',
ngDisabled: '=',
kcOnText: '@onText',
kcOffText: '@offText'
},
// TODO - The same code acts differently when put into the templateURL. Find why and move the code there.
//templateUrl: "templates/kc-switch.html",
template: "<span><div class='onoffswitch' tabindex='0'><input type='checkbox' ng-model='ngModel' ng-disabled='ngDisabled' class='onoffswitch-checkbox' name='{{name}}' id='{{id}}'><label for='{{id}}' class='onoffswitch-label'><span class='onoffswitch-inner'><span class='onoffswitch-active'>{{kcOnText}}</span><span class='onoffswitch-inactive'>{{kcOffText}}</span></span><span class='onoffswitch-switch'></span></label></div></span>",
compile: function(element, attrs) {
/*
We don't want to propagate basic attributes to the root element of directive. Id should be passed to the
input element only to achieve proper label binding (and validity).
*/
element.removeAttr('name');
element.removeAttr('id');
if (!attrs.onText) { attrs.onText = "ON"; }
if (!attrs.offText) { attrs.offText = "OFF"; }
element.bind('keydown', function(e){
var code = e.keyCode || e.which;
if (code === 32 || code === 13) {
e.stopImmediatePropagation();
e.preventDefault();
$(e.target).find('input').click();
}
});
}
}
});
/**
* Directive for presenting an ON-OFF switch for checkbox. The directive expects the value to be string 'true' or 'false', not boolean true/false
* This directive provides some additional capabilities to the default onoffswitch such as:
*
* - Dynamic values for id and name attributes. Useful if you need to use this directive inside a ng-repeat
* - Specific scope to specify the value. Instead of just true or false.
*
* Usage: <input ng-model="mmm" name="nnn" id="iii" kc-onoffswitch-model [on-text="ooo" off-text="fff"] />
*/
module.directive('onoffswitchstring', function() {
return {
restrict: "EA",
replace: true,
scope: {
name: '=',
id: '=',
value: '=',
ngModel: '=',
ngDisabled: '=',
kcOnText: '@onText',
kcOffText: '@offText'
},
// TODO - The same code acts differently when put into the templateURL. Find why and move the code there.
//templateUrl: "templates/kc-switch.html",
template: '<span><div class="onoffswitch" tabindex="0"><input type="checkbox" ng-true-value="\'true\'" ng-false-value="\'false\'" ng-model="ngModel" ng-disabled="ngDisabled" class="onoffswitch-checkbox" name="kc{{name}}" id="kc{{id}}"><label for="kc{{id}}" class="onoffswitch-label"><span class="onoffswitch-inner"><span class="onoffswitch-active">{{kcOnText}}</span><span class="onoffswitch-inactive">{{kcOffText}}</span></span><span class="onoffswitch-switch"></span></label></div></span>',
compile: function(element, attrs) {
if (!attrs.onText) { attrs.onText = "ON"; }
if (!attrs.offText) { attrs.offText = "OFF"; }
element.bind('keydown click', function(e){
var code = e.keyCode || e.which;
if (code === 32 || code === 13) {
e.stopImmediatePropagation();
e.preventDefault();
$(e.target).find('input').click();
}
});
}
}
});
/**
* Directive for presenting an ON-OFF switch for checkbox. The directive expects the true-value or false-value to be string like 'true' or 'false', not boolean true/false.
* This directive provides some additional capabilities to the default onoffswitch such as:
*
* - Specific scope to specify the value. Instead of just 'true' or 'false' you can use any other values. For example: true-value="'foo'" false-value="'bar'" .
* But 'true'/'false' are defaults if true-value and false-value are not specified
*
* Usage: <input ng-model="mmm" name="nnn" id="iii" onoffswitchvalue [ true-value="'true'" false-value="'false'" on-text="ooo" off-text="fff"] />
*/
module.directive('onoffswitchvalue', function() {
return {
restrict: "EA",
replace: true,
scope: {
name: '@',
id: '@',
trueValue: '@',
falseValue: '@',
ngModel: '=',
ngDisabled: '=',
kcOnText: '@onText',
kcOffText: '@offText'
},
// TODO - The same code acts differently when put into the templateURL. Find why and move the code there.
//templateUrl: "templates/kc-switch.html",
template: "<span><div class='onoffswitch' tabindex='0'><input type='checkbox' ng-true-value='{{trueValue}}' ng-false-value='{{falseValue}}' ng-model='ngModel' ng-disabled='ngDisabled' class='onoffswitch-checkbox' name='{{name}}' id='{{id}}'><label for='{{id}}' class='onoffswitch-label'><span class='onoffswitch-inner'><span class='onoffswitch-active'>{{kcOnText}}</span><span class='onoffswitch-inactive'>{{kcOffText}}</span></span><span class='onoffswitch-switch'></span></label></div></span>",
compile: function(element, attrs) {
/*
We don't want to propagate basic attributes to the root element of directive. Id should be passed to the
input element only to achieve proper label binding (and validity).
*/
element.removeAttr('name');
element.removeAttr('id');
if (!attrs.trueValue) { attrs.trueValue = "'true'"; }
if (!attrs.falseValue) { attrs.falseValue = "'false'"; }
if (!attrs.onText) { attrs.onText = "ON"; }
if (!attrs.offText) { attrs.offText = "OFF"; }
element.bind('keydown', function(e){
var code = e.keyCode || e.which;
if (code === 32 || code === 13) {
e.stopImmediatePropagation();
e.preventDefault();
$(e.target).find('input').click();
}
});
}
}
});
module.directive('kcInput', function() {
var d = {
scope : true,
replace : false,
link : function(scope, element, attrs) {
var form = element.children('form');
var label = element.children('label');
var input = element.children('input');
var id = form.attr('name') + '.' + input.attr('name');
element.attr('class', 'control-group');
label.attr('class', 'control-label');
label.attr('for', id);
input.wrap('<div class="controls"/>');
input.attr('id', id);
if (!input.attr('placeHolder')) {
input.attr('placeHolder', label.text());
}
if (input.attr('required')) {
label.append(' <span class="required">*</span>');
}
}
};
return d;
});
module.directive('kcEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.kcEnter);
});
event.preventDefault();
}
});
};
});
module.directive('kcSave', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-primary");
elem.attr("type","submit");
elem.bind('click', function() {
$scope.$apply(function() {
var form = elem.closest('form');
if (form && form.attr('name')) {
var ngValid = form.find('.ng-valid');
if ($scope[form.attr('name')].$valid) {
//ngValid.removeClass('error');
ngValid.parent().removeClass('has-error');
$scope['save']();
} else {
Notifications.error("Missing or invalid field(s). Please verify the fields in red.")
//ngValid.removeClass('error');
ngValid.parent().removeClass('has-error');
var ngInvalid = form.find('.ng-invalid');
//ngInvalid.addClass('error');
ngInvalid.parent().addClass('has-error');
}
}
});
})
}
}
});
module.directive('kcReset', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-default");
elem.attr("type","submit");
elem.bind('click', function() {
$scope.$apply(function() {
var form = elem.closest('form');
if (form && form.attr('name')) {
form.find('.ng-valid').removeClass('error');
form.find('.ng-invalid').removeClass('error');
$scope['reset']();
}
})
})
}
}
});
module.directive('kcCancel', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-default");
elem.attr("type","submit");
}
}
});
module.directive('kcDelete', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-danger");
elem.attr("type","submit");
}
}
});
module.directive('kcDropdown', function ($compile, Notifications) {
return {
scope: {
kcOptions: '=',
kcModel: '=',
id: "=",
kcPlaceholder: '@'
},
restrict: 'EA',
replace: true,
templateUrl: resourceUrl + '/templates/kc-select.html',
link: function(scope, element, attr) {
scope.updateModel = function(item) {
scope.kcModel = item;
};
}
}
});
module.directive('kcReadOnly', function() {
var disabled = {};
var d = {
replace : false,
link : function(scope, element, attrs) {
var disable = function(i, e) {
if (!e.disabled) {
disabled[e.tagName + i] = true;
e.disabled = true;
}
}
var enable = function(i, e) {
if (disabled[e.tagName + i]) {
e.disabled = false;
delete disabled[i];
}
}
var filterIgnored = function(i, e){
return !e.attributes['kc-read-only-ignore'];
}
scope.$watch(attrs.kcReadOnly, function(readOnly) {
if (readOnly) {
element.find('input').filter(filterIgnored).each(disable);
element.find('button').filter(filterIgnored).each(disable);
element.find('select').filter(filterIgnored).each(disable);
element.find('textarea').filter(filterIgnored).each(disable);
} else {
element.find('input').filter(filterIgnored).each(enable);
element.find('input').filter(filterIgnored).each(enable);
element.find('button').filter(filterIgnored).each(enable);
element.find('select').filter(filterIgnored).each(enable);
element.find('textarea').filter(filterIgnored).each(enable);
}
});
}
};
return d;
});
module.directive('kcMenu', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-menu.html'
}
});
module.directive('kcTabsRealm', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-realm.html'
}
});
module.directive('kcTabsAuthentication', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-authentication.html'<|fim▁hole|> }
});
module.directive('kcTabsUser', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-user.html'
}
});
module.directive('kcTabsGroup', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-group.html'
}
});
module.directive('kcTabsGroupList', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-group-list.html'
}
});
module.directive('kcTabsClient', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-client.html'
}
});
module.directive('kcTabsClientTemplate', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-client-template.html'
}
});
module.directive('kcNavigationUser', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-navigation-user.html'
}
});
module.directive('kcTabsIdentityProvider', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-identity-provider.html'
}
});
module.directive('kcTabsUserFederation', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-user-federation.html'
}
});
module.controller('RoleSelectorModalCtrl', function($scope, realm, config, configName, RealmRoles, Client, ClientRole, $modalInstance) {
$scope.selectedRealmRole = {
role: undefined
};
$scope.selectedClientRole = {
role: undefined
};
$scope.client = {
selected: undefined
};
$scope.selectRealmRole = function() {
config[configName] = $scope.selectedRealmRole.role.name;
$modalInstance.close();
}
$scope.selectClientRole = function() {
config[configName] = $scope.client.selected.clientId + "." + $scope.selectedClientRole.role.name;
$modalInstance.close();
}
$scope.cancel = function() {
$modalInstance.dismiss();
}
$scope.changeClient = function() {
if ($scope.client.selected) {
ClientRole.query({realm: realm.realm, client: $scope.client.selected.id}, function (data) {
$scope.clientRoles = data;
});
} else {
console.log('selected client was null');
$scope.clientRoles = null;
}
}
RealmRoles.query({realm: realm.realm}, function(data) {
$scope.realmRoles = data;
})
Client.query({realm: realm.realm}, function(data) {
$scope.clients = data;
if (data.length > 0) {
$scope.client.selected = data[0];
$scope.changeClient();
}
})
});
module.controller('ProviderConfigCtrl', function ($modal, $scope) {
$scope.openRoleSelector = function (configName, config) {
$modal.open({
templateUrl: resourceUrl + '/partials/modal/role-selector.html',
controller: 'RoleSelectorModalCtrl',
resolve: {
realm: function () {
return $scope.realm;
},
config: function () {
return config;
},
configName: function () {
return configName;
}
}
})
}
});
module.directive('kcProviderConfig', function ($modal) {
return {
scope: {
config: '=',
properties: '=',
realm: '=',
clients: '=',
configName: '='
},
restrict: 'E',
replace: true,
controller: 'ProviderConfigCtrl',
templateUrl: resourceUrl + '/templates/kc-provider-config.html'
}
});
module.controller('ComponentRoleSelectorModalCtrl', function($scope, realm, config, configName, RealmRoles, Client, ClientRole, $modalInstance) {
$scope.selectedRealmRole = {
role: undefined
};
$scope.selectedClientRole = {
role: undefined
};
$scope.client = {
selected: undefined
};
$scope.selectRealmRole = function() {
config[configName][0] = $scope.selectedRealmRole.role.name;
$modalInstance.close();
}
$scope.selectClientRole = function() {
config[configName][0] = $scope.client.selected.clientId + "." + $scope.selectedClientRole.role.name;
$modalInstance.close();
}
$scope.cancel = function() {
$modalInstance.dismiss();
}
$scope.changeClient = function() {
if ($scope.client.selected) {
ClientRole.query({realm: realm.realm, client: $scope.client.selected.id}, function (data) {
$scope.clientRoles = data;
});
} else {
console.log('selected client was null');
$scope.clientRoles = null;
}
}
RealmRoles.query({realm: realm.realm}, function(data) {
$scope.realmRoles = data;
})
Client.query({realm: realm.realm}, function(data) {
$scope.clients = data;
if (data.length > 0) {
$scope.client.selected = data[0];
$scope.changeClient();
}
})
});
module.controller('ComponentConfigCtrl', function ($modal, $scope) {
$scope.openRoleSelector = function (configName, config) {
$modal.open({
templateUrl: resourceUrl + '/partials/modal/component-role-selector.html',
controller: 'ComponentRoleSelectorModalCtrl',
resolve: {
realm: function () {
return $scope.realm;
},
config: function () {
return config;
},
configName: function () {
return configName;
}
}
})
}
});
module.directive('kcComponentConfig', function ($modal) {
return {
scope: {
config: '=',
properties: '=',
realm: '=',
clients: '=',
configName: '='
},
restrict: 'E',
replace: true,
controller: 'ComponentConfigCtrl',
templateUrl: resourceUrl + '/templates/kc-component-config.html'
}
});
/*
* Used to select the element (invoke $(elem).select()) on specified action list.
* Usages kc-select-action="click mouseover"
* When used in the textarea element, this will select/highlight the textarea content on specified action (i.e. click).
*/
module.directive('kcSelectAction', function ($compile, Notifications) {
return {
restrict: 'A',
compile: function (elem, attrs) {
var events = attrs.kcSelectAction.split(" ");
for(var i=0; i < events.length; i++){
elem.bind(events[i], function(){
elem.select();
});
}
}
}
});
module.filter('remove', function() {
return function(input, remove, attribute) {
if (!input || !remove) {
return input;
}
var out = [];
for ( var i = 0; i < input.length; i++) {
var e = input[i];
if (Array.isArray(remove)) {
for (var j = 0; j < remove.length; j++) {
if (attribute) {
if (remove[j][attribute] == e[attribute]) {
e = null;
break;
}
} else {
if (remove[j] == e) {
e = null;
break;
}
}
}
} else {
if (attribute) {
if (remove[attribute] == e[attribute]) {
e = null;
}
} else {
if (remove == e) {
e = null;
}
}
}
if (e != null) {
out.push(e);
}
}
return out;
};
});
module.filter('capitalize', function() {
return function(input) {
if (!input) {
return;
}
var splittedWords = input.split(/\s+/);
for (var i=0; i<splittedWords.length ; i++) {
splittedWords[i] = splittedWords[i].charAt(0).toUpperCase() + splittedWords[i].slice(1);
};
return splittedWords.join(" ");
};
});
/*
* Guarantees a deterministic property iteration order.
* See: http://www.2ality.com/2015/10/property-traversal-order-es6.html
*/
module.filter('toOrderedMapSortedByKey', function(){
return function(input){
if(!input){
return input;
}
var keys = Object.keys(input);
if(keys.length <= 1){
return input;
}
keys.sort();
var result = {};
for (var i = 0; i < keys.length; i++) {
result[keys[i]] = input[keys[i]];
}
return result;
};
});
module.directive('kcSidebarResize', function ($window) {
return function (scope, element) {
function resize() {
var navBar = angular.element(document.getElementsByClassName('navbar-pf')).height();
var container = angular.element(document.getElementById("view").getElementsByTagName("div")[0]).height();
var height = Math.max(container, window.innerHeight - navBar - 3);
element[0].style['min-height'] = height + 'px';
}
resize();
var w = angular.element($window);
scope.$watch(function () {
return {
'h': window.innerHeight,
'w': window.innerWidth
};
}, function () {
resize();
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
});
module.directive('kcTooltip', function($compile) {
return {
restrict: 'E',
replace: false,
terminal: true,
priority: 1000,
link: function link(scope,element, attrs) {
var angularElement = angular.element(element[0]);
var tooltip = angularElement.text();
angularElement.text('');
element.addClass('hidden');
var label = angular.element(element.parent().children()[0]);
label.append(' <i class="fa fa-question-circle text-muted" tooltip="' + tooltip + '" tooltip-placement="right" tooltip-trigger="mouseover mouseout"></i>');
$compile(label)(scope);
}
};
});
module.directive( 'kcOpen', function ( $location ) {
return function ( scope, element, attrs ) {
var path;
attrs.$observe( 'kcOpen', function (val) {
path = val;
});
element.bind( 'click', function () {
scope.$apply( function () {
$location.path(path);
});
});
};
});
module.directive('kcOnReadFile', function ($parse) {
console.debug('kcOnReadFile');
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
var fn = $parse(attrs.kcOnReadFile);
element.on('change', function(onChangeEvent) {
var reader = new FileReader();
reader.onload = function(onLoadEvent) {
scope.$apply(function() {
fn(scope, {$fileContent:onLoadEvent.target.result});
});
};
reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
});
}
};
});<|fim▁end|> | |
<|file_name|>HttpError.d.ts<|end_file_name|><|fim▁begin|>export declare class HttpError extends Error {
statusCode: number;
constructor(errorMessage: string, statusCode: number);<|fim▁hole|>}<|fim▁end|> | |
<|file_name|>DeriveColumnsFromTimeTransform.java<|end_file_name|><|fim▁begin|>/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.datavec.api.transform.transform.time;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.datavec.api.transform.ColumnType;
import org.datavec.api.transform.Transform;
import org.datavec.api.transform.metadata.ColumnMetaData;
import org.datavec.api.transform.metadata.IntegerMetaData;
import org.datavec.api.transform.metadata.StringMetaData;
import org.datavec.api.transform.metadata.TimeMetaData;
import org.datavec.api.transform.schema.Schema;
import org.datavec.api.util.jackson.DateTimeFieldTypeDeserializer;
import org.datavec.api.util.jackson.DateTimeFieldTypeSerializer;
import org.datavec.api.writable.IntWritable;
import org.datavec.api.writable.Text;
import org.datavec.api.writable.Writable;
import org.joda.time.DateTime;
import org.joda.time.DateTimeFieldType;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.nd4j.shade.jackson.annotation.JsonIgnore;
import org.nd4j.shade.jackson.annotation.JsonIgnoreProperties;
import org.nd4j.shade.jackson.annotation.JsonInclude;
import org.nd4j.shade.jackson.annotation.JsonProperty;
import org.nd4j.shade.jackson.databind.annotation.JsonDeserialize;
import org.nd4j.shade.jackson.databind.annotation.JsonSerialize;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Create a number of new columns by deriving their values from a Time column.
* Can be used for example to create new columns with the year, month, day, hour, minute, second etc.
*
* @author Alex Black
*/
@JsonIgnoreProperties({"inputSchema", "insertAfterIdx", "deriveFromIdx"})
@EqualsAndHashCode(exclude = {"inputSchema", "insertAfterIdx", "deriveFromIdx"})
@Data
public class DeriveColumnsFromTimeTransform implements Transform {
private final String columnName;
private final String insertAfter;
private DateTimeZone inputTimeZone;
private final List<DerivedColumn> derivedColumns;
private Schema inputSchema;
private int insertAfterIdx = -1;
private int deriveFromIdx = -1;
private DeriveColumnsFromTimeTransform(Builder builder) {
this.derivedColumns = builder.derivedColumns;
this.columnName = builder.columnName;
this.insertAfter = builder.insertAfter;
}
public DeriveColumnsFromTimeTransform(@JsonProperty("columnName") String columnName,
@JsonProperty("insertAfter") String insertAfter,
@JsonProperty("inputTimeZone") DateTimeZone inputTimeZone,
@JsonProperty("derivedColumns") List<DerivedColumn> derivedColumns) {
this.columnName = columnName;
this.insertAfter = insertAfter;
this.inputTimeZone = inputTimeZone;
this.derivedColumns = derivedColumns;
}
@Override
public Schema transform(Schema inputSchema) {
List<ColumnMetaData> oldMeta = inputSchema.getColumnMetaData();
List<ColumnMetaData> newMeta = new ArrayList<>(oldMeta.size() + derivedColumns.size());
List<String> oldNames = inputSchema.getColumnNames();
for (int i = 0; i < oldMeta.size(); i++) {
String current = oldNames.get(i);
newMeta.add(oldMeta.get(i));
if (insertAfter.equals(current)) {
//Insert the derived columns here
for (DerivedColumn d : derivedColumns) {
switch (d.columnType) {
case String:
newMeta.add(new StringMetaData(d.columnName));
break;
case Integer:
newMeta.add(new IntegerMetaData(d.columnName)); //TODO: ranges... if it's a day, we know it must be 1 to 31, etc...
break;
default:
throw new IllegalStateException("Unexpected column type: " + d.columnType);
}
}
}
}
return inputSchema.newSchema(newMeta);
}
@Override
public void setInputSchema(Schema inputSchema) {
insertAfterIdx = inputSchema.getColumnNames().indexOf(insertAfter);
if (insertAfterIdx == -1) {
throw new IllegalStateException(
"Invalid schema/insert after column: input schema does not contain column \"" + insertAfter
+ "\"");
}
deriveFromIdx = inputSchema.getColumnNames().indexOf(columnName);
if (deriveFromIdx == -1) {
throw new IllegalStateException(
"Invalid source column: input schema does not contain column \"" + columnName + "\"");
}
this.inputSchema = inputSchema;
if (!(inputSchema.getMetaData(columnName) instanceof TimeMetaData))
throw new IllegalStateException("Invalid state: input column \"" + columnName
+ "\" is not a time column. Is: " + inputSchema.getMetaData(columnName));
TimeMetaData meta = (TimeMetaData) inputSchema.getMetaData(columnName);
inputTimeZone = meta.getTimeZone();
}
@Override
public Schema getInputSchema() {
return inputSchema;
}
@Override
public List<Writable> map(List<Writable> writables) {
if (writables.size() != inputSchema.numColumns()) {
throw new IllegalStateException("Cannot execute transform: input writables list length (" + writables.size()
+ ") does not " + "match expected number of elements (schema: " + inputSchema.numColumns()
+ "). Transform = " + toString());
}
int i = 0;
Writable source = writables.get(deriveFromIdx);
List<Writable> list = new ArrayList<>(writables.size() + derivedColumns.size());
for (Writable w : writables) {
list.add(w);
if (i++ == insertAfterIdx) {
for (DerivedColumn d : derivedColumns) {
switch (d.columnType) {
case String:
list.add(new Text(d.dateTimeFormatter.print(source.toLong())));
break;
case Integer:
DateTime dt = new DateTime(source.toLong(), inputTimeZone);
list.add(new IntWritable(dt.get(d.fieldType)));
break;
default:
throw new IllegalStateException("Unexpected column type: " + d.columnType);
}
}
}
}
return list;
}
@Override
public List<List<Writable>> mapSequence(List<List<Writable>> sequence) {
List<List<Writable>> out = new ArrayList<>(sequence.size());
for (List<Writable> step : sequence) {
out.add(map(step));
}
return out;
}
/**
* Transform an object
* in to another object
*
* @param input the record to transform
* @return the transformed writable
*/
@Override
public Object map(Object input) {
List<Object> ret = new ArrayList<>();
Long l = (Long) input;
for (DerivedColumn d : derivedColumns) {
switch (d.columnType) {<|fim▁hole|> case String:
ret.add(d.dateTimeFormatter.print(l));
break;
case Integer:
DateTime dt = new DateTime(l, inputTimeZone);
ret.add(dt.get(d.fieldType));
break;
default:
throw new IllegalStateException("Unexpected column type: " + d.columnType);
}
}
return ret;
}
/**
* Transform a sequence
*
* @param sequence
*/
@Override
public Object mapSequence(Object sequence) {
List<Long> longs = (List<Long>) sequence;
List<List<Object>> ret = new ArrayList<>();
for (Long l : longs)
ret.add((List<Object>) map(l));
return ret;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("DeriveColumnsFromTimeTransform(timeColumn=\"").append(columnName).append("\",insertAfter=\"")
.append(insertAfter).append("\",derivedColumns=(");
boolean first = true;
for (DerivedColumn d : derivedColumns) {
if (!first)
sb.append(",");
sb.append(d);
first = false;
}
sb.append("))");
return sb.toString();
}
/**
* The output column name
* after the operation has been applied
*
* @return the output column name
*/
@Override
public String outputColumnName() {
return outputColumnNames()[0];
}
/**
* The output column names
* This will often be the same as the input
*
* @return the output column names
*/
@Override
public String[] outputColumnNames() {
String[] ret = new String[derivedColumns.size()];
for (int i = 0; i < ret.length; i++)
ret[i] = derivedColumns.get(i).columnName;
return ret;
}
/**
* Returns column names
* this op is meant to run on
*
* @return
*/
@Override
public String[] columnNames() {
return new String[] {columnName()};
}
/**
* Returns a singular column name
* this op is meant to run on
*
* @return
*/
@Override
public String columnName() {
return columnName;
}
public static class Builder {
private final String columnName;
private String insertAfter;
private final List<DerivedColumn> derivedColumns = new ArrayList<>();
/**
* @param timeColumnName The name of the time column from which to derive the new values
*/
public Builder(String timeColumnName) {
this.columnName = timeColumnName;
this.insertAfter = timeColumnName;
}
/**
* Where should the new columns be inserted?
* By default, they will be inserted after the source column
*
* @param columnName Name of the column to insert the derived columns after
*/
public Builder insertAfter(String columnName) {
this.insertAfter = columnName;
return this;
}
/**
* Add a String column (for example, human readable format), derived from the time
*
* @param columnName Name of the new/derived column
* @param format Joda time format, as per <a href="http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html">http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html</a>
* @param timeZone Timezone to use for formatting
*/
public Builder addStringDerivedColumn(String columnName, String format, DateTimeZone timeZone) {
derivedColumns.add(new DerivedColumn(columnName, ColumnType.String, format, timeZone, null));
return this;
}
/**
* Add an integer derived column - for example, the hour of day, etc. Uses timezone from the time column metadata
*
* @param columnName Name of the column
* @param type Type of field (for example, DateTimeFieldType.hourOfDay() etc)
*/
public Builder addIntegerDerivedColumn(String columnName, DateTimeFieldType type) {
derivedColumns.add(new DerivedColumn(columnName, ColumnType.Integer, null, null, type));
return this;
}
/**
* Create the transform instance
*/
public DeriveColumnsFromTimeTransform build() {
return new DeriveColumnsFromTimeTransform(this);
}
}
@JsonInclude(JsonInclude.Include.NON_NULL)
@EqualsAndHashCode(exclude = "dateTimeFormatter")
@Data
@JsonIgnoreProperties({"dateTimeFormatter"})
public static class DerivedColumn implements Serializable {
private final String columnName;
private final ColumnType columnType;
private final String format;
private final DateTimeZone dateTimeZone;
@JsonSerialize(using = DateTimeFieldTypeSerializer.class)
@JsonDeserialize(using = DateTimeFieldTypeDeserializer.class)
private final DateTimeFieldType fieldType;
private transient DateTimeFormatter dateTimeFormatter;
// public DerivedColumn(String columnName, ColumnType columnType, String format, DateTimeZone dateTimeZone, DateTimeFieldType fieldType) {
public DerivedColumn(@JsonProperty("columnName") String columnName,
@JsonProperty("columnType") ColumnType columnType, @JsonProperty("format") String format,
@JsonProperty("dateTimeZone") DateTimeZone dateTimeZone,
@JsonProperty("fieldType") DateTimeFieldType fieldType) {
this.columnName = columnName;
this.columnType = columnType;
this.format = format;
this.dateTimeZone = dateTimeZone;
this.fieldType = fieldType;
if (format != null)
dateTimeFormatter = DateTimeFormat.forPattern(this.format).withZone(dateTimeZone);
}
@Override
public String toString() {
return "(name=" + columnName + ",type=" + columnType + ",derived=" + (format != null ? format : fieldType)
+ ")";
}
//Custom serialization methods, because Joda Time doesn't allow DateTimeFormatter objects to be serialized :(
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
if (format != null)
dateTimeFormatter = DateTimeFormat.forPattern(format).withZone(dateTimeZone);
}
}
}<|fim▁end|> | |
<|file_name|>vapid-details-model.d.ts<|end_file_name|><|fim▁begin|>import { DBInterface } from './db-interface';
export declare class VapidDetailsModel extends DBInterface {
protected readonly dbName: string;
protected readonly dbVersion: number;
protected readonly objectStoreName: string;
protected onDbUpgrade(request: IDBOpenDBRequest): void;
/**<|fim▁hole|> */
getVapidFromSWScope(swScope: string): Promise<Uint8Array | undefined>;
/**
* Save a vapid key against a swScope for later date.
*/
saveVapidDetails(swScope: string, vapidKey: Uint8Array): Promise<void>;
/**
* This method deletes details of the current FCM VAPID key for a SW scope.
* Resolves once the scope/vapid details have been deleted and returns the
* deleted vapid key.
*/
deleteVapidDetails(swScope: string): Promise<Uint8Array>;
}<|fim▁end|> | * Given a service worker scope, this method will look up the vapid key
* in indexedDB. |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from setuptools import setup
import pybvc
setup(
name='pybvc',
version=pybvc.__version__,
description='A python library for programming your network via the Brocade Vyatta Controller (BVC)',<|fim▁hole|> author_email='[email protected]',
url='https://github.com/brcdcomm/pybvc',
packages=['pybvc',
'pybvc.common',
'pybvc.controller',
'pybvc.netconfdev',
'pybvc.netconfdev.vrouter',
'pybvc.netconfdev.vdx',
'pybvc.openflowdev'
],
install_requires=['requests>=1.0.0',
'PyYAML',
'xmltodict'],
zip_safe=False,
include_package_data=True,
platforms='any',
license='BSD',
keywords='sdn nfv bvc brocade vyatta controller network vrouter',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: System Administrators',
'Topic :: System :: Networking',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
]
)<|fim▁end|> | long_description=open('README.rst').read(),
author='Elbrys Networks', |
<|file_name|>inabox-messaging-host.js<|end_file_name|><|fim▁begin|>/**
* Copyright 2016 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {FrameOverlayManager} from './frame-overlay-manager';
import {
MessageType,
deserializeMessage,
serializeMessage,
} from '../../src/3p-frame-messaging';
import {PositionObserver} from './position-observer';
import {dev} from '../../src/log';
import {dict} from '../../src/utils/object';
import {getData} from '../../src/event-helper';
import {layoutRectFromDomRect} from '../../src/layout-rect';
/** @const */
const TAG = 'InaboxMessagingHost';
/** Simple helper for named callbacks. */
class NamedObservable {
/**
* Creates an instance of NamedObservable.
*/
constructor() {
/** @private {!Object<string, !Function>} */
this.map_ = {};
}
/**
* @param {string} key
* @param {!Function} callback
*/
listen(key, callback) {
if (key in this.map_) {
dev().fine(TAG, `Overriding message callback [${key}]`);
}
this.map_[key] = callback;
}
/**
* @param {string} key
* @param {*} thisArg
* @param {!Array} args
* @return {boolean} True when a callback was found and successfully executed.
*/
fire(key, thisArg, args) {
if (key in this.map_) {
return this.map_[key].apply(thisArg, args);
}
return false;
}
}
/** @typedef {{
iframe: !HTMLIFrameElement,
measurableFrame: !HTMLIFrameElement,
observeUnregisterFn: (!UnlistenDef|undefined),
}} */
let AdFrameDef;
export class InaboxMessagingHost {
/**
* @param {!Window} win
* @param {!Array<!HTMLIFrameElement>} iframes
*/
constructor(win, iframes) {
/** @private {!Array<!HTMLIFrameElement>} */
this.iframes_ = iframes;
/** @private {!Object<string,!AdFrameDef>} */
this.iframeMap_ = Object.create(null);
/** @private {!PositionObserver} */
this.positionObserver_ = new PositionObserver(win);
/** @private {!NamedObservable} */
this.msgObservable_ = new NamedObservable();
/** @private {!FrameOverlayManager} */
this.frameOverlayManager_ = new FrameOverlayManager(win);
this.msgObservable_.listen(
MessageType.SEND_POSITIONS, this.handleSendPositions_);
this.msgObservable_.listen(
MessageType.FULL_OVERLAY_FRAME, this.handleEnterFullOverlay_);
this.msgObservable_.listen(
MessageType.CANCEL_FULL_OVERLAY_FRAME, this.handleCancelFullOverlay_);
}
/**
* Process a single post message.
*
* A valid message has to be formatted as a string starting with "amp-". The
* rest part should be a stringified JSON object of
* {type: string, sentinel: string}. The allowed types are listed in the
* REQUEST_TYPE enum.
*
* @param {!MessageEvent} message
* @return {boolean} true if message get successfully processed
*/
processMessage(message) {
const request = deserializeMessage(getData(message));
if (!request || !request['sentinel']) {
dev().fine(TAG, 'Ignored non-AMP message:', message);
return false;
}
const iframe =
this.getFrameElement_(message.source, request['sentinel']);
if (!iframe) {
dev().info(TAG, 'Ignored message from untrusted iframe:', message);
return false;
}
if (!this.msgObservable_.fire(request['type'], this,
[iframe, request, message.source, message.origin])) {
dev().warn(TAG, 'Unprocessed AMP message:', message);
return false;
}
return true;
}
/**
* @param {!HTMLIFrameElement} iframe
* @param {!Object} request
* @param {!Window} source
* @param {string} origin
* @return {boolean}
*/
handleSendPositions_(iframe, request, source, origin) {
const viewportRect = this.positionObserver_.getViewportRect();
const targetRect =
layoutRectFromDomRect(iframe./*OK*/getBoundingClientRect());
this.sendPosition_(request, source, origin, dict({
'viewportRect': viewportRect,
'targetRect': targetRect,
}));
dev().assert(this.iframeMap_[request.sentinel]);
this.iframeMap_[request.sentinel].observeUnregisterFn =
this.iframeMap_[request.sentinel].observeUnregisterFn ||
this.positionObserver_.observe(iframe, data =>
this.sendPosition_(request, source, origin, /** @type ?JsonObject */(data)));
return true;
}
/**
*
* @param {!Object} request
* @param {!Window} source
* @param {string} origin
* @param {?JsonObject} data
*/
sendPosition_(request, source, origin, data) {
dev().fine(TAG, `Sent position data to [${request.sentinel}]`, data);
source./*OK*/postMessage(
serializeMessage(MessageType.POSITION, request.sentinel, data),
origin);
}
/**
* @param {!HTMLIFrameElement} iframe
* @param {!Object} request
* @param {!Window} source
* @param {string} origin
* @return {boolean}
* TODO(alanorozco):
* 1. Reject request if frame is out of focus
* 2. Disable zoom and scroll on parent doc
*/
handleEnterFullOverlay_(iframe, request, source, origin) {
this.frameOverlayManager_.expandFrame(iframe, boxRect => {
source./*OK*/postMessage(
serializeMessage(
MessageType.FULL_OVERLAY_FRAME_RESPONSE,
request.sentinel,
dict({
'success': true,
'boxRect': boxRect,
})),
origin);
});
return true;
}
/**
* @param {!HTMLIFrameElement} iframe
* @param {!Object} request
* @param {!Window} source
* @param {string} origin
* @return {boolean}
*/
handleCancelFullOverlay_(iframe, request, source, origin) {
this.frameOverlayManager_.collapseFrame(iframe, boxRect => {
source./*OK*/postMessage(
serializeMessage(
MessageType.CANCEL_FULL_OVERLAY_FRAME_RESPONSE,
request.sentinel,
dict({
'success': true,
'boxRect': boxRect,
})),
origin);
});
return true;
}
/** This method is doing two things.
* 1. It checks that the source of the message is valid.
* Validity means that the message comes from a frame that
* is either directly registered in this.iframes_, or is a
* child of one of those frames.
* 2. It returns whichever iframe is the deepest frame in the source's
* hierarchy that the outer host window can still measure, which is
* the top most cross domained frame, or the creative frame.
* EXAMPLE:
* If we have a frame hierarchy:
* Host -> Friendly Frame -> X Domain Frame 1 -> Message Source Frame
* and "Friendly Frame" is registered in this.iframes_, then
* "Message Source Frame" is valid, because one of its parent frames
* is registered in this.iframes_, and the result of the call to
* getFrameElement_ would be the iframe "X Domain Frame 1" as it is
* the deepest frame that the host doc can accurately measure.
* Note: The sentinel should be unique to the source window, and the result
* is cached using the sentinel as the key.
*
* @param {?Window} source
* @param {string} sentinel
* @return {?HTMLIFrameElement}
* @private
*/
getFrameElement_(source, sentinel) {
if (this.iframeMap_[sentinel]) {
return this.iframeMap_[sentinel].measurableFrame;
}
const measurableFrame = this.getMeasureableFrame(source);
if (!measurableFrame) {
return null;
}<|fim▁hole|> for (let i = 0; i < this.iframes_.length; i++) {
const iframe = this.iframes_[i];
for (let j = 0, tempWin = measurableWin;
j < 10; j++, tempWin = tempWin.parent) {
if (iframe.contentWindow == tempWin) {
this.iframeMap_[sentinel] = {iframe, measurableFrame};
return measurableFrame;
}
if (tempWin == window.top) {
break;
}
}
}
return null;
}
/**
* Returns whichever window in win's parent hierarchy is the deepest window
* that is measurable from the perspective of the current window.
* For when win is nested within a x-domain frame, walks up the window's
* parent hierarchy until the top-most x-domain frame in the hierarchy
* is found. Then, it returns the frame element for that window.
* For when win is friendly framed, returns the frame element for win.
* @param {?Window} win
* @return {?HTMLIFrameElement}
* @visibleForTesting
*/
getMeasureableFrame(win) {
if (!win) {
return null;
}
// First, we try to find the top-most x-domain window in win's parent
// hierarchy. If win is not nested within x-domain framing, then
// this loop breaks immediately.
let topXDomainWin;
for (let j = 0, tempWin = win;
j < 10 && tempWin != tempWin.top && !canInspectWindow_(tempWin);
j++, topXDomainWin = tempWin, tempWin = tempWin.parent) {}
// If topXDomainWin exists, we know that the frame we want to measure
// is a x-domain frame. Unfortunately, you can not access properties
// on a x-domain window, so we can not do window.frameElement, and
// instead must instead get topXDomainWin's parent, and then iterate
// over that parent's child iframes until we find the frame element
// that corresponds to topXDomainWin.
if (!!topXDomainWin) {
const iframes =
topXDomainWin.parent.document.querySelectorAll('iframe');
for (let k = 0, frame = iframes[k]; k < iframes.length;
k++, frame = iframes[k]) {
if (frame.contentWindow == topXDomainWin) {
return /** @type {!HTMLIFrameElement} */(frame);
}
}
}
// If topXDomainWin does not exist, then win is friendly, and we can
// just return its frameElement directly.
return /** @type {!HTMLIFrameElement} */(win.frameElement);
}
/**
* Removes an iframe from the set of iframes we watch, along with executing
* any necessary cleanup. Available at win.AMP.inaboxUnregisterIframe().
*
* @param {!HTMLIFrameElement} iframe
*/
unregisterIframe(iframe) {
// Remove iframe from the list of iframes we're watching.
const iframeIndex = this.iframes_.indexOf(iframe);
if (iframeIndex != -1) {
this.iframes_.splice(iframeIndex, 1);
}
// Also remove it and all of its descendents from our sentinel cache.
// TODO(jeffkaufman): save more info so we don't have to walk the dom here.
for (const sentinel in this.iframeMap_) {
if (this.iframeMap_[sentinel].iframe == iframe) {
if (this.iframeMap_[sentinel].observeUnregisterFn) {
this.iframeMap_[sentinel].observeUnregisterFn();
}
delete this.iframeMap_[sentinel];
}
}
}
}
/**
* Returns true if win's properties can be accessed and win is defined.
* This functioned is used to determine if a window is cross-domained
* from the perspective of the current window.
* @param {!Window} win
* @return {boolean}
* @private
*/
function canInspectWindow_(win) {
try {
const unused = !!win.location.href && win['test']; // eslint-disable-line no-unused-vars
return true;
} catch (unusedErr) { // eslint-disable-line no-unused-vars
return false;
}
}<|fim▁end|> | const measurableWin = measurableFrame.contentWindow; |
<|file_name|>tableentries.py<|end_file_name|><|fim▁begin|># Purpose: ac1009 table entries
# Created: 16.03.2011
# Copyright (C) 2011, Manfred Moitzi
# License: MIT License
from __future__ import unicode_literals
__author__ = "mozman <[email protected]>"
from ..entity import GenericWrapper
from ..tags import DXFTag
from ..classifiedtags import ClassifiedTags
from ..dxfattr import DXFAttr, DXFAttributes, DefSubclass
_LAYERTEMPLATE = """ 0
LAYER
5
0
2
LAYERNAME
70
0
62
7
6
CONTINUOUS
"""
# noinspection PyAugmentAssignment,PyUnresolvedReferences
class Layer(GenericWrapper):
TEMPLATE = ClassifiedTags.from_text(_LAYERTEMPLATE)
DXFATTRIBS = DXFAttributes(DefSubclass(None, {
'handle': DXFAttr(5, None),
'name': DXFAttr(2, None),
'flags': DXFAttr(70, None),
'color': DXFAttr(62, None), # dxf color index, if < 0 layer is off
'linetype': DXFAttr(6, None),
}))
LOCK = 0b00000100
UNLOCK = 0b11111011
def is_locked(self):
return self.dxf.flags & Layer.LOCK > 0
def lock(self):
self.dxf.flags = self.dxf.flags | Layer.LOCK
def unlock(self):
self.dxf.flags = self.dxf.flags & Layer.UNLOCK
def is_off(self):
return self.dxf.color < 0
def is_on(self):
return not self.is_off()
def on(self):
self.dxf.color = abs(self.dxf.color)
def off(self):
self.dxf.color = -abs(self.dxf.color)
def get_color(self):
return abs(self.dxf.color)
def set_color(self, color):
color = abs(color) if self.is_on() else -abs(color)
self.dxf.color = color
_STYLETEMPLATE = """ 0
STYLE
5
0
2
STYLENAME
70
0
40
0.0
41
1.0
50
0.0
71
0
42
1.0
3
arial.ttf
4
"""
class Style(GenericWrapper):
TEMPLATE = ClassifiedTags.from_text(_STYLETEMPLATE)
DXFATTRIBS = DXFAttributes(DefSubclass(None, {
'handle': DXFAttr(5, None),
'name': DXFAttr(2, None),
'flags': DXFAttr(70, None),
'height': DXFAttr(40, None), # fixed height, 0 if not fixed
'width': DXFAttr(41, None), # width factor
'oblique': DXFAttr(50, None), # oblique angle in degree, 0 = vertical
'text_generation_flags': DXFAttr(71, None), # 2 = backward, 4 = mirrored in Y
'last_height': DXFAttr(42, None), # last height used
'font': DXFAttr(3, None), # primary font file name
'bigfont': DXFAttr(4, None), # big font name, blank if none
}))
_LTYPETEMPLATE = """ 0
LTYPE
5
0
2
LTYPENAME
70
0
3
LTYPEDESCRIPTION
72
65
"""
class Linetype(GenericWrapper):
TEMPLATE = ClassifiedTags.from_text(_LTYPETEMPLATE)
DXFATTRIBS = DXFAttributes(DefSubclass(None, {
'handle': DXFAttr(5, None),
'name': DXFAttr(2, None),
'description': DXFAttr(3, None),
'length': DXFAttr(40, None),
'items': DXFAttr(73, None),
}))
@classmethod
def new(cls, handle, dxfattribs=None, dxffactory=None):
if dxfattribs is not None:
pattern = dxfattribs.pop('pattern', [0.0])
else:
pattern = [0.0]
entity = super(Linetype, cls).new(handle, dxfattribs, dxffactory)
entity._setup_pattern(pattern)
return entity
def _setup_pattern(self, pattern):
self.tags.noclass.append(DXFTag(73, len(pattern) - 1))
self.tags.noclass.append(DXFTag(40, float(pattern[0])))
self.tags.noclass.extend((DXFTag(49, float(p)) for p in pattern[1:]))
_VPORTTEMPLATE = """ 0
VPORT
5
0
2
VPORTNAME
70
0
10
0.0
20
0.0
11
1.0
21
1.0
12
70.0
22
50.0
13
0.0<|fim▁hole|>0.0
14
0.5
24
0.5
15
0.5
25
0.5
16
0.0
26
0.0
36
1.0
17
0.0
27
0.0
37
0.0
40
70.
41
1.34
42
50.0
43
0.0
44
0.0
50
0.0
51
0.0
71
0
72
1000
73
1
74
3
75
0
76
0
77
0
78
0
"""
class Viewport(GenericWrapper):
TEMPLATE = ClassifiedTags.from_text(_VPORTTEMPLATE)
DXFATTRIBS = DXFAttributes(DefSubclass(None, {
'handle': DXFAttr(5, None),
'name': DXFAttr(2, None),
'flags': DXFAttr(70, None),
'lower_left': DXFAttr(10, 'Point2D'),
'upper_right': DXFAttr(11, 'Point2D'),
'center_point': DXFAttr(12, 'Point2D'),
'snap_base': DXFAttr(13, 'Point2D'),
'snap_spacing': DXFAttr(14, 'Point2D'),
'grid_spacing': DXFAttr(15, 'Point2D'),
'direction_point': DXFAttr(16, 'Point3D'),
'target_point': DXFAttr(17, 'Point3D'),
'height': DXFAttr(40, None),
'aspect_ratio': DXFAttr(41, None),
'lens_length': DXFAttr(42, None),
'front_clipping': DXFAttr(43, None),
'back_clipping': DXFAttr(44, None),
'snap_rotation': DXFAttr(50, None),
'view_twist': DXFAttr(51, None),
'status': DXFAttr(68, None),
'id': DXFAttr(69, None),
'view_mode': DXFAttr(71, None),
'circle_zoom': DXFAttr(72, None),
'fast_zoom': DXFAttr(73, None),
'ucs_icon': DXFAttr(74, None),
'snap_on': DXFAttr(75, None),
'grid_on': DXFAttr(76, None),
'snap_style': DXFAttr(77, None),
'snap_isopair': DXFAttr(78, None),
}))
_UCSTEMPLATE = """ 0
UCS
5
0
2
UCSNAME
70
0
10
0.0
20
0.0
30
0.0
11
1.0
21
0.0
31
0.0
12
0.0
22
1.0
32
0.0
"""
class UCS(GenericWrapper):
TEMPLATE = ClassifiedTags.from_text(_UCSTEMPLATE)
DXFATTRIBS = DXFAttributes(DefSubclass(None, {
'handle': DXFAttr(5, None),
'name': DXFAttr(2, None),
'flags': DXFAttr(70, None),
'origin': DXFAttr(10, 'Point3D'),
'xaxis': DXFAttr(11, 'Point3D'),
'yaxis': DXFAttr(12, 'Point3D'),
}))
_APPIDTEMPLATE = """ 0
APPID
5
0
2
APPNAME
70
0
"""
class AppID(GenericWrapper):
TEMPLATE = ClassifiedTags.from_text(_APPIDTEMPLATE)
DXFATTRIBS = DXFAttributes(DefSubclass(None, {
'handle': DXFAttr(5, None),
'name': DXFAttr(2, None),
'flags': DXFAttr(70, None),
}))
_VIEWTEMPLATE = """ 0
VIEW
5
0
2
VIEWNAME
70
0
10
0.0
20
0.0
11
1.0
21
1.0
31
1.0
12
0.0
22
0.0
32
0.0
40
70.
41
1.0
42
50.0
43
0.0
44
0.0
50
0.0
71
0
"""
class View(GenericWrapper):
TEMPLATE = ClassifiedTags.from_text(_VIEWTEMPLATE)
DXFATTRIBS = DXFAttributes(DefSubclass(None, {
'handle': DXFAttr(5, None),
'name': DXFAttr(2, None),
'flags': DXFAttr(70, None),
'height': DXFAttr(40, None),
'width': DXFAttr(41, None),
'center_point': DXFAttr(10, 'Point2D'),
'direction_point': DXFAttr(11, 'Point3D'),
'target_point': DXFAttr(12, 'Point3D'),
'lens_length': DXFAttr(42, None),
'front_clipping': DXFAttr(43, None),
'back_clipping': DXFAttr(44, None),
'view_twist': DXFAttr(50, None),
'view_mode': DXFAttr(71, None),
}))
_DIMSTYLETEMPLATE = """ 0
DIMSTYLE
105
0
2
DIMSTYLENAME
70
0
3
4
5
6
7
40
1.0
41
3.0
42
2.0
43
9.0
44
5.0
45
0.0
46
0.0
47
0.0
48
0.0
140
3.0
141
2.0
142
0.0
143
25.399999999999999
144
1.0
145
0.0
146
1.0
147
2.0
71
0
72
0
73
1
74
1
75
0
76
0
77
0
78
0
170
0
171
2
172
0
173
0
174
0
175
0
176
0
177
0
178
0
"""
class DimStyle(GenericWrapper):
TEMPLATE = ClassifiedTags.from_text(_DIMSTYLETEMPLATE)
DXFATTRIBS = DXFAttributes(DefSubclass(None, {
'handle': DXFAttr(105, None),
'name': DXFAttr(2, None),
'flags': DXFAttr(70, None),
'dimpost': DXFAttr(3, None),
'dimapost': DXFAttr(4, None),
'dimblk': DXFAttr(5, None),
'dimblk1': DXFAttr(6, None),
'dimblk2': DXFAttr(7, None),
'dimscale': DXFAttr(40, None),
'dimasz': DXFAttr(41, None),
'dimexo': DXFAttr(42, None),
'dimdli': DXFAttr(43, None),
'dimexe': DXFAttr(44, None),
'dimrnd': DXFAttr(45, None),
'dimdle': DXFAttr(46, None),
'dimtp': DXFAttr(47, None),
'dimtm': DXFAttr(48, None),
'dimtxt': DXFAttr(140, None),
'dimcen': DXFAttr(141, None),
'dimtsz': DXFAttr(142, None),
'dimaltf': DXFAttr(143, None),
'dimlfac': DXFAttr(144, None),
'dimtvp': DXFAttr(145, None),
'dimtfac': DXFAttr(146, None),
'dimgap': DXFAttr(147, None),
'dimtol': DXFAttr(71, None),
'dimlim': DXFAttr(72, None),
'dimtih': DXFAttr(73, None),
'dimtoh': DXFAttr(74, None),
'dimse1': DXFAttr(75, None),
'dimse2': DXFAttr(76, None),
'dimtad': DXFAttr(77, None),
'dimzin': DXFAttr(78, None),
'dimalt': DXFAttr(170, None),
'dimaltd': DXFAttr(171, None),
'dimtofl': DXFAttr(172, None),
'dimsah': DXFAttr(173, None),
'dimtix': DXFAttr(174, None),
'dimsoxd': DXFAttr(175, None),
'dimclrd': DXFAttr(176, None),
'dimclre': DXFAttr(177, None),
'dimclrt': DXFAttr(178, None),
}))<|fim▁end|> | 23 |
<|file_name|>visitor.go<|end_file_name|><|fim▁begin|>package semantical
import (
"github.com/cloudson/gitql/parser"
)
type Visitor interface {
Visit(*parser.NodeProgram) error
VisitSelect(*parser.NodeSelect) error
VisitExpr(*parser.NodeExpr) error
VisitGreater(*parser.NodeGreater) error
VisitSmaller(*parser.NodeSmaller) error
VisitIn(*parser.NodeSmaller) error
VisitEqual(*parser.NodeSmaller) error
VisitNotEqual(*parser.NodeSmaller) error
}
<|fim▁hole|><|fim▁end|> | type SemanticalVisitor struct {
Visitor
} |
<|file_name|>isOrthogonal.ts<|end_file_name|><|fim▁begin|>/**<|fim▁hole|> */
isOrthogonal() : boolean {
return this.transpose().times(this).isIdentity();
}<|fim▁end|> | * Determines if the matrix is a orthogonal.
*
* @return {boolean} |
<|file_name|>SearchFragment.java<|end_file_name|><|fim▁begin|>/*****************************************************************************
* SearchFragment.java
*****************************************************************************
* Copyright © 2014-2015 VLC authors, VideoLAN and VideoLabs
* Author: Geoffrey Métais
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
package org.videolan.vlc.gui.tv;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v17.leanback.widget.ArrayObjectAdapter;
import android.support.v17.leanback.widget.HeaderItem;
import android.support.v17.leanback.widget.ListRow;
import android.support.v17.leanback.widget.ListRowPresenter;
import android.support.v17.leanback.widget.ObjectAdapter;
import android.support.v17.leanback.widget.OnItemViewClickedListener;
import android.support.v17.leanback.widget.Presenter;
import android.support.v17.leanback.widget.Row;
import android.support.v17.leanback.widget.RowPresenter;
import android.text.TextUtils;
import org.videolan.vlc.R;
import org.videolan.vlc.VLCApplication;
import org.videolan.vlc.media.MediaLibrary;
import org.videolan.vlc.media.MediaWrapper;
import java.util.ArrayList;
public class SearchFragment extends android.support.v17.leanback.app.SearchFragment
implements android.support.v17.leanback.app.SearchFragment.SearchResultProvider {
private static final String TAG = "SearchFragment";
private ArrayObjectAdapter mRowsAdapter;
private Handler mHandler = new Handler();
private SearchRunnable mDelayedLoad;
protected Activity mActivity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
setSearchResultProvider(this);
setOnItemViewClickedListener(getDefaultItemClickedListener());
mDelayedLoad = new SearchRunnable();
mActivity = getActivity();
}
@Override
public ObjectAdapter getResultsAdapter() {
return mRowsAdapter;
}
private void queryByWords(String words) {
mRowsAdapter.clear();
if (!TextUtils.isEmpty(words) && words.length() > 2) {
mDelayedLoad.setSearchQuery(words);
mDelayedLoad.setSearchType(MediaWrapper.TYPE_ALL);
VLCApplication.runBackground(mDelayedLoad);
}
}
@Override
public boolean onQueryTextChange(String newQuery) {
queryByWords(newQuery);
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
queryByWords(query);
return true;
}
private void loadRows(String query, int type) {
ArrayList<MediaWrapper> mediaList = MediaLibrary.getInstance().searchMedia(query);
final ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(new CardPresenter(mActivity));
listRowAdapter.addAll(0, mediaList);
mHandler.post(new Runnable() {
@Override
public void run() {
HeaderItem header = new HeaderItem(0, getResources().getString(R.string.search_results));
mRowsAdapter.add(new ListRow(header, listRowAdapter));
}
});
}
protected OnItemViewClickedListener getDefaultItemClickedListener() {
return new OnItemViewClickedListener() {
@Override
public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
if (item instanceof MediaWrapper) {
TvUtil.openMedia(mActivity, (MediaWrapper) item, row);
}
}
};
}
private class SearchRunnable implements Runnable {
private volatile String searchQuery;
private volatile int searchType;
public SearchRunnable() {}
public void run() {
loadRows(searchQuery, searchType);
}<|fim▁hole|>
public void setSearchQuery(String value) {
this.searchQuery = value;
}
public void setSearchType(int value) {
this.searchType = value;
}
}
}<|fim▁end|> | |
<|file_name|>test_sound_formats.py<|end_file_name|><|fim▁begin|>import sys
from unittest import TestCase, expectedFailure, skipIf
import pygame
from pgzero.loaders import sounds, set_root, UnsupportedFormat
pygame.init()
class SoundFormatsTest(TestCase):
"""Test that sound formats we cannot open show an appropriate message."""
@classmethod
def setUpClass(self):
set_root(__file__)
def assert_loadable(self, name):
s = sounds.load(name)
l = s.get_length()
assert 0.85 < l < 1.0, \
"Failed to correctly load sound (got length %0.1fs)" % l
def assert_errmsg(self, name, pattern):
with self.assertRaisesRegex(UnsupportedFormat, pattern):
sounds.load(name)
def test_load_22k16bitpcm(self):
self.assert_loadable('wav22k16bitpcm')
def test_load_22k8bitpcm(self):
self.assert_loadable('wav22k8bitpcm')
def test_load_22kadpcm(self):
self.assert_loadable('wav22kadpcm')
@expectedFailure # See issue #22 - 8Khz files don't open correctly
def test_load_8k16bitpcm(self):
self.assert_loadable('wav8k16bitpcm')
@expectedFailure # See issue #22 - 8Khz files don't open correctly
def test_load_8k8bitpcm(self):
self.assert_loadable('wav8k8bitpcm')
@expectedFailure # See issue #22 - 8Khz files don't open correctly
def test_load_8kadpcm(self):
self.assert_loadable('wav8kadpcm')
@skipIf(sys.platform == "win32", "This will crash on Windows")
def test_load_11kgsm(self):
self.assert_errmsg('wav22kgsm', 'WAV audio encoded as GSM')
@skipIf(sys.platform == "win32", "This will crash on Windows")
def test_load_11kulaw(self):
self.assert_errmsg('wav22kulaw', 'WAV audio encoded as .* µ-law')
@skipIf(sys.platform == "win32", "This will crash on Windows")
def test_load_8kmp316(self):
self.assert_errmsg('wav8kmp316', 'WAV audio encoded as MP3')
@skipIf(sys.platform == "win32", "This will crash on Windows")
def test_load_8kmp38(self):
self.assert_errmsg('wav8kmp38', 'WAV audio encoded as MP3')
def test_load_vorbis1(self):
"""Load OGG Vorbis with .ogg extension."""
<|fim▁hole|>
def test_load_vorbis2(self):
"""Load OGG Vorbis with .oga extension."""
self.assert_loadable('vorbis2')<|fim▁end|> | self.assert_loadable('vorbis1')
|
<|file_name|>BalanceType.java<|end_file_name|><|fim▁begin|>package com.bitdubai.fermat_api.layer.dmp_basic_wallet.common.enums;<|fim▁hole|> * Created by natalia on 06/07/15.
*/
public enum BalanceType {
AVAILABLE("AVAILABLE"),
BOOK("BOOK");
private final String code;
BalanceType(String code) {
this.code = code;
}
public String getCode() { return this.code ; }
public static BalanceType getByCode(String code) {
switch (code) {
case "BOOK": return BOOK;
case "AVAILABLE": return AVAILABLE;
default: return AVAILABLE;
}
}
}<|fim▁end|> |
/** |
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.http import Http404, HttpResponse
from django.template.context_processors import csrf
from rest_framework.authentication import TokenAuthentication
from rest_framework.parsers import JSONParser
from rest_framework.permissions import DjangoModelPermissions
from rest_framework.views import APIView
from .models import FrontendDeployment
dev = """
<!doctype html>
<html lang="en">
<head>
<title>Loading | Falmer</title>
</head>
<body class="FalmerSite">
<script type="text/javascript">window.CSRF = "{csrf_token}";</script><|fim▁hole|> <script type="text/javascript" src="http://localhost:8080/vendor.js"></script>
<script type="text/javascript" src="http://localhost:8080/devFonts.js"></script>
<script type="text/javascript" src="http://localhost:8080/main.js"></script>
<script type="text/javascript" src="http://localhost:8080/productionFonts.js"></script>
</body>
</html>
"""
def application_serve(request):
if request.is_ajax() is False:
try:
deployment = FrontendDeployment.objects.filter(enabled=True).latest('created_at')
except FrontendDeployment.DoesNotExist:
return HttpResponse(dev.format(csrf_token=csrf(request)['csrf_token']))
return HttpResponse(deployment.content.format(csrf_token=csrf(request)['csrf_token']))
raise Http404()
class FrontendAPI(APIView):
authentication_classes = [TokenAuthentication, ]
permission_classes = [DjangoModelPermissions, ]
queryset = FrontendDeployment.objects.none()
def post(self, request):
FrontendDeployment.objects.create(
content=request.data['contents'],
)
return HttpResponse(status=200)<|fim▁end|> | <div class="FalmerAppRoot"></div> |
<|file_name|>accept_ranges.rs<|end_file_name|><|fim▁begin|>use std::fmt::{self, Display};
use std::str::FromStr;
header! {
#[doc="`Accept-Ranges` header, defined in"]
#[doc="[RFC7233](http://tools.ietf.org/html/rfc7233#section-2.3)"]
#[doc=""]
#[doc="The `Accept-Ranges` header field allows a server to indicate that it"]
#[doc="supports range requests for the target resource."]
#[doc=""]
#[doc="# ABNF"]
#[doc="```plain"]
#[doc="Accept-Ranges = acceptable-ranges"]
#[doc="acceptable-ranges = 1#range-unit / \"none\""]
#[doc=""]
#[doc="# Example values"]
#[doc="* `bytes`"]
#[doc="* `none`"]
#[doc="* `unknown-unit`"]
#[doc="```"]
#[doc=""]
#[doc="# Examples"]
#[doc="```"]
#[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"]
#[doc=""]
#[doc="let mut headers = Headers::new();"]
#[doc="headers.set(AcceptRanges(vec![RangeUnit::Bytes]));"]
#[doc="```"]
#[doc="```"]
#[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"]
#[doc=""]
#[doc="let mut headers = Headers::new();"]
#[doc="headers.set(AcceptRanges(vec![RangeUnit::None]));"]
#[doc="```"]
#[doc="```"]
#[doc="use hyper::header::{Headers, AcceptRanges, RangeUnit};"]
#[doc=""]
#[doc="let mut headers = Headers::new();"]
#[doc="headers.set("]
#[doc=" AcceptRanges(vec!["]
#[doc=" RangeUnit::Unregistered(\"nibbles\".to_owned()),"]
#[doc=" RangeUnit::Bytes,"]
#[doc=" RangeUnit::Unregistered(\"doublets\".to_owned()),"]
#[doc=" RangeUnit::Unregistered(\"quadlets\".to_owned()),"]
#[doc=" ])"]
#[doc=");"]
#[doc="```"]
(AcceptRanges, "Accept-Ranges") => (RangeUnit)+<|fim▁hole|> test_header!(test1, vec![b"bytes"]);
test_header!(test2, vec![b"none"]);
test_header!(test3, vec![b"unknown-unit"]);
test_header!(test4, vec![b"bytes, unknown-unit"]);
}
}
/// Range Units, described in [RFC7233](http://tools.ietf.org/html/rfc7233#section-2)
///
/// A representation can be partitioned into subranges according to
/// various structural units, depending on the structure inherent in the
/// representation's media type.
///
/// # ABNF
/// ```plain
/// range-unit = bytes-unit / other-range-unit
/// bytes-unit = "bytes"
/// other-range-unit = token
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RangeUnit {
/// Indicating byte-range requests are supported.
Bytes,
/// Reserved as keyword, indicating no ranges are supported.
None,
/// The given range unit is not registered at IANA.
Unregistered(String),
}
impl FromStr for RangeUnit {
type Err = ::Error;
fn from_str(s: &str) -> ::Result<Self> {
match s {
"bytes" => Ok(RangeUnit::Bytes),
"none" => Ok(RangeUnit::None),
// FIXME: Check if s is really a Token
_ => Ok(RangeUnit::Unregistered(s.to_owned())),
}
}
}
impl Display for RangeUnit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
RangeUnit::Bytes => f.write_str("bytes"),
RangeUnit::None => f.write_str("none"),
RangeUnit::Unregistered(ref x) => f.write_str(&x),
}
}
}<|fim▁end|> |
test_acccept_ranges { |
<|file_name|>upload_file.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
' 检查扩展名是否合法 '
__author__ = 'Ellery'
from app import app
import datetime, random
from PIL import Image
import os
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config.get('ALLOWED_EXTENSIONS')
def unique_name():
now_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
random_num = random.randint(0, 100)
if random_num <= 10:
random_num = str(0) + str(random_num)
unique_num = str(now_time) + str(random_num)
return unique_num
def image_thumbnail(filename):
filepath = os.path.join(app.config.get('UPLOAD_FOLDER'), filename)
im = Image.open(filepath)<|fim▁hole|>
if w > h:
im.thumbnail((106, 106*h/w))
else:
im.thumbnail((106*w/h, 106))
im.save(os.path.join(app.config.get('UPLOAD_FOLDER'),
os.path.splitext(filename)[0] + '_thumbnail' + os.path.splitext(filename)[1]))
def image_delete(filename):
thumbnail_filepath = os.path.join(app.config.get('UPLOAD_FOLDER'), filename)
filepath = thumbnail_filepath.replace('_thumbnail', '')
os.remove(filepath)
os.remove(thumbnail_filepath)
def cut_image(filename, box):
filepath = os.path.join(app.config.get('UPLOAD_AVATAR_FOLDER'), filename)
im = Image.open(filepath)
new_im = im.crop(box)
new_im.save(os.path.join(app.config.get('UPLOAD_AVATAR_FOLDER'), filename))<|fim▁end|> | w, h = im.size |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! Implements methods and structs required to go from binary to SSA
//!
//! Also acts a gateway for users to use the library. Check containers
//! submodule for more information.
pub mod ssaconstructor;
// Old/deprecated
pub mod containers;
pub mod source;
/*********************/
// New replacements<|fim▁hole|>// pub mod instruction_analyzer;
pub mod imports;
pub mod llanalyzer;<|fim▁end|> | pub mod radeco_containers;
pub mod radeco_source;
pub mod bindings; |
<|file_name|>FilterTest.py<|end_file_name|><|fim▁begin|>##########################################################################
#
# Copyright (c) 2013, Image Engine Design Inc. 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 Image Engine Design 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 unittest
import IECore
import Gaffer
import GafferImage
import os
class FilterTest( unittest.TestCase ) :
def testDefaultFilter( self ) :
filters = GafferImage.Filter.filters()
default = GafferImage.Filter.defaultFilter()
self.assertTrue( default in filters )
def testFilterList( self ) :
filters = GafferImage.Filter.filters()
self.assertTrue( len(filters) == 9 )
self.assertTrue( "Box" in filters )
self.assertTrue( "BSpline" in filters )
self.assertTrue( "Bilinear" in filters )
self.assertTrue( "Hermite" in filters )
self.assertTrue( "Mitchell" in filters )
self.assertTrue( "CatmullRom" in filters )
self.assertTrue( "Cubic" in filters )
self.assertTrue( "Lanczos" in filters )
self.assertTrue( "Sinc" in filters )
def testCreators( self ) :
filters = GafferImage.Filter.filters()
for name in filters :
f = GafferImage.Filter.create( name )<|fim▁hole|> self.assertTrue( f.typeName(), name+"Filter" )<|fim▁end|> | |
<|file_name|>MakeExternal.java<|end_file_name|><|fim▁begin|>package me.ccrama.redditslide.Activities;
import android.app.Activity;
import android.content.SharedPreferences;<|fim▁hole|>import java.net.MalformedURLException;
import java.net.URL;
import me.ccrama.redditslide.SettingValues;
/**
* Created by ccrama on 9/28/2015.
*/
public class MakeExternal extends Activity {
@Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
String url = getIntent().getStringExtra("url");
if (url != null) {
try {
URL u = new URL(url);
SettingValues.alwaysExternal.add(u.getHost());
SharedPreferences.Editor e = SettingValues.prefs.edit();
e.putStringSet(SettingValues.PREF_ALWAYS_EXTERNAL, SettingValues.alwaysExternal);
e.apply();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
finish();
}
}<|fim▁end|> | import android.os.Bundle;
|
<|file_name|>ErrorIcon.iconSketch.js<|end_file_name|><|fim▁begin|>import React from 'react';
import ErrorIcon from './ErrorIcon';
<|fim▁hole|>export const symbols = {
'ErrorIcon -> with filled': <ErrorIcon filled={true} />,
'ErrorIcon -> without filled': <ErrorIcon filled={false} />
};<|fim▁end|> | |
<|file_name|>kendo.columnmenu.js<|end_file_name|><|fim▁begin|>/*
* Kendo UI Web v2012.2.710 (http://kendoui.com)
* Copyright 2012 Telerik AD. All rights reserved.
*
* Kendo UI Web commercial licenses may be obtained at http://kendoui.com/web-license
* If you do not own a commercial license, this file shall be governed by the
* GNU General Public License (GPL) version 3.
* For GPL requirements, please review: http://www.gnu.org/copyleft/gpl.html
*/
(function($, undefined) {
var kendo = window.kendo,
ui = kendo.ui,
proxy = $.proxy,
extend = $.extend,
grep = $.grep,
map = $.map,
inArray = $.inArray,
ACTIVE = "k-state-selected",
ASC = "asc",
DESC = "desc",
CLICK = "click",
CHANGE = "change",
POPUP = "kendoPopup",
FILTERMENU = "kendoFilterMenu",
MENU = "kendoMenu",
Widget = ui.Widget;
function trim(text) {
if (!String.prototype.trim) {
text = text.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
} else {
text = text.trim();
}
return text.replace(/ /gi, "");
}
var ColumnMenu = Widget.extend({
init: function(element, options) {
var that = this,
link;
Widget.fn.init.call(that, element, options);
element = that.element;
options = that.options;
that.owner = options.owner;
that.field = element.attr(kendo.attr("field"));
link = element.find(".k-header-column-menu");
if (!link[0]) {
link = element.prepend('<a class="k-header-column-menu" href="#"><span class="k-icon k-i-arrowhead-s"/></a>').find(".k-header-column-menu");
}
that._clickHandler = proxy(that._click, that);
link.click(that._clickHandler);
that.link = link;
that.wrapper = $('<div class="k-column-menu"/>');
that.wrapper.html(kendo.template(template)({
ns: kendo.ns,
messages: options.messages,
sortable: options.sortable,
filterable: options.filterable,
columns: that._ownerColumns(),
showColumns: options.columns
}));
that.popup = that.wrapper[POPUP]({
anchor: link,
open: proxy(that._open, that)
}).data(POPUP);
that._menu();
that._sort();
that._columns();
that._filter();
},
options: {
name: "ColumnMenu",
messages: {
sortAscending: "Sort Ascending",
sortDescending: "Sort Descending",
filter: "Filter",
columns: "Columns"
},
columns: true,
sortable: true,
filterable: true
},
destroy: function() {
var that = this;
if (that.filterMenu) {
that.filterMenu.destroy();
that.filterMenu = null;
}
that.wrapper.children().removeData(MENU);
that.wrapper.removeData(POPUP).remove();
that.link.unbind(CLICK, that._clickHandler);
that.element.removeData("kendoColumnMenu");
that.columns = null;
},
close: function() {
this.menu.close();
this.popup.close();
},
_click: function(e) {
e.preventDefault();
e.stopPropagation();
this.popup.toggle();
},
_open: function() {
$(".k-column-menu").not(this.wrapper).each(function() {
$(this).data(POPUP).close();
});
},
_ownerColumns: function() {
var columns = this.owner.columns,
menuColumns = grep(columns, function(col) {
var result = true,<|fim▁hole|> }
return result;
});
return map(menuColumns, function(col) {
return {
field: col.field,
title: col.title || col.field,
hidden: col.hidden,
index: inArray(col, columns)
};
});
},
_menu: function() {
this.menu = this.wrapper.children()[MENU]({
orientation: "vertical",
closeOnClick: false
}).data(MENU);
},
_sort: function() {
var that = this;
if (that.options.sortable) {
that.refresh();
that.options.dataSource.bind(CHANGE, proxy(that.refresh, that));
that.menu.element.delegate(".k-sort-asc, .k-sort-desc", CLICK, function() {
var item = $(this),
dir = item.hasClass("k-sort-asc") ? ASC : DESC;
item.parent().find(".k-sort-" + (dir == ASC ? DESC : ASC)).removeClass(ACTIVE);
that._sortDataSource(item, dir);
that.close();
});
}
},
_sortDataSource: function(item, dir) {
var that = this,
sortable = that.options.sortable,
dataSource = that.options.dataSource,
idx,
length,
sort = dataSource.sort() || [];
if (item.hasClass(ACTIVE) && sortable && sortable.allowUnsort !== false) {
item.removeClass(ACTIVE);
dir = undefined;
} else {
item.addClass(ACTIVE);
}
if (sortable === true || sortable.mode === "single") {
sort = [ { field: that.field, dir: dir } ];
} else {
for (idx = 0, length = sort.length; idx < length; idx++) {
if (sort[idx].field === that.field) {
sort.splice(idx, 1);
break;
}
}
sort.push({ field: that.field, dir: dir });
}
dataSource.sort(sort);
},
_columns: function() {
var that = this;
if (that.options.columns) {
that._updateColumnsMenu();
that.owner.bind(["columnHide", "columnShow"], function() {
that._updateColumnsMenu();
});
that.wrapper.delegate("[type=checkbox]", CHANGE , function(e) {
var input = $(this),
index = parseInt(input.attr(kendo.attr("index")), 10);
if (input.is(":checked")) {
that.owner.showColumn(index);
} else {
that.owner.hideColumn(index);
}
});
}
},
_updateColumnsMenu: function() {
var columns = this._ownerColumns(),
allselector = map(columns, function(field) {
return "[" + kendo.attr("index") + "=" + field.index+ "]";
}).join(","),
visible = grep(columns, function(field) {
return !field.hidden;
}),
selector = map(visible, function(field) {
return "[" + kendo.attr("index") + "=" + field.index+ "]";
}).join(",");
this.wrapper.find(allselector).attr("checked", false);
this.wrapper.find(selector).attr("checked", true).attr("disabled", visible.length == 1);
},
_filter: function() {
var that = this,
options = that.options;
if (options.filterable !== false) {
that.filterMenu = that.wrapper.find(".k-filterable")[FILTERMENU](
extend(true, {}, {
appendToElement: true,
dataSource: options.dataSource,
values: options.values,
field: that.field
},
options.filterable)
).data(FILTERMENU);
}
},
refresh: function() {
var that = this,
sort = that.options.dataSource.sort() || [],
descriptor,
field = that.field,
idx,
length;
that.wrapper.find(".k-sort-asc, .k-sort-desc").removeClass(ACTIVE);
for (idx = 0, length = sort.length; idx < length; idx++) {
descriptor = sort[idx];
if (field == descriptor.field) {
that.wrapper.find(".k-sort-" + descriptor.dir).addClass(ACTIVE);
}
}
}
});
var template = '<ul>'+
'#if(sortable){#'+
'<li class="k-item k-sort-asc"><span class="k-link"><span class="k-sprite k-i-sort-asc"></span>${messages.sortAscending}</span></li>'+
'<li class="k-item k-sort-desc"><span class="k-link"><span class="k-sprite k-i-sort-desc"></span>${messages.sortDescending}</span></li>'+
'#if(showColumns || filterable){#'+
'<li class="k-separator"></li>'+
'#}#'+
'#}#'+
'#if(showColumns){#'+
'<li class="k-item k-columns-item"><span class="k-link"><span class="k-sprite k-i-columns"></span>${messages.columns}</span><ul>'+
'#for (var col in columns) {#'+
'<li><label><input type="checkbox" data-#=ns#field="#=columns[col].field#" data-#=ns#index="#=columns[col].index#"/>#=columns[col].title#</label></li>'+
'#}#'+
'</ul></li>'+
'#if(filterable){#'+
'<li class="k-separator"></li>'+
'#}#'+
'#}#'+
'#if(filterable){#'+
'<li class="k-item k-filter-item"><span class="k-link"><span class="k-sprite k-filter"></span>${messages.filter}</span><ul>'+
'<li><div class="k-filterable"></div></li>'+
'</ul></li>'+
'#}#'+
'</ul>';
ui.plugin(ColumnMenu);
})(jQuery);
;<|fim▁end|> | title = trim(col.title || "");
if (col.menu === false || (!col.field && !title.length)) {
result = false; |
<|file_name|>dexdata.ts<|end_file_name|><|fim▁begin|>export const BattleAvatarNumbers = {
1: 'lucas',
2: 'dawn',
3: 'youngster-gen4',
4: 'lass-gen4dp',
5: 'camper',
6: 'picnicker',
7: 'bugcatcher',
8: 'aromalady',
9: 'twins-gen4dp',
10: 'hiker-gen4',
11: 'battlegirl-gen4',
12: 'fisherman-gen4',
13: 'cyclist-gen4',
14: 'cyclistf-gen4',
15: 'blackbelt-gen4dp',
16: 'artist-gen4',
17: 'pokemonbreeder-gen4',
18: 'pokemonbreederf-gen4',
19: 'cowgirl',
20: 'jogger',
21: 'pokefan-gen4',
22: 'pokefanf-gen4',
23: 'pokekid',
24: 'youngcouple-gen4dp',
25: 'acetrainer-gen4dp',
26: 'acetrainerf-gen4dp',
27: 'waitress-gen4',
28: 'veteran-gen4',
29: 'ninjaboy',
30: 'dragontamer',
31: 'birdkeeper-gen4dp',
32: 'doubleteam',
33: 'richboy-gen4',
34: 'lady-gen4',
35: 'gentleman-gen4dp',
36: 'madame-gen4dp',
37: 'beauty-gen4dp',
38: 'collector',
39: 'policeman-gen4',
40: 'pokemonranger-gen4',
41: 'pokemonrangerf-gen4',
42: 'scientist-gen4dp',
43: 'swimmer-gen4dp',
44: 'swimmerf-gen4dp',
45: 'tuber',<|fim▁hole|> 50: 'psychic-gen4',
51: 'psychicf-gen4',
52: 'gambler',
53: 'guitarist-gen4',
54: 'acetrainersnow',
55: 'acetrainersnowf',
56: 'skier',
57: 'skierf-gen4dp',
58: 'roughneck-gen4',
59: 'clown',
60: 'worker-gen4',
61: 'schoolkid-gen4dp',
62: 'schoolkidf-gen4',
63: 'roark',
64: 'barry',
65: 'byron',
66: 'aaron',
67: 'bertha',
68: 'flint',
69: 'lucian',
70: 'cynthia-gen4',
71: 'bellepa',
72: 'rancher',
73: 'mars',
74: 'galacticgrunt',
75: 'gardenia',
76: 'crasherwake',
77: 'maylene',
78: 'fantina',
79: 'candice',
80: 'volkner',
81: 'parasollady-gen4',
82: 'waiter-gen4dp',
83: 'interviewers',
84: 'cameraman',
85: 'reporter',
86: 'idol',
87: 'cyrus',
88: 'jupiter',
89: 'saturn',
90: 'galacticgruntf',
91: 'argenta',
92: 'palmer',
93: 'thorton',
94: 'buck',
95: 'darach',
96: 'marley',
97: 'mira',
98: 'cheryl',
99: 'riley',
100: 'dahlia',
101: 'ethan',
102: 'lyra',
103: 'twins-gen4',
104: 'lass-gen4',
105: 'acetrainer-gen4',
106: 'acetrainerf-gen4',
107: 'juggler',
108: 'sage',
109: 'li',
110: 'gentleman-gen4',
111: 'teacher',
112: 'beauty',
113: 'birdkeeper',
114: 'swimmer-gen4',
115: 'swimmerf-gen4',
116: 'kimonogirl',
117: 'scientist-gen4',
118: 'acetrainercouple',
119: 'youngcouple',
120: 'supernerd',
121: 'medium',
122: 'schoolkid-gen4',
123: 'blackbelt-gen4',
124: 'pokemaniac',
125: 'firebreather',
126: 'burglar',
127: 'biker-gen4',
128: 'skierf',
129: 'boarder',
130: 'rocketgrunt',
131: 'rocketgruntf',
132: 'archer',
133: 'ariana',
134: 'proton',
135: 'petrel',
136: 'eusine',
137: 'lucas-gen4pt',
138: 'dawn-gen4pt',
139: 'madame-gen4',
140: 'waiter-gen4',
141: 'falkner',
142: 'bugsy',
143: 'whitney',
144: 'morty',
145: 'chuck',
146: 'jasmine',
147: 'pryce',
148: 'clair',
149: 'will',
150: 'koga',
151: 'bruno',
152: 'karen',
153: 'lance',
154: 'brock',
155: 'misty',
156: 'ltsurge',
157: 'erika',
158: 'janine',
159: 'sabrina',
160: 'blaine',
161: 'blue',
162: 'red',
163: 'red',
164: 'silver',
165: 'giovanni',
166: 'unknownf',
167: 'unknown',
168: 'unknown',
169: 'hilbert',
170: 'hilda',
171: 'youngster',
172: 'lass',
173: 'schoolkid',
174: 'schoolkidf',
175: 'smasher',
176: 'linebacker',
177: 'waiter',
178: 'waitress',
179: 'chili',
180: 'cilan',
181: 'cress',
182: 'nurseryaide',
183: 'preschoolerf',
184: 'preschooler',
185: 'twins',
186: 'pokemonbreeder',
187: 'pokemonbreederf',
188: 'lenora',
189: 'burgh',
190: 'elesa',
191: 'clay',
192: 'skyla',
193: 'pokemonranger',
194: 'pokemonrangerf',
195: 'worker',
196: 'backpacker',
197: 'backpackerf',
198: 'fisherman',
199: 'musician',
200: 'dancer',
201: 'harlequin',
202: 'artist',
203: 'baker',
204: 'psychic',
205: 'psychicf',
206: 'cheren',
207: 'bianca',
208: 'plasmagrunt-gen5bw',
209: 'n',
210: 'richboy',
211: 'lady',
212: 'pilot',
213: 'workerice',
214: 'hoopster',
215: 'scientistf',
216: 'clerkf',
217: 'acetrainerf',
218: 'acetrainer',
219: 'blackbelt',
220: 'scientist',
221: 'striker',
222: 'brycen',
223: 'iris',
224: 'drayden',
225: 'roughneck',
226: 'janitor',
227: 'pokefan',
228: 'pokefanf',
229: 'doctor',
230: 'nurse',
231: 'hooligans',
232: 'battlegirl',
233: 'parasollady',
234: 'clerk',
235: 'clerk-boss',
236: 'backers',
237: 'backersf',
238: 'veteran',
239: 'veteranf',
240: 'biker',
241: 'infielder',
242: 'hiker',
243: 'madame',
244: 'gentleman',
245: 'plasmagruntf-gen5bw',
246: 'shauntal',
247: 'marshal',
248: 'grimsley',
249: 'caitlin',
250: 'ghetsis-gen5bw',
251: 'depotagent',
252: 'swimmer',
253: 'swimmerf',
254: 'policeman',
255: 'maid',
256: 'ingo',
257: 'alder',
258: 'cyclist',
259: 'cyclistf',
260: 'cynthia',
261: 'emmet',
262: 'hilbert-dueldisk',
263: 'hilda-dueldisk',
264: 'hugh',
265: 'rosa',
266: 'nate',
267: 'colress',
268: 'beauty-gen5bw2',
269: 'ghetsis',
270: 'plasmagrunt',
271: 'plasmagruntf',
272: 'iris-gen5bw2',
273: 'brycenman',
274: 'shadowtriad',
275: 'rood',
276: 'zinzolin',
277: 'cheren-gen5bw2',
278: 'marlon',
279: 'roxie',
280: 'roxanne',
281: 'brawly',
282: 'wattson',
283: 'flannery',
284: 'norman',
285: 'winona',
286: 'tate',
287: 'liza',
288: 'juan',
289: 'guitarist',
290: 'steven',
291: 'wallace',
292: 'bellelba',
293: 'benga',
294: 'ash',
'#bw2elesa': 'elesa-gen5bw2',
'#teamrocket': 'teamrocket',
'#yellow': 'yellow',
'#zinnia': 'zinnia',
'#clemont': 'clemont',
'#wally': 'wally',
breeder: 'pokemonbreeder',
breederf: 'pokemonbreederf',
1001: '#1001',
1002: '#1002',
1003: '#1003',
1005: '#1005',
1010: '#1010',
};<|fim▁end|> | 46: 'tuberf',
47: 'sailor',
48: 'sisandbro',
49: 'ruinmaniac', |
<|file_name|>migration.py<|end_file_name|><|fim▁begin|># Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova import db
from nova import exception
from nova import objects
from nova.objects import base
from nova.objects import fields
# TODO(berrange): Remove NovaObjectDictCompat
class Migration(base.NovaPersistentObject, base.NovaObject,
base.NovaObjectDictCompat):
# Version 1.0: Initial version
# Version 1.1: String attributes updated to support unicode
VERSION = '1.1'
fields = {
'id': fields.IntegerField(),
'source_compute': fields.StringField(nullable=True),
'dest_compute': fields.StringField(nullable=True),
'source_node': fields.StringField(nullable=True),
'dest_node': fields.StringField(nullable=True),
'dest_host': fields.StringField(nullable=True),
'old_instance_type_id': fields.IntegerField(nullable=True),
'new_instance_type_id': fields.IntegerField(nullable=True),
'instance_uuid': fields.StringField(nullable=True),
'status': fields.StringField(nullable=True),
}<|fim▁hole|> for key in migration.fields:
migration[key] = db_migration[key]
migration._context = context
migration.obj_reset_changes()
return migration
@base.remotable_classmethod
def get_by_id(cls, context, migration_id):
db_migration = db.migration_get(context, migration_id)
return cls._from_db_object(context, cls(), db_migration)
@base.remotable_classmethod
def get_by_instance_and_status(cls, context, instance_uuid, status):
db_migration = db.migration_get_by_instance_and_status(
context, instance_uuid, status)
return cls._from_db_object(context, cls(), db_migration)
@base.remotable
def create(self):
if self.obj_attr_is_set('id'):
raise exception.ObjectActionError(action='create',
reason='already created')
updates = self.obj_get_changes()
db_migration = db.migration_create(self._context, updates)
self._from_db_object(self._context, self, db_migration)
@base.remotable
def save(self):
updates = self.obj_get_changes()
updates.pop('id', None)
db_migration = db.migration_update(self._context, self.id, updates)
self._from_db_object(self._context, self, db_migration)
self.obj_reset_changes()
@property
def instance(self):
return objects.Instance.get_by_uuid(self._context, self.instance_uuid)
class MigrationList(base.ObjectListBase, base.NovaObject):
# Version 1.0: Initial version
# Migration <= 1.1
# Version 1.1: Added use_slave to get_unconfirmed_by_dest_compute
VERSION = '1.1'
fields = {
'objects': fields.ListOfObjectsField('Migration'),
}
child_versions = {
'1.0': '1.1',
# NOTE(danms): Migration was at 1.1 before we added this
'1.1': '1.1',
}
@base.remotable_classmethod
def get_unconfirmed_by_dest_compute(cls, context, confirm_window,
dest_compute, use_slave=False):
db_migrations = db.migration_get_unconfirmed_by_dest_compute(
context, confirm_window, dest_compute, use_slave=use_slave)
return base.obj_make_list(context, cls(context), objects.Migration,
db_migrations)
@base.remotable_classmethod
def get_in_progress_by_host_and_node(cls, context, host, node):
db_migrations = db.migration_get_in_progress_by_host_and_node(
context, host, node)
return base.obj_make_list(context, cls(context), objects.Migration,
db_migrations)
@base.remotable_classmethod
def get_by_filters(cls, context, filters):
db_migrations = db.migration_get_all_by_filters(context, filters)
return base.obj_make_list(context, cls(context), objects.Migration,
db_migrations)<|fim▁end|> |
@staticmethod
def _from_db_object(context, migration, db_migration): |
<|file_name|>constants.py<|end_file_name|><|fim▁begin|>"""
Constants
"""
<|fim▁hole|>TOOL_PINDEL = 'pindel'
TOOL_DELLY = 'delly'
TOOL_LUMPY = 'lumpy'<|fim▁end|> | TOOL_FREEBAYES = 'freebayes' |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>app.config.from_object('config')<|fim▁end|> | from flask import Flask
app = Flask(__name__) |
<|file_name|>FinalizeOAuth.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
###############################################################################
#
# FinalizeOAuth
# Completes the OAuth process by retrieving a Foursquare access token for a user, after they have visited the authorization URL returned by the InitializeOAuth choreo and clicked "allow."
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
#
#
###############################################################################
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class FinalizeOAuth(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the FinalizeOAuth Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(FinalizeOAuth, self).__init__(temboo_session, '/Library/Foursquare/OAuth/FinalizeOAuth')
def new_input_set(self):
return FinalizeOAuthInputSet()
def _make_result_set(self, result, path):
return FinalizeOAuthResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return FinalizeOAuthChoreographyExecution(session, exec_id, path)
class FinalizeOAuthInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the FinalizeOAuth
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_AccountName(self, value):
"""
Set the value of the AccountName input for this Choreo. ((optional, string) Deprecated (retained for backward compatibility only).)
"""
super(FinalizeOAuthInputSet, self)._set_input('AccountName', value)
def set_AppKeyName(self, value):
"""
Set the value of the AppKeyName input for this Choreo. ((optional, string) Deprecated (retained for backward compatibility only).)
"""
super(FinalizeOAuthInputSet, self)._set_input('AppKeyName', value)
def set_AppKeyValue(self, value):
"""
Set the value of the AppKeyValue input for this Choreo. ((optional, string) Deprecated (retained for backward compatibility only).)
"""
super(FinalizeOAuthInputSet, self)._set_input('AppKeyValue', value)
def set_CallbackID(self, value):
"""
Set the value of the CallbackID input for this Choreo. ((required, string) The callback token returned by the InitializeOAuth Choreo. Used to retrieve the authorization code after the user authorizes.)
"""
super(FinalizeOAuthInputSet, self)._set_input('CallbackID', value)
def set_ClientID(self, value):
"""
Set the value of the ClientID input for this Choreo. ((required, string) The Client ID provided by Foursquare after registering your application.)
"""
super(FinalizeOAuthInputSet, self)._set_input('ClientID', value)
def set_ClientSecret(self, value):
"""
Set the value of the ClientSecret input for this Choreo. ((required, string) The Client Secret provided by Foursquare after registering your application.)
"""
super(FinalizeOAuthInputSet, self)._set_input('ClientSecret', value)
def set_Timeout(self, value):
"""
Set the value of the Timeout input for this Choreo. ((optional, integer) The amount of time (in seconds) to poll your Temboo callback URL to see if your app's user has allowed or denied the request for access. Defaults to 20. Max is 60.)
"""
super(FinalizeOAuthInputSet, self)._set_input('Timeout', value)
class FinalizeOAuthResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the FinalizeOAuth Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_AccessToken(self):
"""
Retrieve the value for the "AccessToken" output from this Choreo execution. ((string) The access token for the user that has granted access to your application.)
"""
return self._output.get('AccessToken', None)
<|fim▁hole|> return FinalizeOAuthResultSet(response, path)<|fim▁end|> | class FinalizeOAuthChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path): |
<|file_name|>warnings.rs<|end_file_name|><|fim▁begin|>// A warning for an unused variable
fn main() {
let x = true;<|fim▁hole|><|fim▁end|> | } |
<|file_name|>access.py<|end_file_name|><|fim▁begin|>"""This file contains (or should), all access control logic for the courseware.
Ideally, it will be the only place that needs to know about any special settings
like DISABLE_START_DATES"""
import logging
from datetime import datetime, timedelta
import pytz
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from xmodule.course_module import (
CourseDescriptor, CATALOG_VISIBILITY_CATALOG_AND_ABOUT,
CATALOG_VISIBILITY_ABOUT)
from xmodule.error_module import ErrorDescriptor
from xmodule.x_module import XModule
from xblock.core import XBlock
from external_auth.models import ExternalAuthMap
from courseware.masquerade import is_masquerading_as_student
from django.utils.timezone import UTC
from student import auth
from student.roles import (
GlobalStaff, CourseStaffRole, CourseInstructorRole,
OrgStaffRole, OrgInstructorRole, CourseBetaTesterRole
)
from student.models import CourseEnrollment, CourseEnrollmentAllowed
from opaque_keys.edx.keys import CourseKey, UsageKey
DEBUG_ACCESS = False
log = logging.getLogger(__name__)
def debug(*args, **kwargs):
# to avoid overly verbose output, this is off by default
if DEBUG_ACCESS:
log.debug(*args, **kwargs)
def has_access(user, action, obj, course_key=None):
"""
Check whether a user has the access to do action on obj. Handles any magic
switching based on various settings.
Things this module understands:
- start dates for modules
- visible_to_staff_only for modules
- DISABLE_START_DATES
- different access for instructor, staff, course staff, and students.
- mobile_available flag for course modules
user: a Django user object. May be anonymous. If none is passed,
anonymous is assumed
obj: The object to check access for. A module, descriptor, location, or
certain special strings (e.g. 'global')
action: A string specifying the action that the client is trying to perform.
actions depend on the obj type, but include e.g. 'enroll' for courses. See the
type-specific functions below for the known actions for that type.
course_key: A course_key specifying which course run this access is for.
Required when accessing anything other than a CourseDescriptor, 'global',
or a location with category 'course'
Returns a bool. It is up to the caller to actually deny access in a way
that makes sense in context.
"""
# Just in case user is passed in as None, make them anonymous
if not user:
user = AnonymousUser()
# delegate the work to type-specific functions.
# (start with more specific types, then get more general)
if isinstance(obj, CourseDescriptor):
return _has_access_course_desc(user, action, obj)
if isinstance(obj, ErrorDescriptor):
return _has_access_error_desc(user, action, obj, course_key)
if isinstance(obj, XModule):
return _has_access_xmodule(user, action, obj, course_key)
# NOTE: any descriptor access checkers need to go above this
if isinstance(obj, XBlock):
return _has_access_descriptor(user, action, obj, course_key)
if isinstance(obj, CourseKey):
return _has_access_course_key(user, action, obj)
if isinstance(obj, UsageKey):
return _has_access_location(user, action, obj, course_key)
if isinstance(obj, basestring):
return _has_access_string(user, action, obj, course_key)
# Passing an unknown object here is a coding error, so rather than
# returning a default, complain.
raise TypeError("Unknown object type in has_access(): '{0}'"
.format(type(obj)))
# ================ Implementation helpers ================================
def _has_access_course_desc(user, action, course):
"""
Check if user has access to a course descriptor.
Valid actions:
'load' -- load the courseware, see inside the course
'load_forum' -- can load and contribute to the forums (one access level for now)
'load_mobile' -- can load from a mobile context
'load_mobile_no_enrollment_check' -- can load from a mobile context without checking for enrollment
'enroll' -- enroll. Checks for enrollment window,
ACCESS_REQUIRE_STAFF_FOR_COURSE,
'see_exists' -- can see that the course exists.
'staff' -- staff access to course.
'see_in_catalog' -- user is able to see the course listed in the course catalog.
'see_about_page' -- user is able to see the course about page.
"""
def can_load():
"""
Can this user load this course?
NOTE: this is not checking whether user is actually enrolled in the course.
"""
# delegate to generic descriptor check to check start dates
return _has_access_descriptor(user, 'load', course, course.id)
def can_load_forum():
"""
Can this user access the forums in this course?
"""
return (
can_load() and
(
CourseEnrollment.is_enrolled(user, course.id) or
_has_staff_access_to_descriptor(user, course, course.id)
)
)
def can_load_mobile():
"""
Can this user access this course from a mobile device?
"""
return (
# check mobile requirements
can_load_mobile_no_enroll_check() and
# check enrollment
(
CourseEnrollment.is_enrolled(user, course.id) or
_has_staff_access_to_descriptor(user, course, course.id)
)
)
def can_load_mobile_no_enroll_check():
"""
Can this enrolled user access this course from a mobile device?
Note: does not check for enrollment since it is assumed the caller has done so.
"""
return (
# check start date
can_load() and
# check mobile_available flag
(
course.mobile_available or
auth.has_access(user, CourseBetaTesterRole(course.id)) or
_has_staff_access_to_descriptor(user, course, course.id)
)
)
def can_enroll():
"""
First check if restriction of enrollment by login method is enabled, both
globally and by the course.
If it is, then the user must pass the criterion set by the course, e.g. that ExternalAuthMap
was set by 'shib:https://idp.stanford.edu/", in addition to requirements below.
Rest of requirements:
(CourseEnrollmentAllowed always overrides)
or
(staff can always enroll)
or
Enrollment can only happen in the course enrollment period, if one exists, and
course is not invitation only.
"""
# if using registration method to restrict (say shibboleth)
if settings.FEATURES.get('RESTRICT_ENROLL_BY_REG_METHOD') and course.enrollment_domain:
if user is not None and user.is_authenticated() and \
ExternalAuthMap.objects.filter(user=user, external_domain=course.enrollment_domain):
debug("Allow: external_auth of " + course.enrollment_domain)
reg_method_ok = True
else:
reg_method_ok = False
else:
reg_method_ok = True # if not using this access check, it's always OK.
now = datetime.now(UTC())
start = course.enrollment_start or datetime.min.replace(tzinfo=pytz.UTC)
end = course.enrollment_end or datetime.max.replace(tzinfo=pytz.UTC)
# if user is in CourseEnrollmentAllowed with right course key then can also enroll
# (note that course.id actually points to a CourseKey)
# (the filter call uses course_id= since that's the legacy database schema)
# (sorry that it's confusing :( )
if user is not None and user.is_authenticated() and CourseEnrollmentAllowed:
if CourseEnrollmentAllowed.objects.filter(email=user.email, course_id=course.id):
return True
if _has_staff_access_to_descriptor(user, course, course.id):
return True
# Invitation_only doesn't apply to CourseEnrollmentAllowed or has_staff_access_access
if course.invitation_only:
debug("Deny: invitation only")
return False
if reg_method_ok and start < now < end:
debug("Allow: in enrollment period")
return True
def see_exists():
"""
Can see if can enroll, but also if can load it: if user enrolled in a course and now
it's past the enrollment period, they should still see it.
TODO (vshnayder): This means that courses with limited enrollment periods will not appear
to non-staff visitors after the enrollment period is over. If this is not what we want, will
need to change this logic.
"""
# VS[compat] -- this setting should go away once all courses have
# properly configured enrollment_start times (if course should be
# staff-only, set enrollment_start far in the future.)
if settings.FEATURES.get('ACCESS_REQUIRE_STAFF_FOR_COURSE'):
# if this feature is on, only allow courses that have ispublic set to be
# seen by non-staff
if course.ispublic:
debug("Allow: ACCESS_REQUIRE_STAFF_FOR_COURSE and ispublic")
return True
return _has_staff_access_to_descriptor(user, course, course.id)
return can_enroll() or can_load()
def can_see_in_catalog():
"""
Implements the "can see course in catalog" logic if a course should be visible in the main course catalog
In this case we use the catalog_visibility property on the course descriptor
but also allow course staff to see this.
"""
return (
course.catalog_visibility == CATALOG_VISIBILITY_CATALOG_AND_ABOUT or
_has_staff_access_to_descriptor(user, course, course.id)
)
def can_see_about_page():
"""
Implements the "can see course about page" logic if a course about page should be visible
In this case we use the catalog_visibility property on the course descriptor
but also allow course staff to see this.
"""
return (
course.catalog_visibility == CATALOG_VISIBILITY_CATALOG_AND_ABOUT or
course.catalog_visibility == CATALOG_VISIBILITY_ABOUT or
_has_staff_access_to_descriptor(user, course, course.id)
)
checkers = {
'load': can_load,
'load_forum': can_load_forum,
'load_mobile': can_load_mobile,
'load_mobile_no_enrollment_check': can_load_mobile_no_enroll_check,
'enroll': can_enroll,
'see_exists': see_exists,
'staff': lambda: _has_staff_access_to_descriptor(user, course, course.id),
'instructor': lambda: _has_instructor_access_to_descriptor(user, course, course.id),
'see_in_catalog': can_see_in_catalog,
'see_about_page': can_see_about_page,
}
return _dispatch(checkers, action, user, course)
def _has_access_error_desc(user, action, descriptor, course_key):
"""
Only staff should see error descriptors.
Valid actions:
'load' -- load this descriptor, showing it to the user.
'staff' -- staff access to descriptor.
"""
def check_for_staff():
return _has_staff_access_to_descriptor(user, descriptor, course_key)
checkers = {
'load': check_for_staff,
'staff': check_for_staff,
'instructor': lambda: _has_instructor_access_to_descriptor(user, descriptor, course_key)
}
return _dispatch(checkers, action, user, descriptor)
def _has_access_descriptor(user, action, descriptor, course_key=None):
"""
Check if user has access to this descriptor.
Valid actions:
'load' -- load this descriptor, showing it to the user.
'staff' -- staff access to descriptor.
NOTE: This is the fallback logic for descriptors that don't have custom policy
(e.g. courses). If you call this method directly instead of going through
has_access(), it will not do the right thing.
"""
def can_load():
"""
NOTE: This does not check that the student is enrolled in the course
that contains this module. We may or may not want to allow non-enrolled
students to see modules. If not, views should check the course, so we
don't have to hit the enrollments table on every module load.
"""
if descriptor.visible_to_staff_only and not _has_staff_access_to_descriptor(user, descriptor, course_key):
return False
# If start dates are off, can always load
if settings.FEATURES['DISABLE_START_DATES'] and not is_masquerading_as_student(user):
debug("Allow: DISABLE_START_DATES")
return True
# Check start date
if 'detached' not in descriptor._class_tags and descriptor.start is not None:
now = datetime.now(UTC())
effective_start = _adjust_start_date_for_beta_testers(
user,
descriptor,
course_key=course_key
)
if now > effective_start:
# after start date, everyone can see it
debug("Allow: now > effective start date")
return True
# otherwise, need staff access
return _has_staff_access_to_descriptor(user, descriptor, course_key)
# No start date, so can always load.
debug("Allow: no start date")
return True
checkers = {
'load': can_load,
'staff': lambda: _has_staff_access_to_descriptor(user, descriptor, course_key),
'instructor': lambda: _has_instructor_access_to_descriptor(user, descriptor, course_key)
}
return _dispatch(checkers, action, user, descriptor)
def _has_access_xmodule(user, action, xmodule, course_key):
"""
Check if user has access to this xmodule.
Valid actions:
- same as the valid actions for xmodule.descriptor
"""
# Delegate to the descriptor
return has_access(user, action, xmodule.descriptor, course_key)
def _has_access_location(user, action, location, course_key):
"""
Check if user has access to this location.
Valid actions:
'staff' : True if the user has staff access to this location
NOTE: if you add other actions, make sure that
has_access(user, location, action) == has_access(user, get_item(location), action)
"""
checkers = {
'staff': lambda: _has_staff_access_to_location(user, location, course_key)
}
return _dispatch(checkers, action, user, location)
def _has_access_course_key(user, action, course_key):
"""
Check if user has access to the course with this course_key
Valid actions:
'staff' : True if the user has staff access to this location
'instructor' : True if the user has staff access to this location
"""
checkers = {
'staff': lambda: _has_staff_access_to_location(user, None, course_key),
'instructor': lambda: _has_instructor_access_to_location(user, None, course_key),
}
return _dispatch(checkers, action, user, course_key)
def _has_access_string(user, action, perm, course_key):
"""
Check if user has certain special access, specified as string. Valid strings:
'global'
Valid actions:<|fim▁hole|> """
def check_staff():
if perm != 'global':
debug("Deny: invalid permission '%s'", perm)
return False
return GlobalStaff().has_user(user)
checkers = {
'staff': check_staff
}
return _dispatch(checkers, action, user, perm)
##### Internal helper methods below
def _dispatch(table, action, user, obj):
"""
Helper: call table[action], raising a nice pretty error if there is no such key.
user and object passed in only for error messages and debugging
"""
if action in table:
result = table[action]()
debug("%s user %s, object %s, action %s",
'ALLOWED' if result else 'DENIED',
user,
obj.location.to_deprecated_string() if isinstance(obj, XBlock) else str(obj),
action)
return result
raise ValueError(u"Unknown action for object type '{0}': '{1}'".format(
type(obj), action))
def _adjust_start_date_for_beta_testers(user, descriptor, course_key=None): # pylint: disable=invalid-name
"""
If user is in a beta test group, adjust the start date by the appropriate number of
days.
Arguments:
user: A django user. May be anonymous.
descriptor: the XModuleDescriptor the user is trying to get access to, with a
non-None start date.
Returns:
A datetime. Either the same as start, or earlier for beta testers.
NOTE: number of days to adjust should be cached to avoid looking it up thousands of
times per query.
NOTE: For now, this function assumes that the descriptor's location is in the course
the user is looking at. Once we have proper usages and definitions per the XBlock
design, this should use the course the usage is in.
NOTE: If testing manually, make sure FEATURES['DISABLE_START_DATES'] = False
in envs/dev.py!
"""
if descriptor.days_early_for_beta is None:
# bail early if no beta testing is set up
return descriptor.start
if CourseBetaTesterRole(course_key).has_user(user):
debug("Adjust start time: user in beta role for %s", descriptor)
delta = timedelta(descriptor.days_early_for_beta)
effective = descriptor.start - delta
return effective
return descriptor.start
def _has_instructor_access_to_location(user, location, course_key=None):
if course_key is None:
course_key = location.course_key
return _has_access_to_course(user, 'instructor', course_key)
def _has_staff_access_to_location(user, location, course_key=None):
if course_key is None:
course_key = location.course_key
return _has_access_to_course(user, 'staff', course_key)
def _has_access_to_course(user, access_level, course_key):
'''
Returns True if the given user has access_level (= staff or
instructor) access to the course with the given course_key.
This ensures the user is authenticated and checks if global staff or has
staff / instructor access.
access_level = string, either "staff" or "instructor"
'''
if user is None or (not user.is_authenticated()):
debug("Deny: no user or anon user")
return False
if is_masquerading_as_student(user):
return False
if GlobalStaff().has_user(user):
debug("Allow: user.is_staff")
return True
if access_level not in ('staff', 'instructor'):
log.debug("Error in access._has_access_to_course access_level=%s unknown", access_level)
debug("Deny: unknown access level")
return False
staff_access = (
CourseStaffRole(course_key).has_user(user) or
OrgStaffRole(course_key.org).has_user(user)
)
if staff_access and access_level == 'staff':
debug("Allow: user has course staff access")
return True
instructor_access = (
CourseInstructorRole(course_key).has_user(user) or
OrgInstructorRole(course_key.org).has_user(user)
)
if instructor_access and access_level in ('staff', 'instructor'):
debug("Allow: user has course instructor access")
return True
debug("Deny: user did not have correct access")
return False
def _has_instructor_access_to_descriptor(user, descriptor, course_key): # pylint: disable=invalid-name
"""Helper method that checks whether the user has staff access to
the course of the location.
descriptor: something that has a location attribute
"""
return _has_instructor_access_to_location(user, descriptor.location, course_key)
def _has_staff_access_to_descriptor(user, descriptor, course_key):
"""Helper method that checks whether the user has staff access to
the course of the location.
descriptor: something that has a location attribute
"""
return _has_staff_access_to_location(user, descriptor.location, course_key)
def get_user_role(user, course_key):
"""
Return corresponding string if user has staff, instructor or student
course role in LMS.
"""
if is_masquerading_as_student(user):
return 'student'
elif has_access(user, 'instructor', course_key):
return 'instructor'
elif has_access(user, 'staff', course_key):
return 'staff'
else:
return 'student'<|fim▁end|> |
'staff' -- global staff access. |
<|file_name|>start_grammar.rs<|end_file_name|><|fim▁begin|>use crate::grammar::ElemTypes;
use crate::grammar::{
build, Elem, Grammar, GrammarErrors, Prod, ProdElement, Rule,
};
use crate::utils::{take_only, ToDoc};
use std::marker::PhantomData;
#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Debug)]
pub enum StreamTerminal<T> {
EndOfStream,
Term(T),
}
impl<T> StreamTerminal<T>
where
T: Eq,
{
pub fn has_kind(&self, kind: &T) -> bool {
match self {
StreamTerminal::Term(t) => t == kind,
StreamTerminal::EndOfStream => false,
}
}
pub fn is_eos(&self) -> bool {
matches!(self, StreamTerminal::EndOfStream)
}
}
impl<T> ToDoc for StreamTerminal<T>
where
T: ToDoc,
{
fn to_doc<'a, DA: pretty::DocAllocator<'a>>(
&self,
da: &'a DA,
) -> pretty::DocBuilder<'a, DA>
where
DA::Doc: Clone,
{
match self {
StreamTerminal::EndOfStream => da.text("<EOS>"),
StreamTerminal::Term(t) => t.to_doc(da),
}
}
}
#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Debug)]
pub enum StartNonTerminal<NT> {
Start,
NTerm(NT),
}
impl<NT> ToDoc for StartNonTerminal<NT>
where
NT: ToDoc,
{
fn to_doc<'a, DA: pretty::DocAllocator<'a>>(
&self,
da: &'a DA,
) -> pretty::DocBuilder<'a, DA>
where
DA::Doc: Clone,
{
match self {
StartNonTerminal::Start => da.text("<START>"),
StartNonTerminal::NTerm(nt) => nt.to_doc(da),
}
}
}
#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Debug)]
pub enum StartActionKey<AK> {
Start,
ActionKey(AK),
}
impl<AK> StartActionKey<AK> {
pub fn as_base(&self) -> Option<&AK> {
match self {
StartActionKey::Start => None,
StartActionKey::ActionKey(ak) => Some(ak),
}
}
}
impl<AK> ToDoc for StartActionKey<AK>
where
AK: ToDoc,
{
fn to_doc<'a, DA: pretty::DocAllocator<'a>>(
&self,
da: &'a DA,
) -> pretty::DocBuilder<'a, DA>
where
DA::Doc: Clone,
{
match self {
StartActionKey::Start => da.text("<START>"),
StartActionKey::ActionKey(ak) => ak.to_doc(da),
}
}
}
#[derive(Clone, Debug)]
pub enum StartActionValue<AV> {
Start,
ActionValue(AV),
}
impl<AV> ToDoc for StartActionValue<AV>
where
AV: ToDoc,
{
fn to_doc<'a, DA: pretty::DocAllocator<'a>>(
&self,
da: &'a DA,
) -> pretty::DocBuilder<'a, DA>
where
DA::Doc: Clone,
{
match self {
StartActionValue::Start => da.text("<START>"),
StartActionValue::ActionValue(av) => av.to_doc(da),
}
}
}
#[derive(Derivative)]
#[derivative(Clone(bound = ""), Debug(bound = ""))]
pub struct StartElementTypes<E>(PhantomData<E>);
impl<E: ElemTypes> ElemTypes for StartElementTypes<E> {
type Term = StreamTerminal<E::Term>;
type NonTerm = StartNonTerminal<E::NonTerm>;
type ActionKey = StartActionKey<E::ActionKey>;
type ActionValue = StartActionValue<E::ActionValue>;
}
pub type StartGrammar<E> = Grammar<StartElementTypes<E>>;
impl<E: ElemTypes> StartGrammar<E> {
pub fn start_rule(&self) -> Rule<StartElementTypes<E>> {
self.get_rule(&StartNonTerminal::Start)
}
pub fn start_prod(&self) -> Prod<StartElementTypes<E>> {
take_only(self.start_rule().prods())
.expect("The start rule should only have a single production.")
}
}
fn base_elem_to_start_elem<E: ElemTypes>(
elem: Elem<E>,
) -> Elem<StartElementTypes<E>> {
match elem {
Elem::Term(t) => Elem::Term(StreamTerminal::Term(t)),
Elem::NonTerm(nt) => Elem::NonTerm(StartNonTerminal::NTerm(nt)),
}
}
pub fn wrap_grammar_with_start<E: ElemTypes>(
g: Grammar<E>,
) -> Result<Grammar<StartElementTypes<E>>, GrammarErrors<StartElementTypes<E>>>
{
build(StartNonTerminal::Start, |gb| {
gb.add_rule(StartNonTerminal::Start, |rb| {
rb.add_prod(StartActionKey::Start, StartActionValue::Start, |pb| {
pb.add_named_nonterm(
"start",
StartNonTerminal::NTerm(g.start_nt().clone()),
)
.add_term(StreamTerminal::EndOfStream);
});
});
for rule in g.rules() {
gb.add_rule(StartNonTerminal::NTerm(rule.head().clone()), |rb| {
for prod in rule.prods() {
rb.add_prod_with_elems(
StartActionKey::ActionKey(prod.action_key().clone()),
StartActionValue::ActionValue(prod.action_value().clone()),
prod
.prod_elements()
.iter()
.map(|e| {
ProdElement::new(
e.id().cloned(),
base_elem_to_start_elem(e.elem().clone()),
)
})<|fim▁hole|> }
})
}<|fim▁end|> | .collect::<Vec<_>>(),
);
}
}); |
<|file_name|>test_encryption.py<|end_file_name|><|fim▁begin|>import io
import tempfile
import unittest
from zipencrypt import ZipFile, ZipInfo, ZIP_DEFLATED
from zipencrypt.zipencrypt2 import _ZipEncrypter, _ZipDecrypter
class TestEncryption(unittest.TestCase):
def setUp(self):
self.plain = "plaintext" * 3
self.pwd = b"password"
def test_roundtrip(self):
encrypt = _ZipEncrypter(self.pwd)
encrypted = map(encrypt, self.plain)
decrypt = _ZipDecrypter(self.pwd)
decrypted = "".join(map(decrypt, encrypted))
self.assertEqual(self.plain, decrypted)
class TestZipfile(unittest.TestCase):
def setUp(self):
self.zipfile = io.BytesIO()
self.plain = "plaintext" * 3
self.pwd = "password"
def test_writestr(self):
with ZipFile(self.zipfile, mode="w") as zipfd:
zipfd.writestr("file1.txt", self.plain, pwd=self.pwd)
with ZipFile(self.zipfile) as zipfd:
content = zipfd.read("file1.txt", pwd=self.pwd)
self.assertEqual(self.plain, content)
def test_writestr_keep_file_open(self):
with ZipFile(self.zipfile, mode="w") as zipfd:
zipfd.writestr("file1.txt", self.plain, pwd=self.pwd)
content = zipfd.read("file1.txt", pwd=self.pwd)
self.assertEqual(self.plain, content)
def test_writestr_with_zipinfo(self):
zinfo = ZipInfo(filename="file1.txt")
zinfo.flag_bits |= 0x8
with ZipFile(self.zipfile, mode="w") as zipfd:
zipfd.writestr(zinfo, self.plain, pwd=self.pwd)
with ZipFile(self.zipfile) as zipfd:
content = zipfd.read("file1.txt", pwd=self.pwd)
self.assertEqual(self.plain, content)
def test_writestr_with_zipinfo_keep_file_open(self):
zinfo = ZipInfo(filename="file1.txt")
zinfo.flag_bits |= 0x8
with ZipFile(self.zipfile, mode="w") as zipfd:
zipfd.writestr(zinfo, self.plain, pwd=self.pwd)
content = zipfd.read("file1.txt", pwd=self.pwd)
self.assertEqual(self.plain, content)
def test_write_with_password(self):
with tempfile.NamedTemporaryFile(bufsize=0) as fd:
fd.write(self.plain)
with ZipFile(self.zipfile, mode="w") as zipfd:
zipfd.write(fd.name, arcname="file1.txt", pwd=self.pwd)
with ZipFile(self.zipfile) as zipfd:
content = zipfd.read("file1.txt", pwd=self.pwd)
self.assertEqual(self.plain, content)
def test_write_with_password_keep_file_open(self):
with tempfile.NamedTemporaryFile(bufsize=0) as fd:
fd.write(self.plain)
with ZipFile(self.zipfile, mode="w") as zipfd:
zipfd.write(fd.name, arcname="file1.txt", pwd=self.pwd)
content = zipfd.read("file1.txt", pwd=self.pwd)
self.assertEqual(self.plain, content)<|fim▁hole|> zipfd.writestr("file1.txt", self.plain, compress_type=ZIP_DEFLATED, pwd=self.pwd)
with ZipFile(self.zipfile) as zipfd:
content = zipfd.read("file1.txt", pwd=self.pwd)
self.assertEqual(self.plain, content)
if __name__ == '__main__':
unittest.main()<|fim▁end|> |
def test_setcompressiontype(self):
with ZipFile(self.zipfile, mode="w") as zipfd: |
<|file_name|>bump.rs<|end_file_name|><|fim▁begin|>//! # Bump frame allocator
//! Some code was borrowed from [Phil Opp's Blog](http://os.phil-opp.com/allocating-frames.html)
use paging::PhysicalAddress;
use super::{Frame, FrameAllocator, MemoryArea, MemoryAreaIter};
pub struct BumpAllocator {
next_free_frame: Frame,
current_area: Option<&'static MemoryArea>,
areas: MemoryAreaIter,
kernel_start: Frame,
kernel_end: Frame
}
impl BumpAllocator {
pub fn new(kernel_start: usize, kernel_end: usize, memory_areas: MemoryAreaIter) -> Self {
let mut allocator = Self {
next_free_frame: Frame::containing_address(PhysicalAddress::new(0)),
current_area: None,
areas: memory_areas,
kernel_start: Frame::containing_address(PhysicalAddress::new(kernel_start)),<|fim▁hole|> }
fn choose_next_area(&mut self) {
self.current_area = self.areas.clone().filter(|area| {
let address = area.base_addr + area.length - 1;
Frame::containing_address(PhysicalAddress::new(address as usize)) >= self.next_free_frame
}).min_by_key(|area| area.base_addr);
if let Some(area) = self.current_area {
let start_frame = Frame::containing_address(PhysicalAddress::new(area.base_addr as usize));
if self.next_free_frame < start_frame {
self.next_free_frame = start_frame;
}
}
}
}
impl FrameAllocator for BumpAllocator {
#[allow(unused)]
fn set_noncore(&mut self, noncore: bool) {}
fn free_frames(&self) -> usize {
let mut count = 0;
for area in self.areas.clone() {
let start_frame = Frame::containing_address(PhysicalAddress::new(area.base_addr as usize));
let end_frame = Frame::containing_address(PhysicalAddress::new((area.base_addr + area.length - 1) as usize));
for frame in Frame::range_inclusive(start_frame, end_frame) {
if frame >= self.kernel_start && frame <= self.kernel_end {
// Inside of kernel range
} else if frame >= self.next_free_frame {
// Frame is in free range
count += 1;
} else {
// Inside of used range
}
}
}
count
}
fn used_frames(&self) -> usize {
let mut count = 0;
for area in self.areas.clone() {
let start_frame = Frame::containing_address(PhysicalAddress::new(area.base_addr as usize));
let end_frame = Frame::containing_address(PhysicalAddress::new((area.base_addr + area.length - 1) as usize));
for frame in Frame::range_inclusive(start_frame, end_frame) {
if frame >= self.kernel_start && frame <= self.kernel_end {
// Inside of kernel range
count += 1
} else if frame >= self.next_free_frame {
// Frame is in free range
} else {
count += 1;
}
}
}
count
}
fn allocate_frames(&mut self, count: usize) -> Option<Frame> {
if count == 0 {
None
} else if let Some(area) = self.current_area {
// "Clone" the frame to return it if it's free. Frame doesn't
// implement Clone, but we can construct an identical frame.
let start_frame = Frame{ number: self.next_free_frame.number };
let end_frame = Frame { number: self.next_free_frame.number + (count - 1) };
// the last frame of the current area
let current_area_last_frame = {
let address = area.base_addr + area.length - 1;
Frame::containing_address(PhysicalAddress::new(address as usize))
};
if end_frame > current_area_last_frame {
// all frames of current area are used, switch to next area
self.choose_next_area();
} else if (start_frame >= self.kernel_start && start_frame <= self.kernel_end)
|| (end_frame >= self.kernel_start && end_frame <= self.kernel_end) {
// `frame` is used by the kernel
self.next_free_frame = Frame {
number: self.kernel_end.number + 1
};
} else {
// frame is unused, increment `next_free_frame` and return it
self.next_free_frame.number += count;
return Some(start_frame);
}
// `frame` was not valid, try it again with the updated `next_free_frame`
self.allocate_frames(count)
} else {
None // no free frames left
}
}
fn deallocate_frames(&mut self, _frame: Frame, _count: usize) {
//panic!("BumpAllocator::deallocate_frame: not supported: {:?}", frame);
}
}<|fim▁end|> | kernel_end: Frame::containing_address(PhysicalAddress::new(kernel_end))
};
allocator.choose_next_area();
allocator |
<|file_name|>routes.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from framework.routing import Rule, json_renderer
from website.addons.github import views
settings_routes = {
'rules': [
# Configuration
Rule(
[
'/project/<pid>/github/settings/',
'/project/<pid>/node/<nid>/github/settings/',
],
'post',
views.config.github_set_config,
json_renderer,
),
Rule(
[
'/project/<pid>/github/tarball/',
'/project/<pid>/node/<nid>/github/tarball/',
],
'get',
views.crud.github_download_starball,
json_renderer,
{'archive': 'tar'},
endpoint_suffix='__tar',
),
Rule(
[<|fim▁hole|> views.crud.github_download_starball,
json_renderer,
{'archive': 'zip'},
endpoint_suffix='__zip',
),
Rule(
[
'/project/<pid>/github/hook/',
'/project/<pid>/node/<nid>/github/hook/',
],
'post',
views.hooks.github_hook_callback,
json_renderer,
),
# OAuth: User
Rule(
'/settings/github/oauth/',
'get',
views.auth.github_oauth_start,
json_renderer,
endpoint_suffix='__user',
),
Rule(
'/settings/github/oauth/',
'delete',
views.auth.github_oauth_delete_user,
json_renderer,
),
# OAuth: Node
Rule(
[
'/project/<pid>/github/oauth/',
'/project/<pid>/node/<nid>/github/oauth/',
],
'get',
views.auth.github_oauth_start,
json_renderer,
),
Rule(
[
'/project/<pid>/github/user_auth/',
'/project/<pid>/node/<nid>/github/user_auth/',
],
'post',
views.auth.github_add_user_auth,
json_renderer,
),
Rule(
[
'/project/<pid>/github/oauth/',
'/project/<pid>/node/<nid>/github/oauth/',
'/project/<pid>/github/config/',
'/project/<pid>/node/<nid>/github/config/'
],
'delete',
views.auth.github_oauth_deauthorize_node,
json_renderer,
),
# OAuth: General
Rule(
[
'/addons/github/callback/<uid>/',
'/addons/github/callback/<uid>/<nid>/',
],
'get',
views.auth.github_oauth_callback,
json_renderer,
),
],
'prefix': '/api/v1',
}
api_routes = {
'rules': [
Rule(
'/github/repo/create/',
'post',
views.repos.github_create_repo,
json_renderer,
),
Rule(
[
'/project/<pid>/github/hgrid/root/',
'/project/<pid>/node/<nid>/github/hgrid/root/',
],
'get',
views.hgrid.github_root_folder_public,
json_renderer,
),
],
'prefix': '/api/v1'
}<|fim▁end|> | '/project/<pid>/github/zipball/',
'/project/<pid>/node/<nid>/github/zipball/',
],
'get', |
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for Streamlabs Water Monitor Usage."""
from datetime import timedelta
from homeassistant.components.streamlabswater import DOMAIN as STREAMLABSWATER_DOMAIN
from homeassistant.const import VOLUME_GALLONS
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
<|fim▁hole|>DEPENDENCIES = ["streamlabswater"]
WATER_ICON = "mdi:water"
MIN_TIME_BETWEEN_USAGE_UPDATES = timedelta(seconds=60)
NAME_DAILY_USAGE = "Daily Water"
NAME_MONTHLY_USAGE = "Monthly Water"
NAME_YEARLY_USAGE = "Yearly Water"
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up water usage sensors."""
client = hass.data[STREAMLABSWATER_DOMAIN]["client"]
location_id = hass.data[STREAMLABSWATER_DOMAIN]["location_id"]
location_name = hass.data[STREAMLABSWATER_DOMAIN]["location_name"]
streamlabs_usage_data = StreamlabsUsageData(location_id, client)
streamlabs_usage_data.update()
add_devices(
[
StreamLabsDailyUsage(location_name, streamlabs_usage_data),
StreamLabsMonthlyUsage(location_name, streamlabs_usage_data),
StreamLabsYearlyUsage(location_name, streamlabs_usage_data),
]
)
class StreamlabsUsageData:
"""Track and query usage data."""
def __init__(self, location_id, client):
"""Initialize the usage data."""
self._location_id = location_id
self._client = client
self._today = None
self._this_month = None
self._this_year = None
@Throttle(MIN_TIME_BETWEEN_USAGE_UPDATES)
def update(self):
"""Query and store usage data."""
water_usage = self._client.get_water_usage_summary(self._location_id)
self._today = round(water_usage["today"], 1)
self._this_month = round(water_usage["thisMonth"], 1)
self._this_year = round(water_usage["thisYear"], 1)
def get_daily_usage(self):
"""Return the day's usage."""
return self._today
def get_monthly_usage(self):
"""Return the month's usage."""
return self._this_month
def get_yearly_usage(self):
"""Return the year's usage."""
return self._this_year
class StreamLabsDailyUsage(Entity):
"""Monitors the daily water usage."""
def __init__(self, location_name, streamlabs_usage_data):
"""Initialize the daily water usage device."""
self._location_name = location_name
self._streamlabs_usage_data = streamlabs_usage_data
self._state = None
@property
def name(self):
"""Return the name for daily usage."""
return "{} {}".format(self._location_name, NAME_DAILY_USAGE)
@property
def icon(self):
"""Return the daily usage icon."""
return WATER_ICON
@property
def state(self):
"""Return the current daily usage."""
return self._streamlabs_usage_data.get_daily_usage()
@property
def unit_of_measurement(self):
"""Return gallons as the unit measurement for water."""
return VOLUME_GALLONS
def update(self):
"""Retrieve the latest daily usage."""
self._streamlabs_usage_data.update()
class StreamLabsMonthlyUsage(StreamLabsDailyUsage):
"""Monitors the monthly water usage."""
@property
def name(self):
"""Return the name for monthly usage."""
return "{} {}".format(self._location_name, NAME_MONTHLY_USAGE)
@property
def state(self):
"""Return the current monthly usage."""
return self._streamlabs_usage_data.get_monthly_usage()
class StreamLabsYearlyUsage(StreamLabsDailyUsage):
"""Monitors the yearly water usage."""
@property
def name(self):
"""Return the name for yearly usage."""
return "{} {}".format(self._location_name, NAME_YEARLY_USAGE)
@property
def state(self):
"""Return the current yearly usage."""
return self._streamlabs_usage_data.get_yearly_usage()<|fim▁end|> | |
<|file_name|>__main__.py<|end_file_name|><|fim▁begin|>if __name__ == "__main__":
try:
from mvc.ui.widgets import Application
except ImportError:
from mvc.ui.console import Application
from mvc.widgets import app<|fim▁hole|> app.widgetapp = Application()
initialize(app.widgetapp)<|fim▁end|> | from mvc.widgets import initialize |
<|file_name|>SectionNotification.spec.tsx<|end_file_name|><|fim▁begin|>import { mount } from 'enzyme';
import * as React from 'react';
import { isUniEnzymeTestkitExists } from 'wix-ui-test-utils/enzyme';
import { createUniDriverFactory } from 'wix-ui-test-utils/uni-driver-factory';
import { isUniTestkitExists } from 'wix-ui-test-utils/vanilla';
import { sectionNotificationTestkitFactory } from '../../testkit';
import { sectionNotificationTestkitFactory as enzymeSectionNotificationTestkitFactory } from '../../testkit/enzyme';
import { SectionNotification } from './';
import { sectionNotificationDriverFactory } from './SectionNotification.driver';
import { NOTIFICATION_TYPE } from './types';
const props = {
icon: <svg>ErrorIcon</svg>,
text: `You will be redirected to payment provider's page.`,
type: NOTIFICATION_TYPE.default,
buttonTitle: 'Proceed',
};
describe('SectionNotification', () => {
const createDriver = createUniDriverFactory(sectionNotificationDriverFactory);
it('should render', async () => {
const driver = createDriver(
<SectionNotification>
<SectionNotification.Text>{props.text}</SectionNotification.Text>
</SectionNotification>,
);
expect(await driver.exists()).toBe(true);
});
it('should render notification with content', async () => {
const driver = createDriver(
<SectionNotification>
<SectionNotification.Icon icon={props.icon} />
<SectionNotification.Text>{props.text}</SectionNotification.Text>
<SectionNotification.Button>
{props.buttonTitle}
</SectionNotification.Button>
</SectionNotification>,
);
expect(await driver.getText()).toEqual(props.text);
expect(await driver.hasButtons()).toBe(true);
expect(await driver.hasIcon()).toBe(true);
});
it('should render notification of type Error', async () => {
const driver = createDriver(
<SectionNotification type={NOTIFICATION_TYPE.error}>
<SectionNotification.Text>{props.text}</SectionNotification.Text>
</SectionNotification>,
);
expect(await driver.isError()).toBe(true);
});
it('should render notification of type Alert', async () => {
const driver = createDriver(
<SectionNotification type={NOTIFICATION_TYPE.alert}>
<SectionNotification.Text>{props.text}</SectionNotification.Text>
</SectionNotification>,
);
expect(await driver.isAlert()).toBe(true);
});
it('should render notification of type Wired', async () => {
const driver = createDriver(
<SectionNotification type={NOTIFICATION_TYPE.wired}>
<SectionNotification.Text>{props.text}</SectionNotification.Text>
</SectionNotification>,
);
expect(await driver.isWired()).toBe(true);
});
<|fim▁hole|> it('should exist', async () => {
expect(
await isUniTestkitExists(
<SectionNotification>
<SectionNotification.Text>{props.text}</SectionNotification.Text>
</SectionNotification>,
sectionNotificationTestkitFactory,
{
dataHookPropName: 'data-hook',
},
),
).toBe(true);
});
});
describe('enzyme testkit', () => {
it('should exist', async () => {
expect(
await isUniEnzymeTestkitExists(
<SectionNotification>
<SectionNotification.Text>{props.text}</SectionNotification.Text>
</SectionNotification>,
enzymeSectionNotificationTestkitFactory,
mount,
{
dataHookPropName: 'data-hook',
},
),
).toBe(true);
});
});
});<|fim▁end|> | describe('testkit', () => { |
<|file_name|>face.js<|end_file_name|><|fim▁begin|>'use strict';<|fim▁hole|>
var conf = require('../config');
var ctrlBuilder = require('../controllers/face-controller');
var version = conf.get('version');
var base_route = conf.get('baseurlpath');
var face_route = base_route + '/face';
module.exports = function (server, models, redis) {
var controller = ctrlBuilder(server, models, redis);
server.get({path: face_route, version: version}, controller.randomFace);
server.head({path: face_route, version: version}, controller.randomFace);
};<|fim▁end|> | |
<|file_name|>observable.ts<|end_file_name|><|fim▁begin|>//Copyright (c) wildcatsoft.
//All Rights Reserved.
//Licensed under the Apache License, Version 2.0.
//See License.txt in the project root for license information.
/// <reference path="../typings/winjs/winjs.d.ts" />
module WinJS.KO {
export var observable = function (data): any {
var _data = typeof data == "object" ? data : new PrimitiveTypeWrapper(data);
if (_data) {
var _observable = WinJS.Binding.as(_data);
createObservable(_observable);
return _observable;
}
return _data;
}
export var computed = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget?, options?, destObj?: any, destProp?: string) {
var readFunction = evaluatorFunctionOrOptions;
if (evaluatorFunctionOrOptions && typeof evaluatorFunctionOrOptions == "object") {
options = evaluatorFunctionOrOptions || {};
readFunction = options["read"];
} else {
options = options || {};
if (!readFunction)
readFunction = options["read"];
}
if (typeof readFunction != "function")
throw new Error("Pass a function that returns the value of the computed function.");
var _computed;
var _propName: string;
if (destObj) {
_computed = destObj;
_propName = destProp;
}
else {
_computed = observable(0);
_propName = "value";
}
evaluatorFunctionTarget = evaluatorFunctionTarget || options["owner"] || _computed;
var evaluator = () => {
return readFunction.call(evaluatorFunctionTarget);
}
var _initVal;
if (_computed.dispose) {
_computed.dispose(_propName);
}
var computedProperty: ComputedProperty = new ComputedProperty;
_computed._computedProperties[_propName] = computedProperty;
var computedUpdater = function () {
var context = DependencyDetection.currentContext();
if (context && context.type == DependencyDetectionContext.TYPE_COMPUTED_DEPENDENCY_BIND) {
return; //triggered by the bind methods in intial evaluation. do nothing
}
computedProperty._removeAllDependencies();
var value;
DependencyDetection.execute(new DependencyDetectionContext(DependencyDetectionContext.TYPE_COMPUTED_EVALUATIOR, new ObservableProperty(_computed, _propName)), function () {
value = evaluator();
});
var dependencies = <ObservableProperty[]>(computedProperty._dependencies || []);
DependencyDetection.execute(new DependencyDetectionContext(DependencyDetectionContext.TYPE_COMPUTED_DEPENDENCY_BIND), function () {
dependencies.forEach(function (d) {
d._observable.bind(d._propertyName, computedUpdater);
});
});
var updateStamp = new UpdateStamp(new Date(0));
dependencies.forEach(function (d) {
var lastUpdateStamp = d._observable._lastUpdatedStamp(d._propertyName);
if (lastUpdateStamp && updateStamp.lessThan(lastUpdateStamp)) {
updateStamp = lastUpdateStamp;
}
});
if (_computed._lastUpdatedStamp) {
var lastUpdatedStamp = <UpdateStamp>_computed._lastUpdatedStamp(_propName);
if (!lastUpdatedStamp || lastUpdatedStamp.lessThan(updateStamp)) {
_computed.updateProperty(_propName, value, updateStamp);
}
} else {
_computed[_propName] = value;
}
return value;
}
var writer = options["write"];
if (writer && typeof writer == "function") {
computedProperty._computedWriter = function (value) {
writer.call(evaluatorFunctionTarget, value);
};
}
computedProperty._computedUpdater = computedUpdater;
if (typeof _computed._lastUpdatedStamp == "function") {
_computed._lastUpdatedStamp(_propName, null);
}
var initValue = computedUpdater();
if (_computed == destObj) {
return _initVal;
}
else {
return _computed;
}
}
export function observableArray(list?): IObservableArray<any> {
var list = list || [];
var winJSList = <any>new WinJS.Binding.List(list);
var lastUpdatedStamp: UpdateStamp;
function onListChanged() {
lastUpdatedStamp = new UpdateStamp();
var oldArray = winJSList._array;
winJSList._array = getRawArray(winJSList);
winJSList.notify("_array", winJSList._array, oldArray);
}
winJSList.addEventListener("itemchanged", onListChanged);
winJSList.addEventListener("iteminserted", onListChanged);
winJSList.addEventListener("itemmoved", onListChanged);
winJSList.addEventListener("itemmutated", onListChanged);
winJSList.addEventListener("itemremoved", onListChanged);
winJSList.addEventListener("reload", onListChanged);
winJSList._lastUpdatedStamp = function () {
return lastUpdatedStamp;
};
winJSList._array = getRawArray(winJSList);
Object.defineProperty(winJSList, "array", {
get: function () {
var context = DependencyDetection.currentContext();
if (context) {
_bindComputedUpdaterIfNeccessary(<any>winJSList, "_array");
}
return winJSList._array;
},
enumerable: true,
configurable: true
});
return <IObservableArray<any>>winJSList;
}
export function isObservableArray(obj): boolean {
return obj instanceof WinJS.Binding.List && obj._array instanceof Array;
}
export function getRawArray<T>(list: WinJS.Binding.List<T>): T[] {
if (list instanceof WinJS.Binding.List) {
return list.map(function (v) {return v });
}
}
export interface IObservableArray<T> extends WinJS.Binding.List<T> {
array: T[];
}
function createObservable(winjsObservable) {
winjsObservable.addComputedProperty = function (name: string, evaluatorFunctionOrOptions, evaluatorFunctionTarget?, options?, destObj?: any, destProp?: string) {
this.addProperty(name);
computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget, options, this, name);
}
var _getProperty: Function = winjsObservable.getProperty;
winjsObservable.getProperty = function (name: string): any {
_bindComputedUpdaterIfNeccessary(this, name);
return _getProperty.call(this, name);
}
var _updateProperty: Function = winjsObservable.updateProperty;
winjsObservable.updateProperty = function (name: string, value: any, updateStamp?: UpdateStamp) {
this._lastUpdatedStamp(name, updateStamp || UpdateStamp.newStamp());
_updateProperty.call(this, name, value);
}
var _setProperty: Function = winjsObservable.setProperty;
winjsObservable.setProperty = function (name: string, value: any) {
var computedProperty: ComputedProperty = this._computedProperty(name);
if (computedProperty) {
if (computedProperty._computedWriter) {
computedProperty._computedWriter(value);
return;
}
else {
throw new Error("Cannot write a value to a computed observable property unless you specify a 'write' option.");
}
}
return _setProperty.call(this, name, value);
}
winjsObservable._removeAllDependencies = function (name: string) {
var property = this._computedProperty(name);
if (property) {
var dependencies: ObservableProperty[] = property._dependencies || [];
dependencies.forEach(function (d) {
d._observable.unbind(d._propertyName, property._computedUpdater);
});
property._dependencies = [];
}
}
var _dispose: Function = winjsObservable.dispose;
winjsObservable.dispose = function (name?: string) {
if (arguments.length > 0) {
var property = this._computedProperty(name);
if (property) {
property._removeAllDependencies();
property._computedUpdater = null;
property._computedWriter = null
delete this._computedProperties[name];
}
}
else {
if (_dispose) {
_dispose.call(this);
}
Object.keys(this).forEach((k) => {
this.dispose(k);
});
}
}
//_winjsObservable: any;
winjsObservable._lastUpdatedStamps = {};
winjsObservable._lastUpdatedStamp = function (name?: string, updateStamp?: UpdateStamp): UpdateStamp {
this._lastUpdatedStamps = this._lastUpdatedStamps || {};
if (arguments.length == 1) {
return this._lastUpdatedStamps[name];
}
else if (arguments.length > 1) {
this._lastUpdatedStamps[name] = updateStamp;
}
}
winjsObservable._computedProperties = {};
winjsObservable._computedProperty = function (name: string): ComputedProperty {
return this._computedProperties[name];
}
winjsObservable.peek = function (name: string) {
return _getProperty.call(this, name);
}
winjsObservable.computed = function (name: string, evaluatorFunctionOrOptions, evaluatorFunctionTarget?, options?) {
computed(evaluatorFunctionOrOptions, evaluatorFunctionTarget, options, this, name);<|fim▁hole|> winjsObservable.getDependenciesCount = function (name: string) {
var computedProperty: ComputedProperty = this._computedProperty(name);
return computedProperty && computedProperty._dependencies ? computedProperty._dependencies.length : 0;
}
}
function _bindComputedUpdaterIfNeccessary(observable: IObservable, name: string) {
var context = DependencyDetection.currentContext();
if (context) {
if (context.type == DependencyDetectionContext.TYPE_COMPUTED_EVALUATIOR) { //initial computed evaluator
var observableProperty = context.observableProperty;
if (!observableProperty || (observableProperty._observable === observable && observableProperty._propertyName == name)) {
return;
}
var computed: ComputedProperty = observableProperty._observable._computedProperty(observableProperty._propertyName);
var property = new ObservableProperty(observable, name);
var dependencies = <any[]>(computed._dependencies || []);
if (!dependencies.some(function (o) {
return o === property;
})) {
dependencies.push(property);
};
computed._dependencies = dependencies;
}
}
}
interface IObservable {
bind(name: string, action: Function);
unbind(name: string, action: Function);
_lastUpdatedStamp(name: string): UpdateStamp;
_computedProperty(name: string): ComputedProperty;
}
class ObservableProperty {
constructor(observable: IObservable, propertyName: string) {
this._observable = observable;
this._propertyName = propertyName;
}
_observable: IObservable;
_propertyName: string;
}
class ComputedProperty {
_dependencies: ObservableProperty[] = [];
_computedUpdater: Function;
_computedWriter: Function;
_removeAllDependencies() {
var computedUpdater = this._computedUpdater;
this._dependencies.forEach(function (d) {
d._observable.unbind(d._propertyName, computedUpdater);
});
this._dependencies = [];
}
}
class DependencyDetectionContext {
constructor(type: number, observablePropertyOrUpdateStamp?) {
this.type = type;
if (type == DependencyDetectionContext.TYPE_COMPUTED_EVALUATIOR) {
this.observableProperty = observablePropertyOrUpdateStamp;
}
else {
this.upateStamp = observablePropertyOrUpdateStamp;
}
}
static TYPE_COMPUTED_EVALUATIOR = 0;
static TYPE_COMPUTED_DEPENDENCY_BIND = 1;
static TYPE_WRITER_INITIAL_RUN = 2;
static COMPUTED_WRITER = 3;
type: number; //0: initial evalutor, 1: computed updater, 2: writer intial run, 3: computed writer
observableProperty: ObservableProperty; //only needed for type 0
upateStamp: UpdateStamp; //only need for type 1, 2, 3
}
class DependencyDetection {
private static _currentContext: DependencyDetectionContext;
private static contextStack = [];
static execute(context: DependencyDetectionContext, callback: Function) {
try {
var existingContext = DependencyDetection._currentContext;
DependencyDetection._currentContext = context;
callback();
}
finally {
DependencyDetection._currentContext = existingContext;
}
}
static currentContext(): DependencyDetectionContext {
return DependencyDetection._currentContext;
}
}
class UpdateStamp {
constructor(timeStamp?: Date, index?: number) {
this.timeStamp = timeStamp || new Date();
this.index = index || 0;
}
timeStamp: Date;
index: number;
lessThan(updateStamp: UpdateStamp): boolean {
return this.timeStamp < updateStamp.timeStamp || (this.timeStamp < updateStamp.timeStamp && this.index < updateStamp.index);
}
static newStamp(): UpdateStamp {
var stamp = new UpdateStamp;
if (stamp.timeStamp == UpdateStamp._lastUpdateStamp.timeStamp) {
stamp.index == UpdateStamp._lastUpdateStamp.index + 1;
}
UpdateStamp._lastUpdateStamp = new UpdateStamp(stamp.timeStamp, stamp.index);
return stamp;
}
private static _lastUpdateStamp: UpdateStamp = new UpdateStamp;
}
class PrimitiveTypeWrapper {
value: any;
constructor(value) {
this.value = value;
}
}
}<|fim▁end|> | }
|
<|file_name|>SetReceiptRulePositionResult.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.simpleemail.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* An empty element returned on a successful request.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/SetReceiptRulePosition" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SetReceiptRulePositionResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof SetReceiptRulePositionResult == false)
return false;
SetReceiptRulePositionResult other = (SetReceiptRulePositionResult) obj;
return true;<|fim▁hole|> final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public SetReceiptRulePositionResult clone() {
try {
return (SetReceiptRulePositionResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}<|fim▁end|> | }
@Override
public int hashCode() { |
<|file_name|>atsc_rx_filter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env /usr/bin/python
#
# Copyright 2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
from gnuradio import gr, filter
from . import dtv_python as dtv
# FIXME move these into separate constants module
ATSC_CHANNEL_BW = 6.0e6
ATSC_SYMBOL_RATE = 4.5e6/286*684 # ~10.76 Mbaud
ATSC_RRC_SYMS = 8 # filter kernel extends over 2N+1 symbols
class atsc_rx_filter(gr.hier_block2):
def __init__(self, input_rate, sps):
gr.hier_block2.__init__(self, "atsc_rx_filter",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature
# Create matched RX filter with RRC response for fractional
# interpolator.
nfilts = 16
output_rate = ATSC_SYMBOL_RATE*sps # Desired oversampled sample rate
filter_rate = input_rate*nfilts
symbol_rate = ATSC_SYMBOL_RATE / 2.0 # One-sided bandwidth of sideband
excess_bw = 0.1152 #1.0-(0.5*ATSC_SYMBOL_RATE/ATSC_CHANNEL_BW) # ~10.3%
ntaps = int((2*ATSC_RRC_SYMS+1)*sps*nfilts)
interp = output_rate / input_rate
gain = nfilts*symbol_rate/filter_rate
rrc_taps = filter.firdes.root_raised_cosine(gain, # Filter gain
filter_rate, # PFB filter prototype rate
symbol_rate, # ATSC symbol rate
excess_bw, # ATSC RRC excess bandwidth
ntaps) # Length of filter<|fim▁hole|> # Connect pipeline
self.connect(self, pfb, self)<|fim▁end|> |
pfb = filter.pfb_arb_resampler_ccf(interp, rrc_taps, nfilts)
|
<|file_name|>[email protected]<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="ca@valencia" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Quantum</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>Quantum</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The Quantum developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Doble click per editar la direccio o la etiqueta</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Crear nova direccio</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copieu l'adreça seleccionada al porta-retalls del sistema</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-46"/>
<source>These are your Quantum 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 line="+60"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</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 Quantum 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="-14"/>
<source>Verify a message to ensure it was signed with a specified Quantum 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>Eliminar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation 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="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-58"/>
<source>Quantum will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation type="unfinished"/>
</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="+282"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show information about Quantum</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Send coins to a Quantum address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for Quantum</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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="+10"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-202"/>
<source>Quantum</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+180"/>
<source>&About Quantum</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>Quantum client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to Quantum network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About Quantum card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Quantum card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid Quantum address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<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 numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. Quantum can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation 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 type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Quantum address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation type="unfinished"/>
</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="+420"/>
<location line="+12"/>
<source>Quantum-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation type="unfinished"/>
</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. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start Quantum after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Quantum on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Quantum 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 Quantum 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 Quantum.</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 Quantum 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="+7"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Quantum.</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="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Quantum network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source><|fim▁hole|> <message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation 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="+348"/>
<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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Quantum-Qt help message to get a list with possible Quantum 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>Quantum - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Quantum 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 Quantum debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the Quantum RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 QTM</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</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="+28"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>123.456 QTM</source>
<translation type="unfinished"/>
</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="-173"/>
<source>Enter a Quantum address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation 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>
<message>
<location line="+251"/>
<source>WARNING: Invalid Quantum address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Quantum address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</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"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Quantum address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Quantum address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Quantum address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</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 Quantum 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>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 110 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation type="unfinished"/>
</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="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</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="+226"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+190"/>
<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 type="unfinished"/>
</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="+55"/>
<location line="+16"/>
<source>All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</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="+206"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>Quantum version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or quantumd</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: quantum.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: quantumd.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Quantum will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=quantumrpc
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 "Quantum Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. Quantum is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>Quantum</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of Quantum</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart Quantum to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. Quantum is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS><|fim▁end|> | <translation type="unfinished"/>
</message> |
<|file_name|>test.rs<|end_file_name|><|fim▁begin|>use intern::intern;
use grammar::repr::*;
use test_util::{normalized_grammar};
use super::lalr_states;
use super::super::interpret::interpret;
fn nt(t: &str) -> NonterminalString {
NonterminalString(intern(t))
}
macro_rules! tokens {
($($x:expr),*) => {
vec![$(TerminalString::Quoted(intern($x))),*].into_iter()
}
}
#[test]
fn figure9_23() {
let grammar = normalized_grammar(r#"
grammar;
extern { enum Tok { } }
S: () = E => ();
E: () = {
E "-" T => ();
T => ();
};
T: () = {
"N" => ();
"(" E ")" => ();<|fim▁hole|> let states = lalr_states(&grammar, nt("S")).unwrap();
println!("{:#?}", states);
let tree = interpret(&states, tokens!["N", "-", "(", "N", "-", "N", ")"]).unwrap();
assert_eq!(
&format!("{:?}", tree)[..],
r#"[S: [E: [E: [T: "N"]], "-", [T: "(", [E: [E: [T: "N"]], "-", [T: "N"]], ")"]]]"#);
}<|fim▁end|> | };
"#);
|
<|file_name|>simple.rs<|end_file_name|><|fim▁begin|>use std::collections::HashMap;
use unshare::{Command, Fd};
use crate::config::command::{CommandInfo, WriteMode};
use crate::launcher::{Context, socket};
use crate::launcher::options::{ArgError, parse_docopts};
use crate::launcher::volumes::prepare_volumes;
use crate::process_util::{run_and_wait, convert_status};
use super::build::{build_container};
use super::network;
use super::wrap::Wrapper;
const DEFAULT_DOCOPT: &'static str = "\
Common options:
-h, --help This help
";
pub type Version = String;
pub struct Args {
cmdname: String,
args: Vec<String>,
environ: HashMap<String, String>,
}
pub fn parse_args(cinfo: &CommandInfo, _context: &Context,
cmd: String, args: Vec<String>)
-> Result<Args, ArgError>
{
if let Some(_) = cinfo.network {
return Err(ArgError::Error(format!(
"Network is not supported for !Command use !Supervise")));
}
if let Some(ref opttext) = cinfo.options {
let (env, _) = parse_docopts(&cinfo.description, opttext,
DEFAULT_DOCOPT,
&cmd, args)?;
Ok(Args {
cmdname: cmd,
environ: env,
args: Vec::new(),
})
} else {
Ok(Args {
cmdname: cmd,
environ: HashMap::new(),
args: args,
})
}
}
pub fn prepare_containers(cinfo: &CommandInfo, _: &Args, context: &Context)
-> Result<Version, String>
{
let ver = build_container(context, &cinfo.container,
context.build_mode, false)?;
let cont = context.config.containers.get(&cinfo.container)
.ok_or_else(|| format!("Container {:?} not found", cinfo.container))?;
prepare_volumes(cont.volumes.values(), context)?;
prepare_volumes(cinfo.volumes.values(), context)?;
return Ok(ver);
}
pub fn run(cinfo: &CommandInfo, args: Args, version: Version,
context: &Context)
-> Result<i32, String>
{
if cinfo.isolate_network || context.isolate_network {
try_msg!(network::isolate_network(),
"Cannot setup isolated network: {err}");
}
let mut cmd: Command = Wrapper::new(Some(&version), &context.settings);
cmd.workdir(&context.workdir);
for (k, v) in &args.environ {
cmd.env(k, v);
}
cmd.arg(&args.cmdname);
cmd.args(&args.args);
if let Some(ref sock_str) = cinfo.pass_tcp_socket {
let sock = socket::parse_and_bind(sock_str)
.map_err(|e| format!("Error listening {:?}: {}", sock_str, e))?;
cmd.file_descriptor(3, Fd::from_file(sock));
}
if cinfo.network.is_none() { // TODO(tailhook) is it still a thing?
cmd.map_users_for(
&context.config.get_container(&cinfo.container).unwrap(),
&context.settings)?;
cmd.gid(0);
cmd.groups(Vec::new());
}
let res = run_and_wait(&mut cmd).map(convert_status);
if cinfo.write_mode != WriteMode::read_only {
let mut cmd: Command = Wrapper::new(None, &context.settings);
cmd.workdir(&context.workdir);
cmd.max_uidmap();
cmd.gid(0);
cmd.groups(Vec::new());
cmd.arg("_clean").arg("--transient");
match cmd.status() {
Ok(s) if s.success() => {}
Ok(s) => warn!("The `vagga _clean --transient` {}", s),
Err(e) => warn!("Failed to run `vagga _clean --transient`: {}", e),
}
}
if res == Ok(0) {
if let Some(ref epilog) = cinfo.epilog {
print!("{}", epilog);<|fim▁hole|> }
return res;
}<|fim▁end|> | } |
<|file_name|>signals.py<|end_file_name|><|fim▁begin|>from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Board, BoardPermissions, User, UserSettings
<|fim▁hole|>def init_board_permissions(sender, **kwargs):
"""Link existing benchmark countries to newly created countries."""
instance = kwargs["instance"]
if kwargs["created"]:
BoardPermissions.objects.create(board=instance)
@receiver(post_save, sender=User)
def init_user_settings(sender, **kwargs):
"""Link existing benchmark countries to newly created countries."""
instance = kwargs["instance"]
if kwargs["created"]:
UserSettings.objects.create(user=instance)<|fim▁end|> |
@receiver(post_save, sender=Board) |
<|file_name|>dialogs.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*-
#--------------------------------------------------------------------------
# Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas
# Copyright: (C) 2001 Centro de Pesquisas Renato Archer
# Homepage: http://www.softwarepublico.gov.br
# Contact: [email protected]
# License: GNU - GPL 2 (LICENSE.txt/LICENCA.txt)
#--------------------------------------------------------------------------
# Este programa e software livre; voce pode redistribui-lo e/ou
# modifica-lo sob os termos da Licenca Publica Geral GNU, conforme
# publicada pela Free Software Foundation; de acordo com a versao 2
# da Licenca.
#
# Este programa eh distribuido na expectativa de ser util, mas SEM
# QUALQUER GARANTIA; sem mesmo a garantia implicita de
# COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM
# PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais
# detalhes.
#--------------------------------------------------------------------------
import itertools
import os
import random
import sys
import time
from functools import partial
from concurrent import futures
if sys.platform == 'win32':
try:
import win32api
_has_win32api = True
except ImportError:
_has_win32api = False
else:
_has_win32api = False
import vtk
import wx
try:
from wx.adv import BitmapComboBox
except ImportError:
from wx.combo import BitmapComboBox
from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor
from wx.lib import masked
from wx.lib.agw import floatspin
import wx.lib.filebrowsebutton as filebrowse
from wx.lib.wordwrap import wordwrap
from invesalius.pubsub import pub as Publisher
import csv
try:
from wx.adv import AboutDialogInfo, AboutBox
except ImportError:
from wx import AboutDialogInfo, AboutBox
import invesalius.constants as const
import invesalius.data.coordinates as dco
import invesalius.data.transformations as tr
import invesalius.gui.widgets.gradient as grad
import invesalius.session as ses
import invesalius.utils as utils
import invesalius.data.vtk_utils as vtku
import invesalius.data.coregistration as dcr
from invesalius.gui.widgets.inv_spinctrl import InvSpinCtrl, InvFloatSpinCtrl
from invesalius.gui.widgets import clut_imagedata
from invesalius.gui.widgets.clut_imagedata import CLUTImageDataWidget, EVT_CLUT_NODE_CHANGED
import numpy as np
from numpy.core.umath_tests import inner1d
from invesalius import inv_paths
try:
from agw import floatspin as FS
except ImportError: # if it's not there locally, try the wxPython lib.
import wx.lib.agw.floatspin as FS
class MaskEvent(wx.PyCommandEvent):
def __init__(self , evtType, id, mask_index):
wx.PyCommandEvent.__init__(self, evtType, id,)
self.mask_index = mask_index
myEVT_MASK_SET = wx.NewEventType()
EVT_MASK_SET = wx.PyEventBinder(myEVT_MASK_SET, 1)
class NumberDialog(wx.Dialog):
def __init__(self, message, value=0):
wx.Dialog.__init__(self, None, -1, "InVesalius 3", size=wx.DefaultSize,
pos=wx.DefaultPosition,
style=wx.DEFAULT_DIALOG_STYLE)
# Static text which contains message to user
label = wx.StaticText(self, -1, message)
# Numeric value to be changed by user
num_ctrl = masked.NumCtrl(self, value=value, integerWidth=3,
fractionWidth=2,
allowNegative=True,
signedForegroundColour = "Black")
self.num_ctrl = num_ctrl
# Buttons
btn_ok = wx.Button(self, wx.ID_OK)
btn_ok.SetHelpText(_("Value will be applied."))
btn_ok.SetDefault()
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btn_cancel.SetHelpText(_("Value will not be applied."))
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.AddButton(btn_cancel)
btnsizer.Realize()
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
sizer.Add(num_ctrl, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
sizer.Add(btnsizer, 0, wx.ALL, 5)
self.SetSizer(sizer)
sizer.Fit(self)
self.Centre()
def SetValue(self, value):
self.num_ctrl.SetValue(value)
def GetValue(self):
return self.num_ctrl.GetValue()
class ResizeImageDialog(wx.Dialog):
def __init__(self):#, message, value=0):
wx.Dialog.__init__(self, None, -1, "InVesalius 3", size=wx.DefaultSize,
pos=wx.DefaultPosition,
style=wx.DEFAULT_DIALOG_STYLE)
lbl_message = wx.StaticText(self, -1, _("InVesalius is running on a 32-bit operating system or has insufficient memory. \nIf you want to work with 3D surfaces or volume rendering, \nit is recommended to reduce the medical images resolution."))
icon = wx.ArtProvider.GetBitmap(wx.ART_WARNING, wx.ART_MESSAGE_BOX, (32,32))
bmp = wx.StaticBitmap(self, -1, icon)
btn_ok = wx.Button(self, wx.ID_OK)
btn_ok.SetDefault()
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btn_sizer = wx.StdDialogButtonSizer()
btn_sizer.AddButton(btn_ok)
btn_sizer.AddButton(btn_cancel)
btn_sizer.Realize()
lbl_message_percent = wx.StaticText(self, -1,_("Percentage of original resolution"))
num_ctrl_percent = InvSpinCtrl(self, -1, value=100, min_value=20, max_value=100)
self.num_ctrl_porcent = num_ctrl_percent
sizer_percent = wx.BoxSizer(wx.HORIZONTAL)
sizer_percent.Add(lbl_message_percent, 0, wx.EXPAND|wx.ALL, 5)
sizer_percent.Add(num_ctrl_percent, 0, wx.ALL, 5)
sizer_itens = wx.BoxSizer(wx.VERTICAL)
sizer_itens.Add(lbl_message, 0, wx.EXPAND|wx.ALL, 5)
sizer_itens.Add(sizer_percent, 0, wx.EXPAND|wx.ALL, 5)
sizer_itens.Add(btn_sizer, 0, wx.EXPAND|wx.ALL, 5)
sizer_general = wx.BoxSizer(wx.HORIZONTAL)
sizer_general.Add(bmp, 0, wx.ALIGN_CENTRE|wx.ALL, 10)
sizer_general.Add(sizer_itens, 0, wx.ALL , 5)
#self.SetAutoLayout(True)
self.SetSizer(sizer_general)
sizer_general.Fit(self)
self.Layout()
self.Centre()
def SetValue(self, value):
self.num_ctrl_porcent.SetValue(value)
def GetValue(self):
return self.num_ctrl_porcent.GetValue()
def Close(self):
self.Destroy()
def ShowNumberDialog(message, value=0):
dlg = NumberDialog(message, value)
dlg.SetValue(value)
if dlg.ShowModal() == wx.ID_OK:
return dlg.GetValue()
dlg.Destroy()
return 0
class ProgressDialog(object):
def __init__(self, parent, maximum, abort=False):
self.title = "InVesalius 3"
self.msg = _("Loading DICOM files")
self.maximum = maximum
self.current = 0
self.style = wx.PD_APP_MODAL
if abort:
self.style = wx.PD_APP_MODAL | wx.PD_CAN_ABORT
self.dlg = wx.ProgressDialog(self.title,
self.msg,
maximum = self.maximum,
parent = parent,
style = self.style)
self.dlg.Bind(wx.EVT_BUTTON, self.Cancel)
self.dlg.SetSize(wx.Size(250,150))
def Cancel(self, evt):
Publisher.sendMessage("Cancel DICOM load")
def Update(self, value, message):
if(int(value) != self.maximum):
try:
return self.dlg.Update(value,message)
#TODO:
#Exception in the Windows XP 64 Bits with wxPython 2.8.10
except(wx._core.PyAssertionError):
return True
else:
return False
def Close(self):
self.dlg.Destroy()
# ---------
INV_NON_COMPRESSED = 0
INV_COMPRESSED = 1
WILDCARD_INV_SAVE = _("InVesalius project (*.inv3)|*.inv3") + "|" + \
_("InVesalius project compressed (*.inv3)|*.inv3")
WILDCARD_OPEN = "InVesalius 3 project (*.inv3)|*.inv3|" \
"All files (*.*)|*.*"
WILDCARD_ANALYZE = "Analyze 7.5 (*.hdr)|*.hdr|" \
"All files (*.*)|*.*"
WILDCARD_NIFTI = "NIfTI 1 (*.nii;*.nii.gz;*.hdr)|*.nii;*.nii.gz;*.hdr|" \
"All files (*.*)|*.*"
#".[jJ][pP][gG]"
WILDCARD_PARREC = "PAR/REC (*.par)|*.par|" \
"All files (*.*)|*.*"
WILDCARD_MESH_FILES = "STL File format (*.stl)|*.stl|" \
"Standard Polygon File Format (*.ply)|*.ply|" \
"Alias Wavefront Object (*.obj)|*.obj|" \
"VTK Polydata File Format (*.vtp)|*.vtp|" \
"All files (*.*)|*.*"
def ShowOpenProjectDialog():
# Default system path
current_dir = os.path.abspath(".")
session = ses.Session()
last_directory = session.get('paths', 'last_directory_inv3', '')
dlg = wx.FileDialog(None, message=_("Open InVesalius 3 project..."),
defaultDir=last_directory,
defaultFile="", wildcard=WILDCARD_OPEN,
style=wx.FD_OPEN|wx.FD_CHANGE_DIR)
# inv3 filter is default
dlg.SetFilterIndex(0)
# Show the dialog and retrieve the user response. If it is the OK response,
# process the data.
filepath = None
try:
if dlg.ShowModal() == wx.ID_OK:
# This returns a Python list of files that were selected.
filepath = dlg.GetPath()
except(wx._core.PyAssertionError): # FIX: win64
filepath = dlg.GetPath()
if filepath:
session['paths']['last_directory_inv3'] = os.path.split(filepath)[0]
session.WriteSessionFile()
# Destroy the dialog. Don't do this until you are done with it!
# BAD things can happen otherwise!
dlg.Destroy()
os.chdir(current_dir)
return filepath
def ShowImportDirDialog(self):
current_dir = os.path.abspath(".")
if sys.platform == 'win32' or sys.platform.startswith('linux'):
session = ses.Session()
if (session.GetLastDicomFolder()):
folder = session.GetLastDicomFolder()
else:
folder = ''
else:
folder = ''
dlg = wx.DirDialog(self, _("Choose a DICOM folder:"), folder,
style=wx.DD_DEFAULT_STYLE
| wx.DD_DIR_MUST_EXIST
| wx.DD_CHANGE_DIR)
path = None
try:
if dlg.ShowModal() == wx.ID_OK:
# GetPath returns in unicode, if a path has non-ascii characters a
# UnicodeEncodeError is raised. To avoid this, path is encoded in utf-8
if sys.platform == "win32":
path = dlg.GetPath()
else:
path = dlg.GetPath().encode('utf-8')
except(wx._core.PyAssertionError): #TODO: error win64
if (dlg.GetPath()):
path = dlg.GetPath()
if (sys.platform != 'darwin'):
if (path):
session.SetLastDicomFolder(path)
# Only destroy a dialog after you're done with it.
dlg.Destroy()
os.chdir(current_dir)
return path
def ShowImportBitmapDirDialog(self):
current_dir = os.path.abspath(".")
# if sys.platform == 'win32' or sys.platform.startswith('linux'):
# session = ses.Session()
# if (session.GetLastDicomFolder()):
# folder = session.GetLastDicomFolder()
# else:
# folder = ''
# else:
# folder = ''
session = ses.Session()
last_directory = session.get('paths', 'last_directory_bitmap', '')
dlg = wx.DirDialog(self, _("Choose a folder with TIFF, BMP, JPG or PNG:"), last_directory,
style=wx.DD_DEFAULT_STYLE
| wx.DD_DIR_MUST_EXIST
| wx.DD_CHANGE_DIR)
path = None
try:
if dlg.ShowModal() == wx.ID_OK:
# GetPath returns in unicode, if a path has non-ascii characters a
# UnicodeEncodeError is raised. To avoid this, path is encoded in utf-8
path = dlg.GetPath()
except(wx._core.PyAssertionError): #TODO: error win64
if (dlg.GetPath()):
path = dlg.GetPath()
# if (sys.platform != 'darwin'):
# if (path):
# session.SetLastDicomFolder(path)
if path:
session['paths']['last_directory_bitmap'] = path
session.WriteSessionFile()
# Only destroy a dialog after you're done with it.
dlg.Destroy()
os.chdir(current_dir)
return path
def ShowImportOtherFilesDialog(id_type, msg='Import NIFTi 1 file'):
# Default system path
session = ses.Session()
last_directory = session.get('paths', 'last_directory_%d' % id_type, '')
dlg = wx.FileDialog(None, message=msg, defaultDir=last_directory,
defaultFile="", wildcard=WILDCARD_NIFTI,
style=wx.FD_OPEN | wx.FD_CHANGE_DIR)
# if id_type == const.ID_NIFTI_IMPORT:
# dlg.SetMessage(_("Import NIFTi 1 file"))
# dlg.SetWildcard(WILDCARD_NIFTI)
# elif id_type == const.ID_TREKKER_MASK:
# dlg.SetMessage(_("Import Trekker mask"))
# dlg.SetWildcard(WILDCARD_NIFTI)
# elif id_type == const.ID_TREKKER_IMG:
# dlg.SetMessage(_("Import Trekker anatomical image"))
# dlg.SetWildcard(WILDCARD_NIFTI)
# elif id_type == const.ID_TREKKER_FOD:
# dlg.SetMessage(_("Import Trekker FOD"))
# dlg.SetWildcard(WILDCARD_NIFTI)
# elif id_type == const.ID_TREKKER_ACT:
# dlg.SetMessage(_("Import acantomical labels"))
# dlg.SetWildcard(WILDCARD_NIFTI)
if id_type == const.ID_PARREC_IMPORT:
dlg.SetMessage(_("Import PAR/REC file"))
dlg.SetWildcard(WILDCARD_PARREC)
elif id_type == const.ID_ANALYZE_IMPORT:
dlg.SetMessage(_("Import Analyze 7.5 file"))
dlg.SetWildcard(WILDCARD_ANALYZE)
# inv3 filter is default
dlg.SetFilterIndex(0)
# Show the dialog and retrieve the user response. If it is the OK response,
# process the data.
filename = None
try:
if dlg.ShowModal() == wx.ID_OK:
# GetPath returns in unicode, if a path has non-ascii characters a
# UnicodeEncodeError is raised. To avoid this, path is encoded in utf-8
if sys.platform == "win32":
filename = dlg.GetPath()
else:
filename = dlg.GetPath().encode('utf-8')
except(wx._core.PyAssertionError): # TODO: error win64
if (dlg.GetPath()):
filename = dlg.GetPath()
if filename:
session['paths']['last_directory_%d' % id_type] = os.path.split(dlg.GetPath())[0]
session.WriteSessionFile()
# Destroy the dialog. Don't do this until you are done with it!
# BAD things can happen otherwise!
dlg.Destroy()
return filename
def ShowImportMeshFilesDialog():
# Default system path
current_dir = os.path.abspath(".")
session = ses.Session()
last_directory = session.get('paths', 'last_directory_surface_import', '')
dlg = wx.FileDialog(None, message=_("Import surface file"),
defaultDir=last_directory,
wildcard=WILDCARD_MESH_FILES,
style=wx.FD_OPEN | wx.FD_CHANGE_DIR)
# stl filter is default
dlg.SetFilterIndex(0)
# Show the dialog and retrieve the user response. If it is the OK response,
# process the data.
filename = None
try:
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()
except(wx._core.PyAssertionError): # TODO: error win64
if (dlg.GetPath()):
filename = dlg.GetPath()
if filename:
session['paths']['last_directory_surface_import'] = os.path.split(filename)[0]
session.WriteSessionFile()
# Destroy the dialog. Don't do this until you are done with it!
# BAD things can happen otherwise!
dlg.Destroy()
os.chdir(current_dir)
return filename
def ImportMeshCoordSystem():
msg = _("Was the imported mesh created by InVesalius?")
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.YES_NO)
else:
dlg = wx.MessageDialog(None, msg, "InVesalius 3",
wx.YES_NO)
if dlg.ShowModal() == wx.ID_YES:
flag = False
else:
flag = True
dlg.Destroy()
return flag
def ShowSaveAsProjectDialog(default_filename=None):
current_dir = os.path.abspath(".")
session = ses.Session()
last_directory = session.get('paths', 'last_directory_inv3', '')
dlg = wx.FileDialog(None,
_("Save project as..."), # title
last_directory, # last used directory
default_filename,
WILDCARD_INV_SAVE,
wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
#dlg.SetFilterIndex(0) # default is VTI
filename = None
try:
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()
ok = 1
else:
ok = 0
except(wx._core.PyAssertionError): #TODO: fix win64
filename = dlg.GetPath()
ok = 1
if (ok):
extension = "inv3"
if sys.platform != 'win32':
if filename.split(".")[-1] != extension:
filename = filename + "." + extension
if filename:
session['paths']['last_directory_inv3'] = os.path.split(filename)[0]
session.WriteSessionFile()
wildcard = dlg.GetFilterIndex()
os.chdir(current_dir)
return filename, wildcard == INV_COMPRESSED
def ShowLoadSaveDialog(message=_(u"Load File"), current_dir=os.path.abspath("."), style=wx.FD_OPEN | wx.FD_CHANGE_DIR,
wildcard=_("Registration files (*.obr)|*.obr"), default_filename="", save_ext=None):
dlg = wx.FileDialog(None, message=message, defaultDir="", defaultFile=default_filename,
wildcard=wildcard, style=style)
# Show the dialog and retrieve the user response. If it is the OK response,
# process the data.
filepath = None
try:
if dlg.ShowModal() == wx.ID_OK:
# This returns a Python list of files that were selected.
filepath = dlg.GetPath()
ok_press = 1
else:
ok_press = 0
except(wx._core.PyAssertionError): # FIX: win64
filepath = dlg.GetPath()
ok_press = 1
# fix the extension if set different than expected
if save_ext and ok_press:
extension = save_ext
if sys.platform != 'win32':
if filepath.split(".")[-1] != extension:
filepath = filepath + "." + extension
# Destroy the dialog. Don't do this until you are done with it!
# BAD things can happen otherwise!
dlg.Destroy()
os.chdir(current_dir)
return filepath
class MessageDialog(wx.Dialog):
def __init__(self, message):
wx.Dialog.__init__(self, None, -1, "InVesalius 3", size=(360, 370), pos=wx.DefaultPosition,
style=wx.DEFAULT_DIALOG_STYLE|wx.ICON_INFORMATION)
# Static text which contains message to user
label = wx.StaticText(self, -1, message)
# Buttons
btn_yes = wx.Button(self, wx.ID_YES)
btn_yes.SetHelpText("")
btn_yes.SetDefault()
btn_no = wx.Button(self, wx.ID_NO)
btn_no.SetHelpText("")
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btn_cancel.SetHelpText("")
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_yes)
btnsizer.AddButton(btn_cancel)
btnsizer.AddButton(btn_no)
btnsizer.Realize()
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|
wx.ALIGN_CENTER_HORIZONTAL|wx.ALL, 5)
self.SetSizer(sizer)
sizer.Fit(self)
self.Centre()
class UpdateMessageDialog(wx.Dialog):
def __init__(self, url):
msg=_("A new version of InVesalius is available. Do you want to open the download website now?")
title=_("Invesalius Update")
self.url = url
wx.Dialog.__init__(self, None, -1, title, size=(360, 370), pos=wx.DefaultPosition,
style=wx.DEFAULT_DIALOG_STYLE|wx.ICON_INFORMATION)
# Static text which contains message to user
label = wx.StaticText(self, -1, msg)
# Buttons
btn_yes = wx.Button(self, wx.ID_YES)
btn_yes.SetHelpText("")
btn_yes.SetDefault()
btn_no = wx.Button(self, wx.ID_NO)
btn_no.SetHelpText("")
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_yes)
btnsizer.AddButton(btn_no)
btnsizer.Realize()
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|
wx.ALIGN_CENTER_HORIZONTAL|wx.ALL, 5)
self.SetSizer(sizer)
sizer.Fit(self)
self.Centre()
btn_yes.Bind(wx.EVT_BUTTON, self._OnYes)
btn_no.Bind(wx.EVT_BUTTON, self._OnNo)
# Subscribing to the pubsub event which happens when InVesalius is
# closed.
Publisher.subscribe(self._OnCloseInV, 'Exit')
def _OnYes(self, evt):
# Launches the default browser with the url to download the new
# InVesalius version.
wx.LaunchDefaultBrowser(self.url)
self.Close()
self.Destroy()
def _OnNo(self, evt):
# Closes and destroy this dialog.
self.Close()
self.Destroy()
def _OnCloseInV(self):
# Closes and destroy this dialog.
self.Close()
self.Destroy()
class MessageBox(wx.Dialog):
def __init__(self, parent, title, message, caption="InVesalius3 Error"):
wx.Dialog.__init__(self, parent, title=caption, style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
title_label = wx.StaticText(self, -1, title)
text = wx.TextCtrl(self, style=wx.TE_MULTILINE|wx.TE_READONLY|wx.BORDER_NONE)
text.SetValue(message)
text.SetBackgroundColour(wx.SystemSettings.GetColour(4))
width, height = text.GetTextExtent("O"*30)
text.SetMinSize((width, -1))
btn_ok = wx.Button(self, wx.ID_OK)
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.Realize()
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(title_label, 0, wx.ALL | wx.EXPAND, 5)
sizer.Add(text, 1, wx.ALL | wx.EXPAND, 5)
sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|wx.EXPAND|wx.ALL, 5)
self.SetSizer(sizer)
sizer.Fit(self)
self.Center()
self.ShowModal()
class ErrorMessageBox(wx.Dialog):
def __init__(self, parent, title, message, caption="InVesalius3 Error"):
wx.Dialog.__init__(self, parent, title=caption, style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
title_label = wx.StaticText(self, -1, title)
title_width, title_height = title_label.GetSize()
icon = wx.ArtProvider.GetBitmap(wx.ART_ERROR, wx.ART_MESSAGE_BOX, (title_height * 2, title_height * 2))
bmp = wx.StaticBitmap(self, -1, icon)
text = wx.TextCtrl(self, style=wx.TE_MULTILINE|wx.TE_READONLY|wx.BORDER_NONE)
text.SetValue(message)
text.SetBackgroundColour(wx.SystemSettings.GetColour(4))
width, height = text.GetTextExtent("M"*60)
text.SetMinSize((width, -1))
btn_ok = wx.Button(self, wx.ID_OK)
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.Realize()
title_sizer = wx.BoxSizer(wx.HORIZONTAL)
title_sizer.Add(bmp, 0, wx.ALL | wx.EXPAND, 5)
title_sizer.Add(title_label, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(title_sizer, 0, wx.ALL | wx.EXPAND, 5)
sizer.Add(text, 1, wx.ALL | wx.EXPAND, 5)
sizer.Add(btnsizer, 0, wx.EXPAND | wx.ALL, 5)
self.SetSizer(sizer)
sizer.Fit(self)
self.Center()
def SaveChangesDialog__Old(filename):
message = _("The project %s has been modified.\nSave changes?")%filename
dlg = MessageDialog(message)
answer = dlg.ShowModal()
dlg.Destroy()
if answer == wx.ID_YES:
return 1
elif answer == wx.ID_NO:
return 0
else:
return -1
def ImportEmptyDirectory(dirpath):
msg = _("%s is an empty folder.") % dirpath.decode("utf-8")
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "",
msg,
wx.ICON_INFORMATION | wx.OK)
else:
dlg = wx.MessageDialog(None, msg,
"InVesalius 3",
wx.ICON_INFORMATION | wx.OK)
dlg.ShowModal()
dlg.Destroy()
def ImportOldFormatInvFile():
msg = _("File was created in a newer InVesalius version. Some functionalities may not work correctly.")
dlg = wx.MessageDialog(None, msg,
"InVesalius 3",
wx.ICON_INFORMATION | wx.OK)
dlg.ShowModal()
dlg.Destroy()
def ImportInvalidFiles(ftype="DICOM"):
if ftype == "Bitmap":
msg = _("There are no Bitmap, JPEG, PNG or TIFF files in the selected folder.")
elif ftype == "DICOM":
msg = _("There are no DICOM files in the selected folder.")
else:
msg = _("Invalid file.")
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.ICON_INFORMATION | wx.OK)
else:
dlg = wx.MessageDialog(None, msg, "InVesalius 3",
wx.ICON_INFORMATION | wx.OK)
dlg.ShowModal()
dlg.Destroy()
def ImportAnalyzeWarning():
msg1 = _("Warning! InVesalius has limited support to Analyze format.\n")
msg2 = _("Slices may be wrongly oriented and functions may not work properly.")
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg1 + msg2,
wx.ICON_INFORMATION | wx.OK)
else:
dlg = wx.MessageDialog(None, msg1 + msg2, "InVesalius 3",
wx.ICON_INFORMATION | wx.OK)
dlg.ShowModal()
dlg.Destroy()
def InexistentMask():
msg = _("A mask is needed to create a surface.")
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.ICON_INFORMATION | wx.OK)
else:
dlg = wx.MessageDialog(None, msg, "InVesalius 3",
wx.ICON_INFORMATION | wx.OK)
dlg.ShowModal()
dlg.Destroy()
def MaskSelectionRequiredForRemoval():
msg = _("No mask was selected for removal.")
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.ICON_INFORMATION | wx.OK)
else:
dlg = wx.MessageDialog(None, msg, "InVesalius 3",
wx.ICON_INFORMATION | wx.OK)
dlg.ShowModal()
dlg.Destroy()
def SurfaceSelectionRequiredForRemoval():
msg = _("No surface was selected for removal.")
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.ICON_INFORMATION | wx.OK)
else:
dlg = wx.MessageDialog(None, msg, "InVesalius 3",
wx.ICON_INFORMATION | wx.OK)
dlg.ShowModal()
dlg.Destroy()
def MeasureSelectionRequiredForRemoval():
msg = _("No measure was selected for removal.")
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.ICON_INFORMATION | wx.OK)
else:
dlg = wx.MessageDialog(None, msg, "InVesalius 3",
wx.ICON_INFORMATION | wx.OK)
dlg.ShowModal()
dlg.Destroy()
def MaskSelectionRequiredForDuplication():
msg = _("No mask was selected for duplication.")
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.ICON_INFORMATION | wx.OK)
else:
dlg = wx.MessageDialog(None, msg, "InVesalius 3",
wx.ICON_INFORMATION | wx.OK)
dlg.ShowModal()
dlg.Destroy()
def SurfaceSelectionRequiredForDuplication():
msg = _("No surface was selected for duplication.")
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.ICON_INFORMATION | wx.OK)
else:
dlg = wx.MessageDialog(None, msg, "InVesalius 3",
wx.ICON_INFORMATION | wx.OK)
dlg.ShowModal()
dlg.Destroy()
# Dialogs for neuronavigation mode
# ----------------------------------
def ShowNavigationTrackerWarning(trck_id, lib_mode):
"""
Spatial Tracker connection error
"""
trck = {const.SELECT: 'Tracker',
const.MTC: 'Claron MicronTracker',
const.FASTRAK: 'Polhemus FASTRAK',
const.ISOTRAKII: 'Polhemus ISOTRAK',
const.PATRIOT: 'Polhemus PATRIOT',
const.CAMERA: 'CAMERA',
const.POLARIS: 'NDI Polaris',
const.POLARISP4: 'NDI Polaris P4',
const.OPTITRACK: 'Optitrack',
const.ROBOT: 'Robotic navigation',
const.DEBUGTRACKRANDOM: 'Debug tracker device (random)',
const.DEBUGTRACKAPPROACH: 'Debug tracker device (approach)'}
if lib_mode == 'choose':
msg = _('No tracking device selected')
elif lib_mode == 'error':
msg = trck[trck_id] + _(' is not installed.')
elif lib_mode == 'disconnect':
msg = trck[trck_id] + _(' disconnected.')
else:
msg = trck[trck_id] + _(' is not connected.')
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.ICON_INFORMATION | wx.OK)
else:
dlg = wx.MessageDialog(None, msg, "InVesalius 3 - Neuronavigator",
wx.ICON_INFORMATION | wx.OK)
dlg.ShowModal()
dlg.Destroy()
def ICPcorregistration(fre):
msg = _("The fiducial registration error is: ") + str(round(fre, 2)) + '\n\n' + \
_("Would you like to improve accuracy?")
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.YES_NO)
else:
dlg = wx.MessageDialog(None, msg, "InVesalius 3",
wx.YES_NO)
if dlg.ShowModal() == wx.ID_YES:
flag = True
else:
flag = False
dlg.Destroy()
return flag
def ReportICPerror(prev_error, final_error):
msg = _("Error after refine: ") + str(round(final_error, 2)) + ' mm' + '\n\n' + \
_("Previous error: ") + str(round(prev_error, 2)) + ' mm'
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.OK)
else:
dlg = wx.MessageDialog(None, msg, "InVesalius 3",
wx.OK)
dlg.ShowModal()
dlg.Destroy()
def ShowEnterMarkerID(default):
msg = _("Edit marker ID")
if sys.platform == 'darwin':
dlg = wx.TextEntryDialog(None, "", msg, defaultValue=default)
else:
dlg = wx.TextEntryDialog(None, msg, "InVesalius 3", value=default)
dlg.ShowModal()
result = dlg.GetValue()
dlg.Destroy()
return result
def ShowConfirmationDialog(msg=_('Proceed?')):
# msg = _("Do you want to delete all markers?")
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.OK | wx.CANCEL | wx.ICON_QUESTION)
else:
dlg = wx.MessageDialog(None, msg, "InVesalius 3",
wx.OK | wx.CANCEL | wx.ICON_QUESTION)
result = dlg.ShowModal()
dlg.Destroy()
return result
def ShowColorDialog(color_current):
cdata = wx.ColourData()
cdata.SetColour(wx.Colour(color_current))
dlg = wx.ColourDialog(None, data=cdata)
dlg.GetColourData().SetChooseFull(True)
if dlg.ShowModal() == wx.ID_OK:
color_new = dlg.GetColourData().GetColour().Get(includeAlpha=False)
else:
color_new = None
dlg.Destroy()
return color_new
# ----------------------------------
class NewMask(wx.Dialog):
def __init__(self,
parent=None,
ID=-1,
title="InVesalius 3",
size=wx.DefaultSize,
pos=wx.DefaultPosition,
style=wx.DEFAULT_DIALOG_STYLE,
useMetal=False):
import invesalius.constants as const
import invesalius.data.mask as mask
import invesalius.project as prj
wx.Dialog.__init__(self, parent, ID, title, pos, style=style)
self.SetExtraStyle(wx.DIALOG_EX_CONTEXTHELP)
self.CenterOnScreen()
# This extra style can be set after the UI object has been created.
if 'wxMac' in wx.PlatformInfo and useMetal:
self.SetExtraStyle(wx.DIALOG_EX_METAL)
self.CenterOnScreen()
# LINE 1: Surface name
label_mask = wx.StaticText(self, -1, _("New mask name:"))
default_name = const.MASK_NAME_PATTERN %(mask.Mask.general_index+2)
text = wx.TextCtrl(self, -1, "", size=(80,-1))
text.SetHelpText(_("Name the mask to be created"))
text.SetValue(default_name)
self.text = text
# LINE 2: Threshold of reference
# Informative label
label_thresh = wx.StaticText(self, -1, _("Threshold preset:"))
# Retrieve existing masks
project = prj.Project()
thresh_list = sorted(project.threshold_modes.keys())
default_index = thresh_list.index(_("Bone"))
self.thresh_list = thresh_list
# Mask selection combo
combo_thresh = wx.ComboBox(self, -1, "", choices= self.thresh_list,
style=wx.CB_DROPDOWN|wx.CB_READONLY)
combo_thresh.SetSelection(default_index)
if sys.platform != 'win32':
combo_thresh.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)
self.combo_thresh = combo_thresh
# LINE 3: Gradient
bound_min, bound_max = project.threshold_range
thresh_min, thresh_max = project.threshold_modes[_("Bone")]
original_colour = random.choice(const.MASK_COLOUR)
self.colour = original_colour
colour = [255*i for i in original_colour]
colour.append(100)
gradient = grad.GradientCtrl(self, -1, int(bound_min),
int(bound_max),
int(thresh_min), int(thresh_max),
colour)
self.gradient = gradient
# OVERVIEW
# Sizer that joins content above
flag_link = wx.EXPAND|wx.GROW|wx.ALL
flag_button = wx.ALL | wx.EXPAND| wx.GROW
fixed_sizer = wx.FlexGridSizer(rows=2, cols=2, hgap=10, vgap=10)
fixed_sizer.AddGrowableCol(0, 1)
fixed_sizer.AddMany([ (label_mask, 1, flag_link, 5),
(text, 1, flag_button, 2),
(label_thresh, 1, flag_link, 5),
(combo_thresh, 0, flag_button, 1)])#,
#(label_quality, 1, flag_link, 5),
#(combo_quality, 0, flag_button, 1)])
# LINE 6: Buttons
btn_ok = wx.Button(self, wx.ID_OK)
btn_ok.SetDefault()
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.AddButton(btn_cancel)
btnsizer.Realize()
# OVERVIEW
# Merge all sizers and checkboxes
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(fixed_sizer, 0, wx.ALL|wx.GROW|wx.EXPAND, 15)
sizer.Add(gradient, 0, wx.BOTTOM|wx.RIGHT|wx.LEFT|wx.EXPAND|wx.GROW, 20)
sizer.Add(btnsizer, 0, wx.ALIGN_RIGHT|wx.BOTTOM, 10)
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
self.Bind(grad.EVT_THRESHOLD_CHANGED, self.OnSlideChanged, self.gradient)
self.combo_thresh.Bind(wx.EVT_COMBOBOX, self.OnComboThresh)
def OnComboThresh(self, evt):
import invesalius.project as prj
proj = prj.Project()
(thresh_min, thresh_max) = proj.threshold_modes[evt.GetString()]
self.gradient.SetMinimun(thresh_min)
self.gradient.SetMaximun(thresh_max)
def OnSlideChanged(self, evt):
import invesalius.project as prj
thresh_min = self.gradient.GetMinValue()
thresh_max = self.gradient.GetMaxValue()
thresh = (thresh_min, thresh_max)
proj = prj.Project()
if thresh in proj.threshold_modes.values():
preset_name = proj.threshold_modes.get_key(thresh)[0]
index = self.thresh_list.index(preset_name)
self.combo_thresh.SetSelection(index)
else:
index = self.thresh_list.index(_("Custom"))
self.combo_thresh.SetSelection(index)
def GetValue(self):
#mask_index = self.combo_mask.GetSelection()
mask_name = self.text.GetValue()
thresh_value = [self.gradient.GetMinValue(), self.gradient.GetMaxValue()]
#quality = const.SURFACE_QUALITY_LIST[self.combo_quality.GetSelection()]
#fill_holes = self.check_box_holes.GetValue()
#keep_largest = self.check_box_largest.GetValue()
#return (mask_index, surface_name, quality, fill_holes, keep_largest)
return mask_name, thresh_value, self.colour
def InexistentPath(path):
msg = _("%s does not exist.")%(path)
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.ICON_INFORMATION | wx.OK)
else:
dlg = wx.MessageDialog(None, msg, "InVesalius 3",
wx.ICON_INFORMATION | wx.OK)
dlg.ShowModal()
dlg.Destroy()
def MissingFilesForReconstruction():
msg = _("Please, provide more than one DICOM file for 3D reconstruction")
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.ICON_INFORMATION | wx.OK)
else:
dlg = wx.MessageDialog(None, msg, "InVesalius 3",
wx.ICON_INFORMATION | wx.OK)
dlg.ShowModal()
dlg.Destroy()
def SaveChangesDialog(filename, parent):
current_dir = os.path.abspath(".")
msg = _(u"The project %s has been modified.\nSave changes?")%filename
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.ICON_QUESTION | wx.YES_NO | wx.CANCEL)
else:
dlg = wx.MessageDialog(None, msg, "InVesalius 3",
wx.ICON_QUESTION | wx.YES_NO | wx.CANCEL)
try:
answer = dlg.ShowModal()
except(wx._core.PyAssertionError): #TODO: FIX win64
answer = wx.ID_YES
dlg.Destroy()
os.chdir(current_dir)
if answer == wx.ID_YES:
return 1
elif answer == wx.ID_NO:
return 0
else:
return -1
def SaveChangesDialog2(filename):
current_dir = os.path.abspath(".")
msg = _("The project %s has been modified.\nSave changes?")%filename
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.ICON_QUESTION | wx.YES_NO)
else:
dlg = wx.MessageDialog(None, msg,
"InVesalius 3",
wx.ICON_QUESTION | wx.YES_NO)
answer = dlg.ShowModal()
dlg.Destroy()
os.chdir(current_dir)
if answer == wx.ID_YES:
return 1
else:# answer == wx.ID_NO:
return 0
def ShowAboutDialog(parent):
info = AboutDialogInfo()
info.Name = "InVesalius"
info.Version = const.INVESALIUS_VERSION
info.Copyright = _("(c) 2007-2022 Center for Information Technology Renato Archer - CTI")
info.Description = wordwrap(_("InVesalius is a medical imaging program for 3D reconstruction. It uses a sequence of 2D DICOM image files acquired with CT or MRI scanners. InVesalius allows exporting 3D volumes or surfaces as mesh files for creating physical models of a patient's anatomy using additive manufacturing (3D printing) technologies. The software is developed by Center for Information Technology Renato Archer (CTI), National Council for Scientific and Technological Development (CNPq) and the Brazilian Ministry of Health.\n\n InVesalius must be used only for research. The Center for Information Technology Renato Archer is not responsible for damages caused by the use of this software.\n\n Contact: [email protected]"), 350, wx.ClientDC(parent))
# _("InVesalius is a software for medical imaging 3D reconstruction. ")+\
# _("Its input is a sequency of DICOM 2D image files acquired with CT or MR.\n\n")+\
# _("The software also allows generating correspondent STL files,")+\
# _("so the user can print 3D physical models of the patient's anatomy ")+\
# _("using Rapid Prototyping."), 350, wx.ClientDC(parent))
icon = wx.Icon(os.path.join(inv_paths.ICON_DIR, "invesalius_64x64.ico"),\
wx.BITMAP_TYPE_ICO)
info.SetWebSite("https://www.cti.gov.br/invesalius")
info.SetIcon(icon)
info.License = _("GNU GPL (General Public License) version 2")
info.Developers = [u"Paulo Henrique Junqueira Amorim",
u"Thiago Franco de Moraes",
u"Hélio Pedrini",
u"Jorge Vicente Lopes da Silva",
u"Victor Hugo de Oliveira e Souza (navigator)",
u"Renan Hiroshi Matsuda (navigator)",
u"André Salles Cunha Peres (navigator)",
u"Oswaldo Baffa Filho (navigator)",
u"Tatiana Al-Chueyr (former)",
u"Guilherme Cesar Soares Ruppert (former)",
u"Fabio de Souza Azevedo (former)",
u"Bruno Lara Bottazzini (contributor)",
u"Olly Betts (patches to support wxPython3)"]
info.Translators = [u"Alex P. Natsios",
u"Alicia Perez",
u"Anderson Antonio Mamede da Silva",
u"Andreas Loupasakis",
u"Angelo Pucillo",
u"Annalisa Manenti",
u"Cheng-Chia Tseng",
u"Dan",
u"DCamer",
u"Dimitris Glezos",
u"Eugene Liscio",
u"Frédéric Lopez",
u"Florin Putura",
u"Fri",
u"Jangblue",
u"Javier de Lima Moreno",
u"Kensey Okinawa",
u"Maki Sugimoto",
u"Mario Regino Moreno Guerra",
u"Massimo Crisantemo",
u"Nikolai Guschinsky",
u"Nikos Korkakakis",
u"Raul Bolliger Neto",
u"Sebastian Hilbert",
u"Semarang Pari",
u"Silvério Santos",
u"Vasily Shishkin",
u"Yohei Sotsuka",
u"Yoshihiro Sato"]
#info.DocWriters = ["Fabio Francisco da Silva (PT)"]
info.Artists = [u"Otavio Henrique Junqueira Amorim"]
# Then we call AboutBox providing its info object
AboutBox(info)
def ShowSavePresetDialog(default_filename="raycasting"):
dlg = wx.TextEntryDialog(None,
_("Save raycasting preset as:"),
"InVesalius 3")
#dlg.SetFilterIndex(0) # default is VTI
filename = None
try:
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetValue()
except(wx._core.PyAssertionError):
filename = dlg.GetValue()
return filename
class NewSurfaceDialog(wx.Dialog):
def __init__(self, parent=None, ID=-1, title="InVesalius 3", size=wx.DefaultSize,
pos=wx.DefaultPosition, style=wx.DEFAULT_DIALOG_STYLE,
useMetal=False):
import invesalius.constants as const
import invesalius.data.surface as surface
import invesalius.project as prj
wx.Dialog.__init__(self, parent, ID, title, pos, (500,300), style)
self.SetExtraStyle(wx.DIALOG_EX_CONTEXTHELP)
self.CenterOnScreen()
# This extra style can be set after the UI object has been created.
if 'wxMac' in wx.PlatformInfo and useMetal:
self.SetExtraStyle(wx.DIALOG_EX_METAL)
self.CenterOnScreen()
# LINE 1: Surface name
label_surface = wx.StaticText(self, -1, _("New surface name:"))
default_name = const.SURFACE_NAME_PATTERN %(surface.Surface.general_index+2)
text = wx.TextCtrl(self, -1, "", size=(80,-1))
text.SetHelpText(_("Name the surface to be created"))
text.SetValue(default_name)
self.text = text
# LINE 2: Mask of reference
# Informative label
label_mask = wx.StaticText(self, -1, _("Mask of reference:"))
# Retrieve existing masks
project = prj.Project()
index_list = sorted(project.mask_dict.keys())
self.mask_list = [project.mask_dict[index].name for index in index_list]
# Mask selection combo
combo_mask = wx.ComboBox(self, -1, "", choices= self.mask_list,
style=wx.CB_DROPDOWN|wx.CB_READONLY)
combo_mask.SetSelection(len(self.mask_list)-1)
if sys.platform != 'win32':
combo_mask.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)
self.combo_mask = combo_mask
# LINE 3: Surface quality
label_quality = wx.StaticText(self, -1, _("Surface quality:"))
choices = const.SURFACE_QUALITY_LIST
style = wx.CB_DROPDOWN|wx.CB_READONLY
combo_quality = wx.ComboBox(self, -1, "",
choices= choices,
style=style)
combo_quality.SetSelection(3)
if sys.platform != 'win32':
combo_quality.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)
self.combo_quality = combo_quality
# OVERVIEW
# Sizer that joins content above
flag_link = wx.EXPAND|wx.GROW|wx.ALL
flag_button = wx.ALL | wx.EXPAND| wx.GROW
fixed_sizer = wx.FlexGridSizer(rows=2, cols=2, hgap=10, vgap=0)
fixed_sizer.AddGrowableCol(0, 1)
fixed_sizer.AddMany([ (label_surface, 1, flag_link, 5),
(text, 1, flag_button, 2),
(label_mask, 1, flag_link, 5),
(combo_mask, 0, flag_button, 1),
(label_quality, 1, flag_link, 5),
(combo_quality, 0, flag_button, 1)])
# LINES 4 and 5: Checkboxes
check_box_holes = wx.CheckBox(self, -1, _("Fill holes"))
check_box_holes.SetValue(True)
self.check_box_holes = check_box_holes
check_box_largest = wx.CheckBox(self, -1, _("Keep largest region"))
self.check_box_largest = check_box_largest
# LINE 6: Buttons
btn_ok = wx.Button(self, wx.ID_OK)
btn_ok.SetDefault()
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.AddButton(btn_cancel)
btnsizer.Realize()
# OVERVIEW
# Merge all sizers and checkboxes
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(fixed_sizer, 0, wx.TOP|wx.RIGHT|wx.LEFT|wx.GROW|wx.EXPAND, 20)
sizer.Add(check_box_holes, 0, wx.RIGHT|wx.LEFT, 30)
sizer.Add(check_box_largest, 0, wx.RIGHT|wx.LEFT, 30)
sizer.Add(btnsizer, 0, wx.ALIGN_RIGHT|wx.ALL, 10)
self.SetSizer(sizer)
sizer.Fit(self)
def GetValue(self):
mask_index = self.combo_mask.GetSelection()
surface_name = self.text.GetValue()
quality = const.SURFACE_QUALITY_LIST[self.combo_quality.GetSelection()]
fill_holes = self.check_box_holes.GetValue()
keep_largest = self.check_box_largest.GetValue()
return (mask_index, surface_name, quality, fill_holes, keep_largest)
def ExportPicture(type_=""):
import invesalius.constants as const
import invesalius.project as proj
INDEX_TO_EXTENSION = {0: "bmp", 1: "jpg", 2: "png", 3: "ps", 4:"povray", 5:"tiff"}
WILDCARD_SAVE_PICTURE = _("BMP image")+" (*.bmp)|*.bmp|"+\
_("JPG image")+" (*.jpg)|*.jpg|"+\
_("PNG image")+" (*.png)|*.png|"+\
_("PostScript document")+" (*.ps)|*.ps|"+\
_("POV-Ray file")+" (*.pov)|*.pov|"+\
_("TIFF image")+" (*.tif)|*.tif"
INDEX_TO_TYPE = {0: const.FILETYPE_BMP,
1: const.FILETYPE_JPG,
2: const.FILETYPE_PNG,
3: const.FILETYPE_PS,
4: const.FILETYPE_POV,
5: const.FILETYPE_TIF}
utils.debug("ExportPicture")
project = proj.Project()
session = ses.Session()
last_directory = session.get('paths', 'last_directory_screenshot', '')
project_name = "%s_%s" % (project.name, type_)
if not sys.platform in ('win32', 'linux2', 'linux'):
project_name += ".jpg"
dlg = wx.FileDialog(None,
"Save %s picture as..." %type_,
last_directory, # last used directory
project_name, # filename
WILDCARD_SAVE_PICTURE,
wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
dlg.SetFilterIndex(1) # default is VTI
if dlg.ShowModal() == wx.ID_OK:
filetype_index = dlg.GetFilterIndex()
filetype = INDEX_TO_TYPE[filetype_index]
extension = INDEX_TO_EXTENSION[filetype_index]
filename = dlg.GetPath()
session['paths']['last_directory_screenshot'] = os.path.split(filename)[0]
session.WriteSessionFile()
if sys.platform != 'win32':
if filename.split(".")[-1] != extension:
filename = filename + "."+ extension
return filename, filetype
else:
return ()
class SurfaceDialog(wx.Dialog):
'''
This dialog is only shown when the mask whose surface will be generate was
edited. So far, the only options available are the choice of method to
generate the surface, Binary or `Context aware smoothing', and options from
`Context aware smoothing'
'''
def __init__(self):
wx.Dialog.__init__(self, None, -1, _('Surface generation options'))
self._build_widgets()
self.CenterOnScreen()
def _build_widgets(self):
btn_ok = wx.Button(self, wx.ID_OK)
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btn_sizer = wx.StdDialogButtonSizer()
btn_sizer.AddButton(btn_ok)
btn_sizer.AddButton(btn_cancel)
btn_sizer.Realize()
self.ca = SurfaceMethodPanel(self, -1, True)
self.main_sizer = wx.BoxSizer(wx.VERTICAL)
self.main_sizer.Add(self.ca, 0, wx.EXPAND|wx.ALL, 5)
self.main_sizer.Add(btn_sizer, 0, wx.EXPAND | wx.ALL, 5)
self.SetSizer(self.main_sizer)
self.Fit()
def GetOptions(self):
return self.ca.GetOptions()
def GetAlgorithmSelected(self):
return self.ca.GetAlgorithmSelected()
####################### New surface creation dialog ###########################
class SurfaceCreationDialog(wx.Dialog):
def __init__(self, parent=None, ID=-1, title=_(u"Surface creation"),
size=wx.DefaultSize, pos=wx.DefaultPosition,
style=wx.DEFAULT_DIALOG_STYLE, useMetal=False,
mask_edited=False):
wx.Dialog.__init__(self, parent, ID, title, pos, size, style)
self.SetExtraStyle(wx.DIALOG_EX_CONTEXTHELP)
if 'wxMac' in wx.PlatformInfo and useMetal:
self.SetExtraStyle(wx.DIALOG_EX_METAL)
self.CenterOnScreen()
# It's necessary to create a staticbox before is children widgets
# because otherwise in MacOSX it'll not be possible to use the mouse in
# static's children widgets.
sb_nsd = wx.StaticBox(self, -1, _('Surface creation options'))
self.nsd = SurfaceCreationOptionsPanel(self, -1)
self.nsd.Bind(EVT_MASK_SET, self.OnSetMask)
surface_options_sizer = wx.StaticBoxSizer(sb_nsd, wx.VERTICAL)
surface_options_sizer.Add(self.nsd, 1, wx.EXPAND|wx.ALL, 5)
sb_ca = wx.StaticBox(self, -1, _('Surface creation method'))
self.ca = SurfaceMethodPanel(self, -1, mask_edited)
surface_method_sizer = wx.StaticBoxSizer(sb_ca, wx.VERTICAL)
surface_method_sizer.Add(self.ca, 1, wx.EXPAND|wx.ALL, 5)
btn_ok = wx.Button(self, wx.ID_OK)
btn_ok.SetDefault()
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.AddButton(btn_cancel)
btnsizer.Realize()
sizer_panels = wx.BoxSizer(wx.HORIZONTAL)
sizer_panels.Add(surface_options_sizer, 0, wx.EXPAND|wx.ALL, 5)
sizer_panels.Add(surface_method_sizer, 0, wx.EXPAND|wx.ALL, 5)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(sizer_panels, 0, wx.ALIGN_RIGHT|wx.ALL, 5)
sizer.Add(btnsizer, 0, wx.ALIGN_RIGHT|wx.ALL, 5)
self.SetSizer(sizer)
sizer.Fit(self)
def OnSetMask(self, evt):
import invesalius.project as proj
mask = proj.Project().mask_dict[evt.mask_index]
self.ca.mask_edited = mask.was_edited
self.ca.ReloadMethodsOptions()
def GetValue(self):
return {"method": self.ca.GetValue(),
"options": self.nsd.GetValue()}
class SurfaceCreationOptionsPanel(wx.Panel):
def __init__(self, parent, ID=-1):
import invesalius.constants as const
import invesalius.data.surface as surface
import invesalius.project as prj
import invesalius.data.slice_ as slc
wx.Panel.__init__(self, parent, ID)
# LINE 1: Surface name
label_surface = wx.StaticText(self, -1, _("New surface name:"))
default_name = const.SURFACE_NAME_PATTERN %(surface.Surface.general_index+2)
text = wx.TextCtrl(self, -1, "", size=(80,-1))
text.SetHelpText(_("Name the surface to be created"))
text.SetValue(default_name)
self.text = text
# LINE 2: Mask of reference
# Informative label
label_mask = wx.StaticText(self, -1, _("Mask of reference:"))
#Retrieve existing masks
project = prj.Project()
index_list = project.mask_dict.keys()
self.mask_list = [project.mask_dict[index].name for index in sorted(index_list)]
active_mask = 0
for idx in project.mask_dict:
if project.mask_dict[idx] is slc.Slice().current_mask:
active_mask = idx
break
# Mask selection combo
combo_mask = wx.ComboBox(self, -1, "", choices= self.mask_list,
style=wx.CB_DROPDOWN|wx.CB_READONLY)
combo_mask.SetSelection(active_mask)
combo_mask.Bind(wx.EVT_COMBOBOX, self.OnSetMask)
if sys.platform != 'win32':
combo_mask.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)
self.combo_mask = combo_mask
# LINE 3: Surface quality
label_quality = wx.StaticText(self, -1, _("Surface quality:"))
choices = const.SURFACE_QUALITY_LIST
style = wx.CB_DROPDOWN|wx.CB_READONLY
combo_quality = wx.ComboBox(self, -1, "",
choices= choices,
style=style)
combo_quality.SetSelection(3)
if sys.platform != 'win32':
combo_quality.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)
self.combo_quality = combo_quality
# OVERVIEW
# Sizer that joins content above
flag_link = wx.EXPAND|wx.GROW|wx.ALL
flag_button = wx.ALL | wx.EXPAND| wx.GROW
fixed_sizer = wx.FlexGridSizer(rows=3, cols=2, hgap=10, vgap=5)
fixed_sizer.AddGrowableCol(0, 1)
fixed_sizer.AddMany([ (label_surface, 1, flag_link, 0),
(text, 1, flag_button, 0),
(label_mask, 1, flag_link, 0),
(combo_mask, 0, flag_button, 0),
(label_quality, 1, flag_link, 0),
(combo_quality, 0, flag_button, 0)])
# LINES 4, 5 and 6: Checkboxes
check_box_border_holes = wx.CheckBox(self, -1, _("Fill border holes"))
check_box_border_holes.SetValue(False)
self.check_box_border_holes = check_box_border_holes
check_box_holes = wx.CheckBox(self, -1, _("Fill holes"))
check_box_holes.SetValue(False)
self.check_box_holes = check_box_holes
check_box_largest = wx.CheckBox(self, -1, _("Keep largest region"))
self.check_box_largest = check_box_largest
# OVERVIEW
# Merge all sizers and checkboxes
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(fixed_sizer, 0, wx.TOP|wx.RIGHT|wx.LEFT|wx.GROW|wx.EXPAND, 5)
sizer.Add(check_box_border_holes, 0, wx.RIGHT|wx.LEFT, 5)
sizer.Add(check_box_holes, 0, wx.RIGHT|wx.LEFT, 5)
sizer.Add(check_box_largest, 0, wx.RIGHT|wx.LEFT, 5)
self.SetSizer(sizer)
sizer.Fit(self)
def OnSetMask(self, evt):
new_evt = MaskEvent(myEVT_MASK_SET, -1, self.combo_mask.GetSelection())
self.GetEventHandler().ProcessEvent(new_evt)
def GetValue(self):
mask_index = self.combo_mask.GetSelection()
surface_name = self.text.GetValue()
quality = const.SURFACE_QUALITY_LIST[self.combo_quality.GetSelection()]
fill_border_holes = self.check_box_border_holes.GetValue()
fill_holes = self.check_box_holes.GetValue()
keep_largest = self.check_box_largest.GetValue()
return {"index": mask_index,
"name": surface_name,
"quality": quality,
"fill_border_holes": fill_border_holes,
"fill": fill_holes,
"keep_largest": keep_largest,
"overwrite": False}
class CAOptions(wx.Panel):
'''
Options related to Context aware algorithm:
Angle: The min angle to a vertex to be considered a staircase vertex;
Max distance: The max distance a normal vertex must be to calculate its
weighting;
Min Weighting: The min weight a vertex must have;
Steps: The number of iterations the smoothing algorithm have to do.
'''
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1)
self._build_widgets()<|fim▁hole|>
def _build_widgets(self):
sb = wx.StaticBox(self, -1, _('Options'))
self.angle = InvFloatSpinCtrl(self, -1, value=0.7, min_value=0.0,
max_value=1.0, increment=0.1,
digits=1)
self.max_distance = InvFloatSpinCtrl(self, -1, value=3.0, min_value=0.0,
max_value=100.0, increment=0.1,
digits=2)
self.min_weight = InvFloatSpinCtrl(self, -1, value=0.5, min_value=0.0,
max_value=1.0, increment=0.1,
digits=1)
self.steps = InvSpinCtrl(self, -1, value=10, min_value=1, max_value=100)
layout_sizer = wx.FlexGridSizer(rows=4, cols=2, hgap=5, vgap=5)
layout_sizer.Add(wx.StaticText(self, -1, _(u'Angle:')), 0, wx.EXPAND)
layout_sizer.Add(self.angle, 0, wx.EXPAND)
layout_sizer.Add(wx.StaticText(self, -1, _(u'Max. distance:')), 0, wx.EXPAND)
layout_sizer.Add(self.max_distance, 0, wx.EXPAND)
layout_sizer.Add(wx.StaticText(self, -1, _(u'Min. weight:')), 0, wx.EXPAND)
layout_sizer.Add(self.min_weight, 0, wx.EXPAND)
layout_sizer.Add(wx.StaticText(self, -1, _(u'N. steps:')), 0, wx.EXPAND)
layout_sizer.Add(self.steps, 0, wx.EXPAND)
self.main_sizer = wx.StaticBoxSizer(sb, wx.VERTICAL)
self.main_sizer.Add(layout_sizer, 0, wx.EXPAND | wx.ALL, 5)
self.SetSizer(self.main_sizer)
class SurfaceMethodPanel(wx.Panel):
'''
This dialog is only shown when the mask whose surface will be generate was
edited. So far, the only options available are the choice of method to
generate the surface, Binary or `Context aware smoothing', and options from
`Context aware smoothing'
'''
def __init__(self, parent, id, mask_edited=False):
wx.Panel.__init__(self, parent, id)
self.mask_edited = mask_edited
self.alg_types = {_(u'Default'): 'Default',
_(u'Context aware smoothing'): 'ca_smoothing',
_(u'Binary'): 'Binary'}
self.edited_imp = [_(u'Default'), ]
self._build_widgets()
self._bind_wx()
def _build_widgets(self):
self.ca_options = CAOptions(self)
self.cb_types = wx.ComboBox(self, -1, _(u'Default'),
choices=[i for i in sorted(self.alg_types)
if not (self.mask_edited and i in self.edited_imp)],
style=wx.CB_READONLY)
w, h = self.cb_types.GetSize()
icon = wx.ArtProvider.GetBitmap(wx.ART_INFORMATION, wx.ART_MESSAGE_BOX,
(h * 0.8, h * 0.8))
self.bmp = wx.StaticBitmap(self, -1, icon)
self.bmp.SetToolTip(_("It is not possible to use the Default method because the mask was edited."))
self.method_sizer = wx.BoxSizer(wx.HORIZONTAL)
self.method_sizer.Add(wx.StaticText(self, -1, _(u'Method:')), 0,
wx.EXPAND | wx.ALL, 5)
self.method_sizer.Add(self.cb_types, 1, wx.EXPAND)
self.method_sizer.Add(self.bmp, 0, wx.EXPAND|wx.ALL, 5)
self.main_sizer = wx.BoxSizer(wx.VERTICAL)
self.main_sizer.Add(self.method_sizer, 0, wx.EXPAND | wx.ALL, 5)
self.main_sizer.Add(self.ca_options, 0, wx.EXPAND | wx.ALL, 5)
self.SetSizer(self.main_sizer)
self.Layout()
self.Fit()
if self.mask_edited:
self.cb_types.SetValue(_(u'Context aware smoothing'))
self.ca_options.Enable()
self.method_sizer.Show(self.bmp)
else:
self.ca_options.Disable()
self.method_sizer.Hide(self.bmp)
def _bind_wx(self):
self.cb_types.Bind(wx.EVT_COMBOBOX, self._set_cb_types)
def _set_cb_types(self, evt):
if self.alg_types[evt.GetString()] == 'ca_smoothing':
self.ca_options.Enable()
else:
self.ca_options.Disable()
evt.Skip()
def GetAlgorithmSelected(self):
try:
return self.alg_types[self.cb_types.GetValue()]
except KeyError:
return self.alg_types[0]
def GetOptions(self):
if self.GetAlgorithmSelected() == 'ca_smoothing':
options = {'angle': self.ca_options.angle.GetValue(),
'max distance': self.ca_options.max_distance.GetValue(),
'min weight': self.ca_options.min_weight.GetValue(),
'steps': self.ca_options.steps.GetValue()}
else:
options = {}
return options
def GetValue(self):
algorithm = self.GetAlgorithmSelected()
options = self.GetOptions()
return {"algorithm": algorithm,
"options": options}
def ReloadMethodsOptions(self):
self.cb_types.Clear()
self.cb_types.AppendItems([i for i in sorted(self.alg_types)
if not (self.mask_edited and i in self.edited_imp)])
if self.mask_edited:
self.cb_types.SetValue(_(u'Context aware smoothing'))
self.ca_options.Enable()
self.method_sizer.Show(self.bmp)
else:
self.cb_types.SetValue(_(u'Default'))
self.ca_options.Disable()
self.method_sizer.Hide(self.bmp)
self.method_sizer.Layout()
class ClutImagedataDialog(wx.Dialog):
def __init__(self, histogram, init, end, nodes=None):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1, style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP)
self.histogram = histogram
self.init = init
self.end = end
self.nodes = nodes
self._init_gui()
self.bind_events()
self.bind_events_wx()
def _init_gui(self):
self.clut_widget = CLUTImageDataWidget(self, -1, self.histogram,
self.init, self.end, self.nodes)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.clut_widget, 1, wx.EXPAND)
self.SetSizer(sizer)
self.Fit()
def bind_events_wx(self):
self.clut_widget.Bind(EVT_CLUT_NODE_CHANGED, self.OnClutChange)
def bind_events(self):
Publisher.subscribe(self._refresh_widget, 'Update clut imagedata widget')
def OnClutChange(self, evt):
Publisher.sendMessage('Change colour table from background image from widget',
nodes=evt.GetNodes())
Publisher.sendMessage('Update window level text',
window=self.clut_widget.window_width,
level=self.clut_widget.window_level)
def _refresh_widget(self):
self.clut_widget.Refresh()
def Show(self, gen_evt=True, show=True):
super(wx.Dialog, self).Show(show)
if gen_evt:
self.clut_widget._generate_event()
class WatershedOptionsPanel(wx.Panel):
def __init__(self, parent, config):
wx.Panel.__init__(self, parent)
self.algorithms = ("Watershed", "Watershed IFT")
self.con2d_choices = (4, 8)
self.con3d_choices = (6, 18, 26)
self.config = config
self._init_gui()
def _init_gui(self):
self.choice_algorithm = wx.RadioBox(self, -1, _(u"Method"),
choices=self.algorithms,
style=wx.NO_BORDER | wx.HORIZONTAL)
self.choice_algorithm.SetSelection(self.algorithms.index(self.config.algorithm))
self.choice_2dcon = wx.RadioBox(self, -1, "2D",
choices=[str(i) for i in self.con2d_choices],
style=wx.NO_BORDER | wx.HORIZONTAL)
self.choice_2dcon.SetSelection(self.con2d_choices.index(self.config.con_2d))
self.choice_3dcon = wx.RadioBox(self, -1, "3D",
choices=[str(i) for i in self.con3d_choices],
style=wx.NO_BORDER | wx.HORIZONTAL)
self.choice_3dcon.SetSelection(self.con3d_choices.index(self.config.con_3d))
self.gaussian_size = InvSpinCtrl(self, -1, value=self.config.mg_size,
min_value=1, max_value=10)
box_sizer = wx.StaticBoxSizer(wx.StaticBox(self, -1, "Conectivity"), wx.VERTICAL)
box_sizer.Add(self.choice_2dcon, 0, wx.ALL, 5)
box_sizer.Add(self.choice_3dcon, 0, wx.ALL, 5)
g_sizer = wx.BoxSizer(wx.HORIZONTAL)
g_sizer.Add(wx.StaticText(self, -1, _("Gaussian sigma")), 0, wx.ALIGN_CENTER | wx.ALL, 5)
g_sizer.Add(self.gaussian_size, 0, wx.ALL, 5)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.choice_algorithm, 0, wx.ALL, 5)
sizer.Add(box_sizer, 1, wx.EXPAND | wx.ALL, 5)
sizer.Add(g_sizer, 0, wx.ALL, 5)
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
def apply_options(self):
self.config.algorithm = self.algorithms[self.choice_algorithm.GetSelection()]
self.config.con_2d = self.con2d_choices[self.choice_2dcon.GetSelection()]
self.config.con_3d = self.con3d_choices[self.choice_3dcon.GetSelection()]
self.config.mg_size = self.gaussian_size.GetValue()
class WatershedOptionsDialog(wx.Dialog):
def __init__(self, config, ID=-1, title=_(u'Watershed'), style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), ID, title=title, style=style)
self.config = config
self._init_gui()
def _init_gui(self):
wop = WatershedOptionsPanel(self, self.config)
self.wop = wop
sizer = wx.BoxSizer(wx.VERTICAL)
btn_ok = wx.Button(self, wx.ID_OK)
btn_ok.SetDefault()
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.AddButton(btn_cancel)
btnsizer.Realize()
sizer.Add(wop, 0, wx.EXPAND)
sizer.Add(btnsizer, 0, wx.ALIGN_RIGHT | wx.BOTTOM, 5)
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
btn_ok.Bind(wx.EVT_BUTTON, self.OnOk)
self.CenterOnScreen()
def OnOk(self, evt):
self.wop.apply_options()
evt.Skip()
class MaskBooleanDialog(wx.Dialog):
def __init__(self, masks, ID=-1, title=_(u"Boolean operations"), style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), ID, title=title, style=style)
self._init_gui(masks)
self.CenterOnScreen()
def _init_gui(self, masks):
mask_choices = [(masks[i].name, masks[i]) for i in sorted(masks)]
self.mask1 = wx.ComboBox(self, -1, mask_choices[0][0], choices=[])
self.mask2 = wx.ComboBox(self, -1, mask_choices[0][0], choices=[])
for n, m in mask_choices:
self.mask1.Append(n, m)
self.mask2.Append(n, m)
self.mask1.SetSelection(0)
if len(mask_choices) > 1:
self.mask2.SetSelection(1)
else:
self.mask2.SetSelection(0)
icon_folder = inv_paths.ICON_DIR
op_choices = ((_(u"Union"), const.BOOLEAN_UNION, 'bool_union.png'),
(_(u"Difference"), const.BOOLEAN_DIFF, 'bool_difference.png'),
(_(u"Intersection"), const.BOOLEAN_AND, 'bool_intersection.png'),
(_(u"Exclusive disjunction"), const.BOOLEAN_XOR, 'bool_disjunction.png'))
self.op_boolean = BitmapComboBox(self, -1, op_choices[0][0], choices=[])
for n, i, f in op_choices:
bmp = wx.Bitmap(os.path.join(icon_folder, f), wx.BITMAP_TYPE_PNG)
self.op_boolean.Append(n, bmp, i)
self.op_boolean.SetSelection(0)
btn_ok = wx.Button(self, wx.ID_OK)
btn_ok.SetDefault()
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.AddButton(btn_cancel)
btnsizer.Realize()
gsizer = wx.FlexGridSizer(rows=3, cols=2, hgap=5, vgap=5)
gsizer.Add(wx.StaticText(self, -1, _(u"Mask 1")), 0, wx.ALIGN_CENTER_VERTICAL)
gsizer.Add(self.mask1, 1, wx.EXPAND)
gsizer.Add(wx.StaticText(self, -1, _(u"Operation")), 0, wx.ALIGN_CENTER_VERTICAL)
gsizer.Add(self.op_boolean, 1, wx.EXPAND)
gsizer.Add(wx.StaticText(self, -1, _(u"Mask 2")), 0, wx.ALIGN_CENTER_VERTICAL)
gsizer.Add(self.mask2, 1, wx.EXPAND)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(gsizer, 0, wx.EXPAND | wx.ALL, border=5)
sizer.Add(btnsizer, 0, wx.EXPAND | wx.ALL, border=5)
self.SetSizer(sizer)
sizer.Fit(self)
btn_ok.Bind(wx.EVT_BUTTON, self.OnOk)
def OnOk(self, evt):
op = self.op_boolean.GetClientData(self.op_boolean.GetSelection())
m1 = self.mask1.GetClientData(self.mask1.GetSelection())
m2 = self.mask2.GetClientData(self.mask2.GetSelection())
Publisher.sendMessage('Do boolean operation',
operation=op, mask1=m1, mask2=m2)
Publisher.sendMessage('Reload actual slice')
Publisher.sendMessage('Refresh viewer')
self.Close()
self.Destroy()
class ReorientImageDialog(wx.Dialog):
def __init__(self, ID=-1, title=_(u'Image reorientation'), style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), ID, title=title, style=style)
self._closed = False
self._last_ax = "0.0"
self._last_ay = "0.0"
self._last_az = "0.0"
self._init_gui()
self._bind_events()
self._bind_events_wx()
def _init_gui(self):
interp_methods_choices = ((_(u"Nearest Neighbour"), 0),
(_(u"Trilinear"), 1),
(_(u"Tricubic"), 2),
(_(u"Lanczos (experimental)"), 3))
self.interp_method = wx.ComboBox(self, -1, choices=[], style=wx.CB_READONLY)
for txt, im_code in interp_methods_choices:
self.interp_method.Append(txt, im_code)
self.interp_method.SetValue(interp_methods_choices[2][0])
self.anglex = wx.TextCtrl(self, -1, "0.0")
self.angley = wx.TextCtrl(self, -1, "0.0")
self.anglez = wx.TextCtrl(self, -1, "0.0")
self.btnapply = wx.Button(self, -1, _("Apply"))
sizer = wx.BoxSizer(wx.VERTICAL)
angles_sizer = wx.FlexGridSizer(3, 2, 5, 5)
angles_sizer.AddMany([
(wx.StaticText(self, -1, _("Angle X")), 1, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5),
(self.anglex, 0, wx.EXPAND | wx.ALL, 5),
(wx.StaticText(self, -1, _("Angle Y")), 1, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5),
(self.angley, 0, wx.EXPAND | wx.ALL, 5),
(wx.StaticText(self, -1, _("Angle Z")), 1, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5),
(self.anglez, 0, wx.EXPAND | wx.ALL, 5),
])
sizer.Add(wx.StaticText(self, -1, _("Interpolation method:")), 0, wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, 5)
sizer.Add(self.interp_method, 0, wx.EXPAND | wx.ALL, 5)
sizer.Add(angles_sizer, 0, wx.EXPAND | wx.ALL, 5)
sizer.Add(self.btnapply, 0, wx.EXPAND | wx.ALL, 5)
sizer.AddSpacer(5)
self.SetSizer(sizer)
self.Fit()
def _bind_events(self):
Publisher.subscribe(self._update_angles, 'Update reorient angles')
Publisher.subscribe(self._close_dialog, 'Close reorient dialog')
def _bind_events_wx(self):
self.interp_method.Bind(wx.EVT_COMBOBOX, self.OnSelect)
self.anglex.Bind(wx.EVT_KILL_FOCUS, self.OnLostFocus)
self.angley.Bind(wx.EVT_KILL_FOCUS, self.OnLostFocus)
self.anglez.Bind(wx.EVT_KILL_FOCUS, self.OnLostFocus)
self.anglex.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
self.angley.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
self.anglez.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
self.btnapply.Bind(wx.EVT_BUTTON, self.apply_reorientation)
self.Bind(wx.EVT_CLOSE, self.OnClose)
def _update_angles(self, angles):
anglex, angley, anglez = angles
self.anglex.SetValue("%.3f" % np.rad2deg(anglex))
self.angley.SetValue("%.3f" % np.rad2deg(angley))
self.anglez.SetValue("%.3f" % np.rad2deg(anglez))
def _close_dialog(self):
self.Destroy()
def apply_reorientation(self, evt):
Publisher.sendMessage('Apply reorientation')
self.Close()
def OnClose(self, evt):
self._closed = True
Publisher.sendMessage('Disable style', style=const.SLICE_STATE_REORIENT)
Publisher.sendMessage('Enable style', style=const.STATE_DEFAULT)
self.Destroy()
def OnSelect(self, evt):
im_code = self.interp_method.GetClientData(self.interp_method.GetSelection())
Publisher.sendMessage('Set interpolation method', interp_method=im_code)
def OnSetFocus(self, evt):
self._last_ax = self.anglex.GetValue()
self._last_ay = self.angley.GetValue()
self._last_az = self.anglez.GetValue()
def OnLostFocus(self, evt):
if not self._closed:
try:
ax = np.deg2rad(float(self.anglex.GetValue()))
ay = np.deg2rad(float(self.angley.GetValue()))
az = np.deg2rad(float(self.anglez.GetValue()))
except ValueError:
self.anglex.SetValue(self._last_ax)
self.angley.SetValue(self._last_ay)
self.anglez.SetValue(self._last_az)
return
Publisher.sendMessage('Set reorientation angles', angles=(ax, ay, az))
class ImportBitmapParameters(wx.Dialog):
from os import sys
def __init__(self):
if sys.platform == 'win32':
size=wx.Size(380,180)
else:
size=wx.Size(380,210)
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1,
_(u"Create project from bitmap"),
size=size,
style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP)
self.interval = 0
self._init_gui()
self.bind_evts()
self.CenterOnScreen()
def _init_gui(self):
import invesalius.project as prj
p = wx.Panel(self, -1, style = wx.TAB_TRAVERSAL
| wx.CLIP_CHILDREN
| wx.FULL_REPAINT_ON_RESIZE)
gbs_principal = self.gbs = wx.GridBagSizer(4,1)
gbs = self.gbs = wx.GridBagSizer(5, 2)
flag_labels = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL
stx_name = wx.StaticText(p, -1, _(u"Project name:"))
tx_name = self.tx_name = wx.TextCtrl(p, -1, "InVesalius Bitmap", size=wx.Size(220,-1))
stx_orientation = wx.StaticText(p, -1, _(u"Slices orientation:"),)
cb_orientation_options = [_(u'Axial'), _(u'Coronal'), _(u'Sagital')]
cb_orientation = self.cb_orientation = wx.ComboBox(p, value="Axial", choices=cb_orientation_options,\
size=wx.Size(160,-1), style=wx.CB_DROPDOWN|wx.CB_READONLY)
stx_spacing = wx.StaticText(p, -1, _(u"Spacing (mm):"))
gbs.Add(stx_name, (0,0), flag=flag_labels)
gbs.Add(tx_name, (0,1))
try:
gbs.Add(0, 0, (1,0))
except TypeError:
gbs.AddStretchSpacer((1,0))
gbs.Add(stx_orientation, (2,0), flag=flag_labels)
gbs.Add(cb_orientation, (2,1))
gbs.Add(stx_spacing, (3,0))
try:
gbs.Add(0, 0, (4,0))
except TypeError:
gbs.AddStretchSpacer((4,0))
#--- spacing --------------
gbs_spacing = wx.GridBagSizer(2, 6)
stx_spacing_x = stx_spacing_x = wx.StaticText(p, -1, _(u"X:"))
fsp_spacing_x = self.fsp_spacing_x = InvFloatSpinCtrl(p, -1, min_value=0, max_value=1000000000,
increment=0.25, value=1.0, digits=8)
stx_spacing_y = stx_spacing_y = wx.StaticText(p, -1, _(u"Y:"))
fsp_spacing_y = self.fsp_spacing_y = InvFloatSpinCtrl(p, -1, min_value=0, max_value=1000000000,
increment=0.25, value=1.0, digits=8)
stx_spacing_z = stx_spacing_z = wx.StaticText(p, -1, _(u"Z:"))
fsp_spacing_z = self.fsp_spacing_z = InvFloatSpinCtrl(p, -1, min_value=0, max_value=1000000000,
increment=0.25, value=1.0, digits=8)
try:
proj = prj.Project()
sx = proj.spacing[0]
sy = proj.spacing[1]
sz = proj.spacing[2]
fsp_spacing_x.SetValue(sx)
fsp_spacing_y.SetValue(sy)
fsp_spacing_z.SetValue(sz)
except(AttributeError):
pass
gbs_spacing.Add(stx_spacing_x, (0,0), flag=flag_labels)
gbs_spacing.Add(fsp_spacing_x, (0,1))
gbs_spacing.Add(stx_spacing_y, (0,2), flag=flag_labels)
gbs_spacing.Add(fsp_spacing_y, (0,3))
gbs_spacing.Add(stx_spacing_z, (0,4), flag=flag_labels)
gbs_spacing.Add(fsp_spacing_z, (0,5))
#----- buttons ------------------------
gbs_button = wx.GridBagSizer(2, 4)
btn_ok = self.btn_ok= wx.Button(p, wx.ID_OK)
btn_ok.SetDefault()
btn_cancel = wx.Button(p, wx.ID_CANCEL)
try:
gbs_button.Add(0, 0, (0,2))
except TypeError:
gbs_button.AddStretchSpacer((0,2))
gbs_button.Add(btn_cancel, (1,2))
gbs_button.Add(btn_ok, (1,3))
gbs_principal.Add(gbs, (0,0), flag = wx.ALL|wx.EXPAND)
gbs_principal.Add(gbs_spacing, (1,0), flag=wx.ALL|wx.EXPAND)
try:
gbs_principal.Add(0, 0, (2,0))
except TypeError:
gbs_principal.AddStretchSpacer((2,0))
gbs_principal.Add(gbs_button, (3,0), flag = wx.ALIGN_RIGHT)
box = wx.BoxSizer()
box.Add(gbs_principal, 1, wx.ALL|wx.EXPAND, 10)
p.SetSizer(box)
box.Fit(self)
self.Layout()
def bind_evts(self):
self.btn_ok.Bind(wx.EVT_BUTTON, self.OnOk)
def SetInterval(self, v):
self.interval = v
def OnOk(self, evt):
orient_selection = self.cb_orientation.GetSelection()
if(orient_selection == 1):
orientation = u"CORONAL"
elif(orient_selection == 2):
orientation = u"SAGITTAL"
else:
orientation = u"AXIAL"
values = [self.tx_name.GetValue(), orientation,\
self.fsp_spacing_x.GetValue(), self.fsp_spacing_y.GetValue(),\
self.fsp_spacing_z.GetValue(), self.interval]
Publisher.sendMessage('Open bitmap files', rec_data=values)
self.Close()
self.Destroy()
def BitmapNotSameSize():
dlg = wx.MessageDialog(None,_("All bitmaps files must be the same \n width and height size."), 'Error',\
wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
class PanelTargeFFill(wx.Panel):
def __init__(self, parent, ID=-1, style=wx.TAB_TRAVERSAL|wx.NO_BORDER):
wx.Panel.__init__(self, parent, ID, style=style)
self._init_gui()
def _init_gui(self):
self.target_2d = wx.RadioButton(self, -1, _(u"2D - Actual slice"), style=wx.RB_GROUP)
self.target_3d = wx.RadioButton(self, -1, _(u"3D - All slices"))
sizer = wx.GridBagSizer(5, 5)
try:
sizer.Add(0, 0, (0, 0))
except TypeError:
sizer.AddStretchSpacer((0, 0))
sizer.Add(self.target_2d, (1, 0), (1, 6), flag=wx.LEFT, border=5)
sizer.Add(self.target_3d, (2, 0), (1, 6), flag=wx.LEFT, border=5)
try:
sizer.Add(0, 0, (3, 0))
except TypeError:
sizer.AddStretchSpacer((3, 0))
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
class Panel2DConnectivity(wx.Panel):
def __init__(self, parent, ID=-1, show_orientation=False, style=wx.TAB_TRAVERSAL|wx.NO_BORDER):
wx.Panel.__init__(self, parent, ID, style=style)
self._init_gui(show_orientation)
def _init_gui(self, show_orientation):
self.conect2D_4 = wx.RadioButton(self, -1, "4", style=wx.RB_GROUP)
self.conect2D_8 = wx.RadioButton(self, -1, "8")
sizer = wx.GridBagSizer(5, 5)
try:
sizer.Add(0, 0, (0, 0))
except TypeError:
sizer.AddStretchSpacer((0, 0))
sizer.Add(wx.StaticText(self, -1, _(u"2D Connectivity")), (1, 0), (1, 6), flag=wx.LEFT, border=5)
sizer.Add(self.conect2D_4, (2, 0), flag=wx.LEFT, border=7)
sizer.Add(self.conect2D_8, (2, 1), flag=wx.LEFT, border=7)
try:
sizer.Add(0, 0, (3, 0))
except TypeError:
sizer.AddStretchSpacer((3, 0))
if show_orientation:
self.cmb_orientation = wx.ComboBox(self, -1, choices=(_(u"Axial"), _(u"Coronal"), _(u"Sagital")), style=wx.CB_READONLY)
self.cmb_orientation.SetSelection(0)
sizer.Add(wx.StaticText(self, -1, _(u"Orientation")), (4, 0), (1, 6), flag=wx.LEFT|wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, border=5)
sizer.Add(self.cmb_orientation, (5, 0), (1, 10), flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=7)
try:
sizer.Add(0, 0, (6, 0))
except TypeError:
sizer.AddStretchSpacer((6, 0))
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
def GetConnSelected(self):
if self.conect2D_4.GetValue():
return 4
else:
return 8
def GetOrientation(self):
dic_ori = {
_(u"Axial"): 'AXIAL',
_(u"Coronal"): 'CORONAL',
_(u"Sagital"): 'SAGITAL'
}
return dic_ori[self.cmb_orientation.GetStringSelection()]
class Panel3DConnectivity(wx.Panel):
def __init__(self, parent, ID=-1, style=wx.TAB_TRAVERSAL|wx.NO_BORDER):
wx.Panel.__init__(self, parent, ID, style=style)
self._init_gui()
def _init_gui(self):
self.conect3D_6 = wx.RadioButton(self, -1, "6", style=wx.RB_GROUP)
self.conect3D_18 = wx.RadioButton(self, -1, "18")
self.conect3D_26 = wx.RadioButton(self, -1, "26")
sizer = wx.GridBagSizer(5, 5)
try:
sizer.Add(0, 0, (0, 0))
except TypeError:
sizer.AddStretchSpacer((0, 0))
sizer.Add(wx.StaticText(self, -1, _(u"3D Connectivity")), (1, 0), (1, 6), flag=wx.LEFT, border=5)
sizer.Add(self.conect3D_6, (2, 0), flag=wx.LEFT, border=9)
sizer.Add(self.conect3D_18, (2, 1), flag=wx.LEFT, border=9)
sizer.Add(self.conect3D_26, (2, 2), flag=wx.LEFT, border=9)
try:
sizer.Add(0, 0, (3, 0))
except TypeError:
sizer.AddStretchSpacer((3, 0))
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
def GetConnSelected(self):
if self.conect3D_6.GetValue():
return 6
elif self.conect3D_18.GetValue():
return 18
else:
return 26
class PanelFFillThreshold(wx.Panel):
def __init__(self, parent, config, ID=-1, style=wx.TAB_TRAVERSAL|wx.NO_BORDER):
wx.Panel.__init__(self, parent, ID, style=style)
self.config = config
self._init_gui()
def _init_gui(self):
import invesalius.project as prj
project = prj.Project()
bound_min, bound_max = project.threshold_range
colour = [i*255 for i in const.MASK_COLOUR[0]]
colour.append(100)
self.threshold = grad.GradientCtrl(self, -1, int(bound_min),
int(bound_max), self.config.t0,
self.config.t1, colour)
# sizer
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.AddSpacer(5)
sizer.Add(self.threshold, 0, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
sizer.AddSpacer(5)
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
self.Bind(grad.EVT_THRESHOLD_CHANGING, self.OnSlideChanged, self.threshold)
self.Bind(grad.EVT_THRESHOLD_CHANGED, self.OnSlideChanged, self.threshold)
def OnSlideChanged(self, evt):
self.config.t0 = int(self.threshold.GetMinValue())
self.config.t1 = int(self.threshold.GetMaxValue())
print(self.config.t0, self.config.t1)
class PanelFFillDynamic(wx.Panel):
def __init__(self, parent, config, ID=-1, style=wx.TAB_TRAVERSAL|wx.NO_BORDER):
wx.Panel.__init__(self, parent, ID, style=style)
self.config = config
self._init_gui()
def _init_gui(self):
self.use_ww_wl = wx.CheckBox(self, -1, _(u"Use WW&WL"))
self.use_ww_wl.SetValue(self.config.use_ww_wl)
self.deviation_min = InvSpinCtrl(self, -1, value=self.config.dev_min, min_value=0, max_value=10000)
self.deviation_min.CalcSizeFromTextSize()
self.deviation_max = InvSpinCtrl(self, -1, value=self.config.dev_max, min_value=0, max_value=10000)
self.deviation_max.CalcSizeFromTextSize()
sizer = wx.GridBagSizer(5, 5)
try:
sizer.Add(0, 0, (0, 0))
except TypeError:
sizer.AddStretchSpacer((0, 0))
sizer.Add(self.use_ww_wl, (1, 0), (1, 6), flag=wx.LEFT, border=5)
try:
sizer.Add(0, 0, (2, 0))
except TypeError:
sizer.AddStretchSpacer((2, 0))
sizer.Add(wx.StaticText(self, -1, _(u"Deviation")), (3, 0), (1, 6), flag=wx.LEFT, border=5)
sizer.Add(wx.StaticText(self, -1, _(u"Min:")), (4, 0), flag=wx.ALIGN_CENTER_VERTICAL|wx.LEFT, border=9)
sizer.Add(self.deviation_min, (4, 1))
sizer.Add(wx.StaticText(self, -1, _(u"Max:")), (4, 2), flag=wx.ALIGN_CENTER_VERTICAL|wx.LEFT, border=9)
sizer.Add(self.deviation_max, (4, 3))
try:
sizer.Add(0, 0, (5, 0))
except TypeError:
sizer.AddStretchSpacer((5, 0))
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
self.use_ww_wl.Bind(wx.EVT_CHECKBOX, self.OnSetUseWWWL)
self.deviation_min.Bind(wx.EVT_SPINCTRL, self.OnSetDeviation)
self.deviation_max.Bind(wx.EVT_SPINCTRL, self.OnSetDeviation)
def OnSetUseWWWL(self, evt):
self.config.use_ww_wl = self.use_ww_wl.GetValue()
def OnSetDeviation(self, evt):
self.config.dev_max = self.deviation_max.GetValue()
self.config.dev_min = self.deviation_min.GetValue()
class PanelFFillConfidence(wx.Panel):
def __init__(self, parent, config, ID=-1, style=wx.TAB_TRAVERSAL|wx.NO_BORDER):
wx.Panel.__init__(self, parent, ID, style=style)
self.config = config
self._init_gui()
def _init_gui(self):
self.use_ww_wl = wx.CheckBox(self, -1, _(u"Use WW&WL"))
self.use_ww_wl.SetValue(self.config.use_ww_wl)
self.spin_mult = InvFloatSpinCtrl(self, -1,
value=self.config.confid_mult,
min_value=1.0, max_value=10.0,
increment=0.1, digits=1)
# style=wx.TE_PROCESS_TAB|wx.TE_PROCESS_ENTER,
# agwStyle=floatspin.FS_RIGHT)
self.spin_mult.CalcSizeFromTextSize()
self.spin_iters = InvSpinCtrl(self, -1, value=self.config.confid_iters, min_value=0, max_value=100)
self.spin_iters.CalcSizeFromTextSize()
sizer = wx.GridBagSizer(5, 5)
try:
sizer.Add(0, 0, (0, 0))
except TypeError:
sizer.AddStretchSpacer((0, 0))
sizer.Add(self.use_ww_wl, (1, 0), (1, 6), flag=wx.LEFT, border=5)
try:
sizer.Add(0, 0, (2, 0))
except TypeError:
sizer.AddStretchSpacer((2, 0))
sizer.Add(wx.StaticText(self, -1, _(u"Multiplier")), (3, 0), (1, 3), flag=wx.ALIGN_CENTER_VERTICAL|wx.LEFT, border=5)
sizer.Add(self.spin_mult, (3, 3), (1, 3))
sizer.Add(wx.StaticText(self, -1, _(u"Iterations")), (4, 0), (1, 3), flag=wx.ALIGN_CENTER_VERTICAL|wx.LEFT, border=5)
sizer.Add(self.spin_iters, (4, 3), (1, 2))
try:
sizer.Add(0, 0, (5, 0))
except TypeError:
sizer.AddStretchSpacer((5, 0))
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
self.use_ww_wl.Bind(wx.EVT_CHECKBOX, self.OnSetUseWWWL)
self.spin_mult.Bind(wx.EVT_SPINCTRL, self.OnSetMult)
self.spin_iters.Bind(wx.EVT_SPINCTRL, self.OnSetIters)
def OnSetUseWWWL(self, evt):
self.config.use_ww_wl = self.use_ww_wl.GetValue()
def OnSetMult(self, evt):
self.config.confid_mult = self.spin_mult.GetValue()
def OnSetIters(self, evt):
self.config.confid_iters = self.spin_iters.GetValue()
class PanelFFillProgress(wx.Panel):
def __init__(self, parent, ID=-1, style=wx.TAB_TRAVERSAL|wx.NO_BORDER):
wx.Panel.__init__(self, parent, ID, style=style)
self._init_gui()
def _init_gui(self):
self.progress = wx.Gauge(self, -1)
self.lbl_progress_caption = wx.StaticText(self, -1, _("Elapsed time:"))
self.lbl_time = wx.StaticText(self, -1, _("00:00:00"))
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(self.progress, 0, wx.EXPAND | wx.ALL, 5)
time_sizer = wx.BoxSizer(wx.HORIZONTAL)
time_sizer.Add(self.lbl_progress_caption, 0, wx.EXPAND, 0)
time_sizer.Add(self.lbl_time, 1, wx.EXPAND | wx.LEFT, 5)
main_sizer.Add(time_sizer, 0, wx.EXPAND | wx.ALL, 5)
self.SetSizer(main_sizer)
main_sizer.Fit(self)
main_sizer.SetSizeHints(self)
def StartTimer(self):
self.t0 = time.time()
def StopTimer(self):
fmt = "%H:%M:%S"
self.lbl_time.SetLabel(time.strftime(fmt, time.gmtime(time.time() - self.t0)))
self.progress.SetValue(0)
def Pulse(self):
fmt = "%H:%M:%S"
self.lbl_time.SetLabel(time.strftime(fmt, time.gmtime(time.time() - self.t0)))
self.progress.Pulse()
class FFillOptionsDialog(wx.Dialog):
def __init__(self, title, config):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1, title, style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP)
self.config = config
self._init_gui()
def _init_gui(self):
"""
Create the widgets.
"""
# Target
if sys.platform == "win32":
border_style = wx.SIMPLE_BORDER
else:
border_style = wx.SUNKEN_BORDER
self.panel_target = PanelTargeFFill(self, style=border_style|wx.TAB_TRAVERSAL)
self.panel2dcon = Panel2DConnectivity(self, style=border_style|wx.TAB_TRAVERSAL)
self.panel3dcon = Panel3DConnectivity(self, style=border_style|wx.TAB_TRAVERSAL)
if self.config.target == "2D":
self.panel_target.target_2d.SetValue(1)
self.panel2dcon.Enable(1)
self.panel3dcon.Enable(0)
else:
self.panel_target.target_3d.SetValue(1)
self.panel3dcon.Enable(1)
self.panel2dcon.Enable(0)
# Connectivity 2D
if self.config.con_2d == 8:
self.panel2dcon.conect2D_8.SetValue(1)
else:
self.panel2dcon.conect2D_4.SetValue(1)
self.config.con_2d = 4
# Connectivity 3D
if self.config.con_3d == 18:
self.panel3dcon.conect3D_18.SetValue(1)
elif self.config.con_3d == 26:
self.panel3dcon.conect3D_26.SetValue(1)
else:
self.panel3dcon.conect3D_6.SetValue(1)
self.close_btn = wx.Button(self, wx.ID_CLOSE)
# Sizer
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.AddSpacer(5)
sizer.Add(wx.StaticText(self, -1, _(u"Parameters")), flag=wx.LEFT, border=5)
sizer.AddSpacer(5)
sizer.Add(self.panel_target, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=7)
sizer.AddSpacer(5)
sizer.Add(self.panel2dcon, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=7)
sizer.AddSpacer(5)
sizer.Add(self.panel3dcon, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=7)
sizer.AddSpacer(5)
sizer.Add(self.close_btn, 0, flag=wx.ALIGN_RIGHT|wx.RIGHT, border=7)
sizer.AddSpacer(5)
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
self.close_btn.Bind(wx.EVT_BUTTON, self.OnBtnClose)
self.Bind(wx.EVT_RADIOBUTTON, self.OnSetRadio)
self.Bind(wx.EVT_CLOSE, self.OnClose)
def OnBtnClose(self, evt):
self.Close()
def OnSetRadio(self, evt):
# Target
if self.panel_target.target_2d.GetValue():
self.config.target = "2D"
self.panel2dcon.Enable(1)
self.panel3dcon.Enable(0)
else:
self.config.target = "3D"
self.panel3dcon.Enable(1)
self.panel2dcon.Enable(0)
# 2D
if self.panel2dcon.conect2D_4.GetValue():
self.config.con_2d = 4
elif self.panel2dcon.conect2D_8.GetValue():
self.config.con_2d = 8
# 3D
if self.panel3dcon.conect3D_6.GetValue():
self.config.con_3d = 6
elif self.panel3dcon.conect3D_18.GetValue():
self.config.con_3d = 18
elif self.panel3dcon.conect3D_26.GetValue():
self.config.con_3d = 26
def OnClose(self, evt):
print("ONCLOSE")
if self.config.dlg_visible:
Publisher.sendMessage('Disable style', style=const.SLICE_STATE_MASK_FFILL)
evt.Skip()
self.Destroy()
class SelectPartsOptionsDialog(wx.Dialog):
def __init__(self, config):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1, _(u"Select mask parts"), style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP)
self.config = config
self.SetReturnCode(wx.CANCEL)
self._init_gui()
def _init_gui(self):
self.target_name = wx.TextCtrl(self, -1)
self.target_name.SetValue(self.config.mask_name)
# Connectivity 3D
self.panel3dcon = Panel3DConnectivity(self)
if self.config.con_3d == 18:
self.panel3dcon.conect3D_18.SetValue(1)
elif self.config.con_3d == 26:
self.panel3dcon.conect3D_26.SetValue(1)
else:
self.panel3dcon.conect3D_6.SetValue(1)
self.btn_ok = wx.Button(self, wx.ID_OK)
self.btn_cancel = wx.Button(self, wx.ID_CANCEL)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.AddSpacer(5)
sizer.Add(wx.StaticText(self, -1, _(u"Target mask name")), flag=wx.LEFT, border=5)
sizer.AddSpacer(5)
sizer.Add(self.target_name, flag=wx.LEFT|wx.EXPAND|wx.RIGHT, border=9)
sizer.AddSpacer(5)
sizer.Add(self.panel3dcon, flag=wx.LEFT|wx.RIGHT|wx.EXPAND)
sizer.AddSpacer(5)
btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
btn_sizer.Add(self.btn_ok, 0)# flag=wx.ALIGN_RIGHT, border=5)
btn_sizer.Add(self.btn_cancel, 0, flag=wx.LEFT, border=5)
sizer.Add(btn_sizer, 0, flag=wx.ALIGN_RIGHT|wx.LEFT|wx.RIGHT, border=5)
sizer.AddSpacer(5)
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
self.btn_ok.Bind(wx.EVT_BUTTON, self.OnOk)
self.btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
self.target_name.Bind(wx.EVT_CHAR, self.OnChar)
self.Bind(wx.EVT_RADIOBUTTON, self.OnSetRadio)
self.Bind(wx.EVT_CLOSE, self.OnClose)
def OnOk(self, evt):
self.SetReturnCode(wx.OK)
self.Close()
def OnCancel(self, evt):
self.SetReturnCode(wx.CANCEL)
self.Close()
def OnChar(self, evt):
evt.Skip()
self.config.mask_name = self.target_name.GetValue()
def OnSetRadio(self, evt):
if self.panel3dcon.conect3D_6.GetValue():
self.config.con_3d = 6
elif self.panel3dcon.conect3D_18.GetValue():
self.config.con_3d = 18
elif self.panel3dcon.conect3D_26.GetValue():
self.config.con_3d = 26
def OnClose(self, evt):
if self.config.dlg_visible:
Publisher.sendMessage('Disable style', style=const.SLICE_STATE_SELECT_MASK_PARTS)
evt.Skip()
self.Destroy()
class FFillSegmentationOptionsDialog(wx.Dialog):
def __init__(self, config, ID=-1, title=_(u"Region growing"), style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), ID, title=title, style=style)
self.config = config
self._init_gui()
def _init_gui(self):
"""
Create the widgets.
"""
import invesalius.project as prj
# Target
if sys.platform == "win32":
border_style = wx.SIMPLE_BORDER
else:
border_style = wx.SUNKEN_BORDER
self.panel_target = PanelTargeFFill(self, style=border_style|wx.TAB_TRAVERSAL)
self.panel2dcon = Panel2DConnectivity(self, style=border_style|wx.TAB_TRAVERSAL)
self.panel3dcon = Panel3DConnectivity(self, style=border_style|wx.TAB_TRAVERSAL)
if self.config.target == "2D":
self.panel_target.target_2d.SetValue(1)
self.panel2dcon.Enable(1)
self.panel3dcon.Enable(0)
else:
self.panel_target.target_3d.SetValue(1)
self.panel3dcon.Enable(1)
self.panel2dcon.Enable(0)
# Connectivity 2D
if self.config.con_2d == 8:
self.panel2dcon.conect2D_8.SetValue(1)
else:
self.panel2dcon.conect2D_4.SetValue(1)
self.config.con_2d = 4
# Connectivity 3D
if self.config.con_3d == 18:
self.panel3dcon.conect3D_18.SetValue(1)
elif self.config.con_3d == 26:
self.panel3dcon.conect3D_26.SetValue(1)
else:
self.panel3dcon.conect3D_6.SetValue(1)
self.cmb_method = wx.ComboBox(self, -1, choices=(_(u"Dynamic"), _(u"Threshold"), _(u"Confidence")), style=wx.CB_READONLY)
if self.config.method == 'dynamic':
self.cmb_method.SetSelection(0)
elif self.config.method == 'threshold':
self.cmb_method.SetSelection(1)
elif self.config.method == 'confidence':
self.cmb_method.SetSelection(2)
self.panel_ffill_threshold = PanelFFillThreshold(self, self.config, -1, style=border_style|wx.TAB_TRAVERSAL)
self.panel_ffill_threshold.SetMinSize((250, -1))
self.panel_ffill_threshold.Hide()
self.panel_ffill_dynamic = PanelFFillDynamic(self, self.config, -1, style=border_style|wx.TAB_TRAVERSAL)
self.panel_ffill_dynamic.SetMinSize((250, -1))
self.panel_ffill_dynamic.Hide()
self.panel_ffill_confidence = PanelFFillConfidence(self, self.config, -1, style=border_style|wx.TAB_TRAVERSAL)
self.panel_ffill_confidence.SetMinSize((250, -1))
self.panel_ffill_confidence.Hide()
self.panel_ffill_progress = PanelFFillProgress(self, -1, style=wx.TAB_TRAVERSAL)
self.panel_ffill_progress.SetMinSize((250, -1))
# self.panel_ffill_progress.Hide()
self.close_btn = wx.Button(self, wx.ID_CLOSE)
# Sizer
sizer = wx.GridBagSizer(2, 2)
try:
sizer.Add(0, 0, (0, 0))
except TypeError:
sizer.AddStretchSpacer((0, 0))
sizer.Add(wx.StaticText(self, -1, _(u"Parameters")), (1, 0), (1, 6), flag=wx.LEFT, border=5)
try:
sizer.Add(0, 0, (2, 0))
except TypeError:
sizer.AddStretchSpacer((2, 0))
sizer.Add(self.panel_target, (3, 0), (1, 6), flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=7)
try:
sizer.Add(0, 0, (4, 0))
except TypeError:
sizer.AddStretchSpacer((4, 0))
sizer.Add(self.panel2dcon, (5, 0), (1, 6), flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=7)
try:
sizer.Add(0, 0, (6, 0))
except TypeError:
sizer.AddStretchSpacer((6, 0))
sizer.Add(self.panel3dcon, (7, 0), (1, 6), flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=7)
try:
sizer.Add(0, 0, (8, 0))
except TypeError:
sizer.AddStretchSpacer((8, 0))
sizer.Add(wx.StaticText(self, -1, _(u"Method")), (9, 0), (1, 1), flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL, border=7)
sizer.Add(self.cmb_method, (9, 1), (1, 5), flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=7)
try:
sizer.Add(0, 0, (10, 0))
except TypeError:
sizer.AddStretchSpacer((10, 0))
if self.config.method == 'dynamic':
self.cmb_method.SetSelection(0)
self.panel_ffill_dynamic.Show()
sizer.Add(self.panel_ffill_dynamic, (11, 0), (1, 6), flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=7)
elif self.config.method == 'confidence':
self.cmb_method.SetSelection(2)
self.panel_ffill_confidence.Show()
sizer.Add(self.panel_ffill_confidence, (11, 0), (1, 6), flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=7)
else:
self.cmb_method.SetSelection(1)
self.panel_ffill_threshold.Show()
sizer.Add(self.panel_ffill_threshold, (11, 0), (1, 6), flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=7)
self.config.method = 'threshold'
try:
sizer.Add(0, 0, (12, 0))
except TypeError:
sizer.AddStretchSpacer((12, 0))
sizer.Add(self.panel_ffill_progress, (13, 0), (1, 6), flag=wx.ALIGN_RIGHT|wx.RIGHT, border=5)
try:
sizer.Add(0, 0, (14, 0))
except TypeError:
sizer.AddStretchSpacer((14, 0))
sizer.Add(self.close_btn, (15, 0), (1, 6), flag=wx.ALIGN_RIGHT|wx.RIGHT, border=5)
try:
sizer.Add(0, 0, (16, 0))
except TypeError:
sizer.AddStretchSpacer((16, 0))
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
self.Bind(wx.EVT_RADIOBUTTON, self.OnSetRadio)
self.cmb_method.Bind(wx.EVT_COMBOBOX, self.OnSetMethod)
self.close_btn.Bind(wx.EVT_BUTTON, self.OnBtnClose)
self.Bind(wx.EVT_CLOSE, self.OnClose)
def OnSetRadio(self, evt):
# Target
if self.panel_target.target_2d.GetValue():
self.config.target = "2D"
self.panel2dcon.Enable(1)
self.panel3dcon.Enable(0)
else:
self.config.target = "3D"
self.panel3dcon.Enable(1)
self.panel2dcon.Enable(0)
# 2D
if self.panel2dcon.conect2D_4.GetValue():
self.config.con_2d = 4
elif self.panel2dcon.conect2D_8.GetValue():
self.config.con_2d = 8
# 3D
if self.panel3dcon.conect3D_6.GetValue():
self.config.con_3d = 6
elif self.panel3dcon.conect3D_18.GetValue():
self.config.con_3d = 18
elif self.panel3dcon.conect3D_26.GetValue():
self.config.con_3d = 26
def OnSetMethod(self, evt):
item_panel = self.GetSizer().FindItemAtPosition((11, 0)).GetWindow()
if self.cmb_method.GetSelection() == 0:
self.config.method = 'dynamic'
item_panel.Hide()
self.panel_ffill_dynamic.Show()
self.GetSizer().Replace(item_panel, self.panel_ffill_dynamic)
elif self.cmb_method.GetSelection() == 2:
self.config.method = 'confidence'
item_panel.Hide()
self.panel_ffill_confidence.Show()
self.GetSizer().Replace(item_panel, self.panel_ffill_confidence)
else:
self.config.method = 'threshold'
item_panel.Hide()
self.panel_ffill_threshold.Show()
self.GetSizer().Replace(item_panel, self.panel_ffill_threshold)
self.GetSizer().Fit(self)
self.Layout()
def OnBtnClose(self, evt):
self.Close()
def OnClose(self, evt):
if self.config.dlg_visible:
Publisher.sendMessage('Disable style', style=const.SLICE_STATE_MASK_FFILL)
evt.Skip()
self.Destroy()
class CropOptionsDialog(wx.Dialog):
def __init__(self, config, ID=-1, title=_(u"Crop mask"), style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP):
self.config = config
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), ID, title=title, style=style)
self._init_gui()
def UpdateValues(self, limits):
xi, xf, yi, yf, zi, zf = limits
self.tx_axial_i.SetValue(str(zi))
self.tx_axial_f.SetValue(str(zf))
self.tx_sagital_i.SetValue(str(xi))
self.tx_sagital_f.SetValue(str(xf))
self.tx_coronal_i.SetValue(str(yi))
self.tx_coronal_f.SetValue(str(yf))
def _init_gui(self):
p = wx.Panel(self, -1, style = wx.TAB_TRAVERSAL
| wx.CLIP_CHILDREN
| wx.FULL_REPAINT_ON_RESIZE)
gbs_principal = self.gbs = wx.GridBagSizer(4,1)
gbs = self.gbs = wx.GridBagSizer(3, 4)
flag_labels = wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL
txt_style = wx.TE_READONLY
stx_axial = wx.StaticText(p, -1, _(u"Axial:"))
self.tx_axial_i = tx_axial_i = wx.TextCtrl(p, -1, "", size=wx.Size(50,-1), style=txt_style)
stx_axial_t = wx.StaticText(p, -1, _(u" - "))
self.tx_axial_f = tx_axial_f = wx.TextCtrl(p, -1, "", size=wx.Size(50,-1), style=txt_style)
gbs.Add(stx_axial, (0,0), flag=flag_labels)
gbs.Add(tx_axial_i, (0,1))
gbs.Add(stx_axial_t, (0,2), flag=flag_labels)
gbs.Add(tx_axial_f, (0,3))
stx_sagital = wx.StaticText(p, -1, _(u"Sagital:"))
self.tx_sagital_i = tx_sagital_i = wx.TextCtrl(p, -1, "", size=wx.Size(50,-1), style=txt_style)
stx_sagital_t = wx.StaticText(p, -1, _(u" - "))
self.tx_sagital_f = tx_sagital_f = wx.TextCtrl(p, -1, "", size=wx.Size(50,-1), style=txt_style)
gbs.Add(stx_sagital, (1,0), flag=flag_labels)
gbs.Add(tx_sagital_i, (1,1))
gbs.Add(stx_sagital_t, (1,2), flag=flag_labels)
gbs.Add(tx_sagital_f, (1,3))
stx_coronal = wx.StaticText(p, -1, _(u"Coronal:"))
self.tx_coronal_i = tx_coronal_i = wx.TextCtrl(p, -1, "", size=wx.Size(50,-1), style=txt_style)
stx_coronal_t = wx.StaticText(p, -1, _(u" - "))
self.tx_coronal_f = tx_coronal_f = wx.TextCtrl(p, -1, "", size=wx.Size(50,-1), style=txt_style)
gbs.Add(stx_coronal, (2,0), flag=flag_labels)
gbs.Add(tx_coronal_i, (2,1))
gbs.Add(stx_coronal_t, (2,2), flag=flag_labels)
gbs.Add(tx_coronal_f, (2,3))
gbs_button = wx.GridBagSizer(2, 4)
btn_ok = self.btn_ok= wx.Button(p, wx.ID_OK)
btn_ok.SetDefault()
btn_cancel = wx.Button(p, wx.ID_CANCEL)
gbs_button.Add(btn_cancel, (0,0))
gbs_button.Add(btn_ok, (0,1))
gbs_principal.Add(gbs, (0,0), flag = wx.ALL|wx.EXPAND)
try:
gbs_principal.Add(0, 0, (1, 0))
gbs_principal.Add(0, 0, (2, 0))
except TypeError:
gbs_principal.AddStretchSpacer((1, 0))
gbs_principal.AddStretchSpacer((2, 0))
gbs_principal.Add(gbs_button, (3,0), flag = wx.ALIGN_RIGHT)
box = wx.BoxSizer()
box.Add(gbs_principal, 1, wx.ALL|wx.EXPAND, 10)
p.SetSizer(box)
box.Fit(p)
p.Layout()
sizer = wx.BoxSizer()
sizer.Add(p, 1, wx.EXPAND)
sizer.Fit(self)
self.Layout()
Publisher.subscribe(self.UpdateValues, 'Update crop limits into gui')
btn_ok.Bind(wx.EVT_BUTTON, self.OnOk)
btn_cancel.Bind(wx.EVT_BUTTON, self.OnClose)
self.Bind(wx.EVT_CLOSE, self.OnClose)
def OnOk(self, evt):
self.config.dlg_visible = False
Publisher.sendMessage('Crop mask')
Publisher.sendMessage('Disable style', style=const.SLICE_STATE_CROP_MASK)
evt.Skip()
def OnClose(self, evt):
self.config.dlg_visible = False
Publisher.sendMessage('Disable style', style=const.SLICE_STATE_CROP_MASK)
evt.Skip()
self.Destroy()
class FillHolesAutoDialog(wx.Dialog):
def __init__(self, title):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1, title, style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP)
self._init_gui()
def _init_gui(self):
if sys.platform == "win32":
border_style = wx.SIMPLE_BORDER
else:
border_style = wx.SUNKEN_BORDER
self.spin_size = InvSpinCtrl(self, -1, value=1000, min_value=1, max_value=1000000000)
self.panel_target = PanelTargeFFill(self, style=border_style|wx.TAB_TRAVERSAL)
self.panel2dcon = Panel2DConnectivity(self, show_orientation=True, style=border_style|wx.TAB_TRAVERSAL)
self.panel3dcon = Panel3DConnectivity(self, style=border_style|wx.TAB_TRAVERSAL)
self.panel2dcon.Enable(1)
self.panel3dcon.Enable(0)
self.panel_target.target_2d.SetValue(1)
self.panel2dcon.conect2D_4.SetValue(1)
self.panel3dcon.conect3D_6.SetValue(1)
self.apply_btn = wx.Button(self, wx.ID_APPLY)
self.close_btn = wx.Button(self, wx.ID_CLOSE)
# Sizer
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.AddSpacer(5)
sizer.Add(wx.StaticText(self, -1, _(u"Parameters")), flag=wx.LEFT, border=5)
sizer.AddSpacer(5)
sizer.Add(self.panel_target, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=7)
sizer.AddSpacer(5)
sizer.Add(self.panel2dcon, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=7)
sizer.AddSpacer(5)
sizer.Add(self.panel3dcon, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=7)
sizer.AddSpacer(5)
spin_sizer = wx.BoxSizer(wx.HORIZONTAL)
spin_sizer.Add(wx.StaticText(self, -1, _(u"Max hole size")), flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL, border=5)
spin_sizer.Add(self.spin_size, 0, flag=wx.LEFT|wx.RIGHT, border=5)
spin_sizer.Add(wx.StaticText(self, -1, _(u"voxels")), flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, border=5)
sizer.Add(spin_sizer, 0, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, border=7)
sizer.AddSpacer(5)
btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
btn_sizer.Add(self.apply_btn, 0)# flag=wx.ALIGN_RIGHT, border=5)
btn_sizer.Add(self.close_btn, 0, flag=wx.LEFT, border=5)
sizer.Add(btn_sizer, 0, flag=wx.ALIGN_RIGHT|wx.LEFT|wx.RIGHT, border=5)
sizer.AddSpacer(5)
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
self.apply_btn.Bind(wx.EVT_BUTTON, self.OnApply)
self.close_btn.Bind(wx.EVT_BUTTON, self.OnBtnClose)
self.Bind(wx.EVT_RADIOBUTTON, self.OnSetRadio)
def OnApply(self, evt):
if self.panel_target.target_2d.GetValue():
target = "2D"
conn = self.panel2dcon.GetConnSelected()
orientation = self.panel2dcon.GetOrientation()
else:
target = "3D"
conn = self.panel3dcon.GetConnSelected()
orientation = 'VOLUME'
parameters = {
'target': target,
'conn': conn,
'orientation': orientation,
'size': self.spin_size.GetValue(),
}
Publisher.sendMessage("Fill holes automatically", parameters=parameters)
def OnBtnClose(self, evt):
self.Close()
self.Destroy()
def OnSetRadio(self, evt):
# Target
if self.panel_target.target_2d.GetValue():
self.panel2dcon.Enable(1)
self.panel3dcon.Enable(0)
else:
self.panel3dcon.Enable(1)
self.panel2dcon.Enable(0)
class MaskDensityDialog(wx.Dialog):
def __init__(self, title):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1, _(u"Mask density"),
style=wx.DEFAULT_DIALOG_STYLE | wx.FRAME_FLOAT_ON_PARENT)
self._init_gui()
self._bind_events()
def _init_gui(self):
import invesalius.project as prj
project = prj.Project()
self.cmb_mask = wx.ComboBox(self, -1, choices=[], style=wx.CB_READONLY)
if project.mask_dict.values():
for mask in project.mask_dict.values():
self.cmb_mask.Append(mask.name, mask)
self.cmb_mask.SetValue(list(project.mask_dict.values())[0].name)
self.calc_button = wx.Button(self, -1, _(u'Calculate'))
self.mean_density = self._create_selectable_label_text('')
self.min_density = self._create_selectable_label_text('')
self.max_density = self._create_selectable_label_text('')
self.std_density = self._create_selectable_label_text('')
slt_mask_sizer = wx.FlexGridSizer(rows=1, cols=3, vgap=5, hgap=5)
slt_mask_sizer.AddMany([
(wx.StaticText(self, -1, _(u'Mask:'), style=wx.ALIGN_CENTER_VERTICAL), 0, wx.ALIGN_CENTRE),
(self.cmb_mask, 1, wx.EXPAND),
(self.calc_button, 0, wx.EXPAND),
])
values_sizer = wx.FlexGridSizer(rows=4, cols=2, vgap=5, hgap=5)
values_sizer.AddMany([
(wx.StaticText(self, -1, _(u'Mean:')), 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT),
(self.mean_density, 1, wx.EXPAND),
(wx.StaticText(self, -1, _(u'Minimun:')), 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT),
(self.min_density, 1, wx.EXPAND),
(wx.StaticText(self, -1, _(u'Maximun:')), 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT),
(self.max_density, 1, wx.EXPAND),
(wx.StaticText(self, -1, _(u'Standard deviation:')), 0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT),
(self.std_density, 1, wx.EXPAND),
])
sizer = wx.FlexGridSizer(rows=4, cols=1, vgap=5, hgap=5)
sizer.AddSpacer(5)
sizer.AddMany([
(slt_mask_sizer, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 5) ,
(values_sizer, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 5),
])
sizer.AddSpacer(5)
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
self.CenterOnScreen()
def _create_selectable_label_text(self, text):
label = wx.TextCtrl(self, -1, style=wx.TE_READONLY)
label.SetValue(text)
# label.SetBackgroundColour(self.GetBackgroundColour())
return label
def _bind_events(self):
self.calc_button.Bind(wx.EVT_BUTTON, self.OnCalcButton)
def OnCalcButton(self, evt):
from invesalius.data.slice_ import Slice
mask = self.cmb_mask.GetClientData(self.cmb_mask.GetSelection())
slc = Slice()
with futures.ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(slc.calc_image_density, mask)
for c in itertools.cycle(['', '.', '..', '...']):
s = _(u'Calculating ') + c
self.mean_density.SetValue(s)
self.min_density.SetValue(s)
self.max_density.SetValue(s)
self.std_density.SetValue(s)
self.Update()
self.Refresh()
if future.done():
break
time.sleep(0.1)
_min, _max, _mean, _std = future.result()
self.mean_density.SetValue(str(_mean))
self.min_density.SetValue(str(_min))
self.max_density.SetValue(str(_max))
self.std_density.SetValue(str(_std))
print(">>>> Area of mask", slc.calc_mask_area(mask))
class ObjectCalibrationDialog(wx.Dialog):
def __init__(self, tracker, pedal_connection):
self.tracker = tracker
self.pedal_connection = pedal_connection
self.trk_init, self.tracker_id = tracker.GetTrackerInfo()
self.obj_ref_id = 2
self.obj_name = None
self.polydata = None
self.use_default_object = False
self.object_fiducial_being_set = None
self.obj_fiducials = np.full([5, 3], np.nan)
self.obj_orients = np.full([5, 3], np.nan)
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1, _(u"Object calibration"), size=(450, 440),
style=wx.DEFAULT_DIALOG_STYLE | wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP)
self._init_gui()
self.LoadObject()
self.__bind_events()
def __bind_events(self):
Publisher.subscribe(self.SetObjectFiducial, 'Set object fiducial')
def _init_gui(self):
self.interactor = wxVTKRenderWindowInteractor(self, -1, size=self.GetSize())
self.interactor.Enable(1)
self.ren = vtk.vtkRenderer()
self.interactor.GetRenderWindow().AddRenderer(self.ren)
# Initialize list of buttons and txtctrls for wx objects
self.btns_coord = [None] * 5
self.text_actors = [None] * 5
self.ball_actors = [None] * 5
self.txt_coord = [list(), list(), list(), list(), list()]
# ComboBox for tracker reference mode
tooltip = wx.ToolTip(_(u"Choose the object reference mode"))
choice_ref = wx.ComboBox(self, -1, "", size=wx.Size(90, 23),
choices=const.REF_MODE, style=wx.CB_DROPDOWN | wx.CB_READONLY)
choice_ref.SetToolTip(tooltip)
choice_ref.Bind(wx.EVT_COMBOBOX, self.OnChooseReferenceMode)
choice_ref.SetSelection(1)
choice_ref.Enable(1)
if self.tracker_id == const.PATRIOT or self.tracker_id == const.ISOTRAKII:
self.obj_ref_id = 0
choice_ref.SetSelection(0)
choice_ref.Enable(0)
# ComboBox for sensor selection for FASTRAK
tooltip = wx.ToolTip(_(u"Choose the FASTRAK sensor port"))
choice_sensor = wx.ComboBox(self, -1, "", size=wx.Size(90, 23),
choices=const.FT_SENSOR_MODE, style=wx.CB_DROPDOWN | wx.CB_READONLY)
choice_sensor.SetSelection(0)
choice_sensor.SetToolTip(tooltip)
choice_sensor.Bind(wx.EVT_COMBOBOX, self.OnChoiceFTSensor)
if self.tracker_id in [const.FASTRAK, const.DEBUGTRACKRANDOM, const.DEBUGTRACKAPPROACH]:
choice_sensor.Show(True)
else:
choice_sensor.Show(False)
self.choice_sensor = choice_sensor
# Buttons to finish or cancel object registration
tooltip = wx.ToolTip(_(u"Registration done"))
# btn_ok = wx.Button(self, -1, _(u"Done"), size=wx.Size(90, 30))
btn_ok = wx.Button(self, wx.ID_OK, _(u"Done"), size=wx.Size(90, 30))
btn_ok.SetToolTip(tooltip)
extra_sizer = wx.FlexGridSizer(rows=3, cols=1, hgap=5, vgap=30)
extra_sizer.AddMany([choice_ref,
btn_ok,
choice_sensor])
# Push buttons for object fiducials
for object_fiducial in const.OBJECT_FIDUCIALS:
index = object_fiducial['fiducial_index']
label = object_fiducial['label']
button_id = object_fiducial['button_id']
tip = object_fiducial['tip']
ctrl = wx.ToggleButton(self, button_id, label=label, size=wx.Size(60, 23))
ctrl.SetToolTip(wx.ToolTip(tip))
ctrl.Bind(wx.EVT_TOGGLEBUTTON, partial(self.OnObjectFiducialButton, index, ctrl=ctrl))
self.btns_coord[index] = ctrl
for m in range(0, 5):
for n in range(0, 3):
self.txt_coord[m].append(wx.StaticText(self, -1, label='-',
style=wx.ALIGN_RIGHT, size=wx.Size(40, 23)))
coord_sizer = wx.GridBagSizer(hgap=20, vgap=5)
for m in range(0, 5):
coord_sizer.Add(self.btns_coord[m], pos=wx.GBPosition(m, 0))
for n in range(0, 3):
coord_sizer.Add(self.txt_coord[m][n], pos=wx.GBPosition(m, n + 1), flag=wx.TOP, border=5)
group_sizer = wx.FlexGridSizer(rows=1, cols=2, hgap=50, vgap=5)
group_sizer.AddMany([(coord_sizer, 0, wx.LEFT, 20),
(extra_sizer, 0, wx.LEFT, 10)])
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(self.interactor, 0, wx.EXPAND)
main_sizer.Add(group_sizer, 0,
wx.EXPAND|wx.GROW|wx.LEFT|wx.TOP|wx.RIGHT|wx.BOTTOM, 10)
self.SetSizer(main_sizer)
main_sizer.Fit(self)
def ObjectImportDialog(self):
msg = _("Would like to use InVesalius default object?")
if sys.platform == 'darwin':
dlg = wx.MessageDialog(None, "", msg,
wx.ICON_QUESTION | wx.YES_NO)
else:
dlg = wx.MessageDialog(None, msg,
"InVesalius 3",
wx.ICON_QUESTION | wx.YES_NO)
answer = dlg.ShowModal()
dlg.Destroy()
if answer == wx.ID_YES:
return 1
else: # answer == wx.ID_NO:
return 0
def LoadObject(self):
self.use_default_object = self.ObjectImportDialog()
if not self.use_default_object:
filename = ShowImportMeshFilesDialog()
if filename:
if filename.lower().endswith('.stl'):
reader = vtk.vtkSTLReader()
elif filename.lower().endswith('.ply'):
reader = vtk.vtkPLYReader()
elif filename.lower().endswith('.obj'):
reader = vtk.vtkOBJReader()
elif filename.lower().endswith('.vtp'):
reader = vtk.vtkXMLPolyDataReader()
else:
wx.MessageBox(_("File format not recognized by InVesalius"), _("Import surface error"))
return
else:
filename = os.path.join(inv_paths.OBJ_DIR, "magstim_fig8_coil.stl")
reader = vtk.vtkSTLReader()
# XXX: If the user cancels the dialog for importing the coil mesh file, the current behavior is to
# use the default object after all. A more logical behavior in that case would be to cancel the
# whole object calibration, but implementing that would need larger refactoring.
#
self.use_default_object = True
else:
filename = os.path.join(inv_paths.OBJ_DIR, "magstim_fig8_coil.stl")
reader = vtk.vtkSTLReader()
if _has_win32api:
self.obj_name = win32api.GetShortPathName(filename).encode(const.FS_ENCODE)
else:
self.obj_name = filename.encode(const.FS_ENCODE)
reader.SetFileName(self.obj_name)
reader.Update()
polydata = reader.GetOutput()
self.polydata = polydata
if polydata.GetNumberOfPoints() == 0:
wx.MessageBox(_("InVesalius was not able to import this surface"), _("Import surface error"))
transform = vtk.vtkTransform()
transform.RotateZ(90)
transform_filt = vtk.vtkTransformPolyDataFilter()
transform_filt.SetTransform(transform)
transform_filt.SetInputData(polydata)
transform_filt.Update()
normals = vtk.vtkPolyDataNormals()
normals.SetInputData(transform_filt.GetOutput())
normals.SetFeatureAngle(80)
normals.AutoOrientNormalsOn()
normals.Update()
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(normals.GetOutput())
mapper.ScalarVisibilityOff()
#mapper.ImmediateModeRenderingOn()
obj_actor = vtk.vtkActor()
obj_actor.SetMapper(mapper)
self.ball_actors[0], self.text_actors[0] = self.OnCreateObjectText('Left', (0,55,0))
self.ball_actors[1], self.text_actors[1] = self.OnCreateObjectText('Right', (0,-55,0))
self.ball_actors[2], self.text_actors[2] = self.OnCreateObjectText('Anterior', (23,0,0))
self.ren.AddActor(obj_actor)
self.ren.ResetCamera()
self.interactor.Render()
def OnCreateObjectText(self, name, coord):
ball_source = vtk.vtkSphereSource()
ball_source.SetRadius(3)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(ball_source.GetOutputPort())
ball_actor = vtk.vtkActor()
ball_actor.SetMapper(mapper)
ball_actor.SetPosition(coord)
ball_actor.GetProperty().SetColor(1, 0, 0)
textSource = vtk.vtkVectorText()
textSource.SetText(name)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(textSource.GetOutputPort())
tactor = vtk.vtkFollower()
tactor.SetMapper(mapper)
tactor.GetProperty().SetColor(1.0, 0.0, 0.0)
tactor.SetScale(5)
ball_position = ball_actor.GetPosition()
tactor.SetPosition(ball_position[0]+5, ball_position[1]+5, ball_position[2]+10)
self.ren.AddActor(tactor)
tactor.SetCamera(self.ren.GetActiveCamera())
self.ren.AddActor(ball_actor)
return ball_actor, tactor
def OnObjectFiducialButton(self, index, evt, ctrl):
if not self.tracker.IsTrackerInitialized():
ShowNavigationTrackerWarning(0, 'choose')
return
# TODO: The code below until the end of the function is essentially copy-paste from
# OnTrackerFiducials function in NeuronavigationPanel class. Probably the easiest
# way to deduplicate this would be to create a Fiducial class, which would contain
# this code just once.
#
# Do not allow several object fiducials to be set at the same time.
if self.object_fiducial_being_set is not None and self.object_fiducial_being_set != index:
ctrl.SetValue(False)
return
# Called when the button for setting the object fiducial is enabled and either pedal is pressed
# or the button is pressed again.
#
def set_fiducial_callback(state):
if state:
Publisher.sendMessage('Set object fiducial', fiducial_index=index)
ctrl.SetValue(False)
self.object_fiducial_being_set = None
if ctrl.GetValue():
self.object_fiducial_being_set = index
if self.pedal_connection is not None:
self.pedal_connection.add_callback(
name='fiducial',
callback=set_fiducial_callback,
remove_when_released=True,
)
else:
set_fiducial_callback(True)
if self.pedal_connection is not None:
self.pedal_connection.remove_callback(name='fiducial')
def SetObjectFiducial(self, fiducial_index):
coord, coord_raw = self.tracker.GetTrackerCoordinates(
# XXX: Always use static reference mode when getting the coordinates. This is what the
# code did previously, as well. At some point, it should probably be thought through
# if this is actually what we want or if it should be changed somehow.
#
ref_mode_id=const.STATIC_REF,
n_samples=const.CALIBRATION_TRACKER_SAMPLES,
)
# XXX: The condition below happens when setting the "fixed" coordinate in the object calibration.
# The case is not handled by GetTrackerCoordinates function, therefore redo some computation
# that is already done once by GetTrackerCoordinates, namely, invert the y-coordinate.
#
# (What is done here does not seem to be completely consistent with "always use static reference
# mode" principle above, but it's hard to come up with a simple change to increase the consistency
# and not change the function to the point of potentially breaking it.)
#
if self.obj_ref_id and fiducial_index == 4:
if self.tracker_id == const.ROBOT:
trck_init_robot = self.trk_init[1][0]
coord = trck_init_robot.Run()
else:
coord = coord_raw[self.obj_ref_id, :]
else:
coord = coord_raw[0, :]
if fiducial_index == 3:
coord = np.zeros([6,])
# Update text controls with tracker coordinates
if coord is not None or np.sum(coord) != 0.0:
self.obj_fiducials[fiducial_index, :] = coord[:3]
self.obj_orients[fiducial_index, :] = coord[3:]
for i in [0, 1, 2]:
self.txt_coord[fiducial_index][i].SetLabel(str(round(coord[i], 1)))
if self.text_actors[fiducial_index]:
self.text_actors[fiducial_index].GetProperty().SetColor(0.0, 1.0, 0.0)
self.ball_actors[fiducial_index].GetProperty().SetColor(0.0, 1.0, 0.0)
self.Refresh()
else:
ShowNavigationTrackerWarning(0, 'choose')
def OnChooseReferenceMode(self, evt):
# When ref mode is changed the tracker coordinates are set to nan
# This is for Polhemus FASTRAK wrapper, where the sensor attached to the object can be the stylus (Static
# reference - Selection 0 - index 0 for coordinates) or can be a 3rd sensor (Dynamic reference - Selection 1 -
# index 2 for coordinates)
# I use the index 2 directly here to send to the coregistration module where it is possible to access without
# any conditional statement the correct index of coordinates.
if evt.GetSelection() == 1:
self.obj_ref_id = 2
if self.tracker_id in [const.FASTRAK, const.DEBUGTRACKRANDOM, const.DEBUGTRACKAPPROACH]:
self.choice_sensor.Show(self.obj_ref_id)
else:
self.obj_ref_id = 0
self.choice_sensor.Show(self.obj_ref_id)
for m in range(0, 5):
self.obj_fiducials[m, :] = np.full([1, 3], np.nan)
self.obj_orients[m, :] = np.full([1, 3], np.nan)
for n in range(0, 3):
self.txt_coord[m][n].SetLabel('-')
# Used to update choice sensor controls
self.Layout()
def OnChoiceFTSensor(self, evt):
if evt.GetSelection():
self.obj_ref_id = 3
else:
self.obj_ref_id = 0
def GetValue(self):
return self.obj_fiducials, self.obj_orients, self.obj_ref_id, self.obj_name, self.polydata, self.use_default_object
class ICPCorregistrationDialog(wx.Dialog):
def __init__(self, nav_prop):
import invesalius.project as prj
self.m_change = nav_prop[0]
self.tracker = nav_prop[1]
self.obj_ref_id = 2
self.obj_name = None
self.obj_actor = None
self.polydata = None
self.m_icp = None
self.initial_focus = None
self.prev_error = None
self.final_error = None
self.icp_mode = 0
self.staticballs = []
self.point_coord = []
self.transformed_points = []
self.obj_fiducials = np.full([5, 3], np.nan)
self.obj_orients = np.full([5, 3], np.nan)
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1, _(u"Refine Corregistration"), size=(380, 440),
style=wx.DEFAULT_DIALOG_STYLE | wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP)
self.proj = prj.Project()
self._init_gui()
def _init_gui(self):
self.interactor = wxVTKRenderWindowInteractor(self, -1, size=self.GetSize())
self.interactor.Enable(1)
self.ren = vtk.vtkRenderer()
self.interactor.GetRenderWindow().AddRenderer(self.ren)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnUpdate, self.timer)
txt_surface = wx.StaticText(self, -1, _('Select the surface:'))
txt_mode = wx.StaticText(self, -1, _('Registration mode:'))
combo_surface_name = wx.ComboBox(self, -1, size=(210, 23),
style=wx.CB_DROPDOWN | wx.CB_READONLY)
# combo_surface_name.SetSelection(0)
if sys.platform != 'win32':
combo_surface_name.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)
combo_surface_name.Bind(wx.EVT_COMBOBOX, self.OnComboName)
for n in range(len(self.proj.surface_dict)):
combo_surface_name.Insert(str(self.proj.surface_dict[n].name), n)
self.combo_surface_name = combo_surface_name
init_surface = 0
combo_surface_name.SetSelection(init_surface)
self.surface = self.proj.surface_dict[init_surface].polydata
self.LoadActor()
tooltip = wx.ToolTip(_("Choose the registration mode:"))
choice_icp_method = wx.ComboBox(self, -1, "", size=(100, 23),
choices=([_("Affine"), _("Similarity"), _("RigidBody")]),
style=wx.CB_DROPDOWN|wx.CB_READONLY)
choice_icp_method.SetSelection(0)
choice_icp_method.SetToolTip(tooltip)
choice_icp_method.Bind(wx.EVT_COMBOBOX, self.OnChoiceICPMethod)
# Buttons to acquire and remove points
create_point = wx.Button(self, -1, label=_('Create point'))
create_point.Bind(wx.EVT_BUTTON, self.OnCreatePoint)
cont_point = wx.ToggleButton(self, -1, label=_('Continuous acquisition'))
cont_point.Bind(wx.EVT_TOGGLEBUTTON, partial(self.OnContinuousAcquisition, btn=cont_point))
self.cont_point = cont_point
btn_reset = wx.Button(self, -1, label=_('Remove points'))
btn_reset.Bind(wx.EVT_BUTTON, self.OnReset)
btn_apply_icp = wx.Button(self, -1, label=_('Apply registration'))
btn_apply_icp.Bind(wx.EVT_BUTTON, self.OnICP)
btn_apply_icp.Enable(False)
self.btn_apply_icp = btn_apply_icp
tooltip = wx.ToolTip(_(u"Refine done"))
btn_ok = wx.Button(self, wx.ID_OK, _(u"Done"))
btn_ok.SetToolTip(tooltip)
btn_ok.Enable(False)
self.btn_ok = btn_ok
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btn_cancel.SetHelpText("")
top_sizer = wx.FlexGridSizer(rows=2, cols=2, hgap=50, vgap=5)
top_sizer.AddMany([txt_surface, txt_mode,
combo_surface_name, choice_icp_method])
btn_acqui_sizer = wx.FlexGridSizer(rows=1, cols=3, hgap=15, vgap=15)
btn_acqui_sizer.AddMany([create_point, cont_point, btn_reset])
btn_ok_sizer = wx.FlexGridSizer(rows=1, cols=3, hgap=20, vgap=20)
btn_ok_sizer.AddMany([btn_apply_icp, btn_ok, btn_cancel])
btn_sizer = wx.FlexGridSizer(rows=2, cols=1, hgap=50, vgap=20)
btn_sizer.AddMany([(btn_acqui_sizer, 1, wx.ALIGN_CENTER_HORIZONTAL),
(btn_ok_sizer, 1, wx.ALIGN_RIGHT)])
self.progress = wx.Gauge(self, -1)
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(top_sizer, 0, wx.LEFT|wx.TOP|wx.BOTTOM, 10)
main_sizer.Add(self.interactor, 0, wx.EXPAND)
main_sizer.Add(btn_sizer, 0,
wx.EXPAND|wx.GROW|wx.LEFT|wx.TOP|wx.BOTTOM, 10)
main_sizer.Add(self.progress, 0, wx.EXPAND | wx.ALL, 5)
self.SetSizer(main_sizer)
main_sizer.Fit(self)
def LoadActor(self):
'''
Load the selected actor from the project (self.surface) into the scene
:return:
'''
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(self.surface)
mapper.ScalarVisibilityOff()
#mapper.ImmediateModeRenderingOn()
obj_actor = vtk.vtkActor()
obj_actor.SetMapper(mapper)
self.obj_actor = obj_actor
poses_recorded = vtku.Text()
poses_recorded.SetSize(const.TEXT_SIZE_LARGE)
poses_recorded.SetPosition((const.X, const.Y))
poses_recorded.ShadowOff()
poses_recorded.SetValue("Poses recorded: ")
collect_points = vtku.Text()
collect_points.SetSize(const.TEXT_SIZE_LARGE)
collect_points.SetPosition((const.X+0.35, const.Y))
collect_points.ShadowOff()
collect_points.SetValue("0")
self.collect_points = collect_points
self.ren.AddActor(obj_actor)
self.ren.AddActor(poses_recorded.actor)
self.ren.AddActor(collect_points.actor)
self.ren.ResetCamera()
self.interactor.Render()
def RemoveActor(self):
self.ren.RemoveAllViewProps()
self.point_coord = []
self.transformed_points = []
self.m_icp = None
self.SetProgress(0)
self.btn_apply_icp.Enable(False)
self.btn_ok.Enable(False)
self.ren.ResetCamera()
self.interactor.Render()
def GetCurrentCoord(self):
coord_raw, markers_flag = self.tracker.TrackerCoordinates.GetCoordinates()
coord, _ = dcr.corregistrate_dynamic((self.m_change, 0), coord_raw, const.DEFAULT_REF_MODE, [None, None])
return coord[:3]
def AddMarker(self, size, colour, coord):
"""
Points are rendered into the scene. These points give visual information about the registration.
:param size: value of the marker size
:type size: int
:param colour: RGB Color Code for the marker
:type colour: tuple (int(R),int(G),int(B))
:param coord: x, y, z of the marker
:type coord: np.ndarray
"""
x, y, z = coord[0], -coord[1], coord[2]
ball_ref = vtk.vtkSphereSource()
ball_ref.SetRadius(size)
ball_ref.SetCenter(x, y, z)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(ball_ref.GetOutputPort())
prop = vtk.vtkProperty()
prop.SetColor(colour[0:3])
#adding a new actor for the present ball
sphere_actor = vtk.vtkActor()
sphere_actor.SetMapper(mapper)
sphere_actor.SetProperty(prop)
self.ren.AddActor(sphere_actor)
self.point_coord.append([x, y, z])
self.collect_points.SetValue(str(int(self.collect_points.GetValue()) + 1))
self.interactor.Render()
if len(self.point_coord) >= 5 and self.btn_apply_icp.IsEnabled() is False:
self.btn_apply_icp.Enable(True)
if self.progress.GetValue() != 0:
self.SetProgress(0)
def SetProgress(self, progress):
self.progress.SetValue(progress * 100)
self.interactor.Render()
def vtkmatrix_to_numpy(self, matrix):
"""
Copies the elements of a vtkMatrix4x4 into a numpy array.
:param matrix: The matrix to be copied into an array.
:type matrix: vtk.vtkMatrix4x4
:rtype: numpy.ndarray
"""
m = np.ones((4, 4))
for i in range(4):
for j in range(4):
m[i, j] = matrix.GetElement(i, j)
return m
def SetCameraVolume(self, position):
"""
Positioning of the camera based on the acquired point
:param position: x, y, z of the last acquired point
:return:
"""
cam_focus = np.array([position[0], -position[1], position[2]])
cam = self.ren.GetActiveCamera()
if self.initial_focus is None:
self.initial_focus = np.array(cam.GetFocalPoint())
cam_pos0 = np.array(cam.GetPosition())
cam_focus0 = np.array(cam.GetFocalPoint())
v0 = cam_pos0 - cam_focus0
v0n = np.sqrt(inner1d(v0, v0))
v1 = (cam_focus - self.initial_focus)
v1n = np.sqrt(inner1d(v1, v1))
if not v1n:
v1n = 1.0
cam_pos = (v1/v1n)*v0n + cam_focus
cam.SetFocalPoint(cam_focus)
cam.SetPosition(cam_pos)
self.interactor.Render()
def ErrorEstimation(self, surface, points):
"""
Estimation of the average squared distance between the cloud of points to the closest mesh
:param surface: Surface polydata of the scene
:type surface: vtk.polydata
:param points: Cloud of points
:type points: np.ndarray
:return: mean distance
"""
cell_locator = vtk.vtkCellLocator()
cell_locator.SetDataSet(surface)
cell_locator.BuildLocator()
cellId = vtk.mutable(0)
c = [0.0, 0.0, 0.0]
subId = vtk.mutable(0)
d = vtk.mutable(0.0)
error = []
for i in range(len(points)):
cell_locator.FindClosestPoint(points[i], c, cellId, subId, d)
error.append(np.sqrt(float(d)))
return np.mean(error)
def OnComboName(self, evt):
surface_name = evt.GetString()
surface_index = evt.GetSelection()
self.surface = self.proj.surface_dict[surface_index].polydata
if self.obj_actor:
self.RemoveActor()
self.LoadActor()
def OnChoiceICPMethod(self, evt):
self.icp_mode = evt.GetSelection()
def OnContinuousAcquisition(self, evt=None, btn=None):
value = btn.GetValue()
if value:
self.timer.Start(500)
else:
self.timer.Stop()
def OnUpdate(self, evt):
current_coord = self.GetCurrentCoord()
self.AddMarker(3, (1, 0, 0), current_coord)
self.SetCameraVolume(current_coord)
def OnCreatePoint(self, evt):
current_coord = self.GetCurrentCoord()
self.AddMarker(3, (1, 0, 0), current_coord)
self.SetCameraVolume(current_coord)
def OnReset(self, evt):
if self.cont_point:
self.cont_point.SetValue(False)
self.OnContinuousAcquisition(evt=None, btn=self.cont_point)
self.RemoveActor()
self.LoadActor()
def OnICP(self, evt):
if self.cont_point:
self.cont_point.SetValue(False)
self.OnContinuousAcquisition(evt=None, btn=self.cont_point)
self.SetProgress(0.3)
time.sleep(1)
sourcePoints = np.array(self.point_coord)
sourcePoints_vtk = vtk.vtkPoints()
for i in range(len(sourcePoints)):
id0 = sourcePoints_vtk.InsertNextPoint(sourcePoints[i])
source = vtk.vtkPolyData()
source.SetPoints(sourcePoints_vtk)
icp = vtk.vtkIterativeClosestPointTransform()
icp.SetSource(source)
icp.SetTarget(self.surface)
self.SetProgress(0.5)
if self.icp_mode == 0:
print("Affine mode")
icp.GetLandmarkTransform().SetModeToAffine()
elif self.icp_mode == 1:
print("Similarity mode")
icp.GetLandmarkTransform().SetModeToSimilarity()
elif self.icp_mode == 2:
print("Rigid mode")
icp.GetLandmarkTransform().SetModeToRigidBody()
#icp.DebugOn()
icp.SetMaximumNumberOfIterations(1000)
icp.Modified()
icp.Update()
self.m_icp = self.vtkmatrix_to_numpy(icp.GetMatrix())
icpTransformFilter = vtk.vtkTransformPolyDataFilter()
icpTransformFilter.SetInputData(source)
icpTransformFilter.SetTransform(icp)
icpTransformFilter.Update()
transformedSource = icpTransformFilter.GetOutput()
for i in range(transformedSource.GetNumberOfPoints()):
p = [0, 0, 0]
transformedSource.GetPoint(i, p)
self.transformed_points.append(p)
point = vtk.vtkSphereSource()
point.SetCenter(p)
point.SetRadius(3)
point.SetPhiResolution(3)
point.SetThetaResolution(3)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(point.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
actor.GetProperty().SetColor((0,1,0))
self.ren.AddActor(actor)
self.prev_error = self.ErrorEstimation(self.surface, sourcePoints)
self.final_error = self.ErrorEstimation(self.surface, self.transformed_points)
self.interactor.Render()
self.SetProgress(1)
self.btn_ok.Enable(True)
def GetValue(self):
return self.m_icp, self.point_coord, self.transformed_points, self.prev_error, self.final_error
class SurfaceProgressWindow(object):
def __init__(self):
self.title = "InVesalius 3"
self.msg = _("Creating 3D surface ...")
self.style = wx.PD_APP_MODAL | wx.PD_APP_MODAL | wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME
self.dlg = wx.ProgressDialog(self.title,
self.msg,
parent=None,
style=self.style)
self.running = True
self.error = None
self.dlg.Show()
def WasCancelled(self):
# print("Cancelled?", self.dlg.WasCancelled())
return self.dlg.WasCancelled()
def Update(self, msg=None, value=None):
if msg is None:
self.dlg.Pulse()
else:
self.dlg.Pulse(msg)
def Close(self):
self.dlg.Destroy()
class GoToDialog(wx.Dialog):
def __init__(self, title=_("Go to slice ..."), init_orientation=const.AXIAL_STR):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1, title, style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP)
self._init_gui(init_orientation)
def _init_gui(self, init_orientation):
orientations = (
(_("Axial"), const.AXIAL_STR),
(_("Coronal"), const.CORONAL_STR),
(_("Sagital"), const.SAGITAL_STR),
)
self.goto_slice = wx.TextCtrl(self, -1, "")
self.goto_orientation = wx.ComboBox(self, -1, style=wx.CB_DROPDOWN|wx.CB_READONLY)
cb_init = 0
for n, orientation in enumerate(orientations):
self.goto_orientation.Append(*orientation)
if orientation[1] == init_orientation:
cb_init = n
self.goto_orientation.SetSelection(cb_init)
btn_ok = wx.Button(self, wx.ID_OK)
btn_ok.SetHelpText("")
btn_ok.SetDefault()
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btn_cancel.SetHelpText("")
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.AddButton(btn_cancel)
btnsizer.Realize()
main_sizer = wx.BoxSizer(wx.VERTICAL)
slice_sizer = wx.BoxSizer(wx.HORIZONTAL)
slice_sizer.Add(wx.StaticText(self, -1, _("Slice number"), style=wx.ALIGN_CENTER), 0, wx.ALIGN_CENTER|wx.RIGHT, 5)
slice_sizer.Add(self.goto_slice, 1, wx.EXPAND)
main_sizer.Add((5, 5))
main_sizer.Add(slice_sizer, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
main_sizer.Add((5, 5))
main_sizer.Add(self.goto_orientation, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
main_sizer.Add((5, 5))
main_sizer.Add(btnsizer, 0, wx.EXPAND)
main_sizer.Add((5, 5))
self.SetSizer(main_sizer)
main_sizer.Fit(self)
self.orientation = None
self.__bind_events()
btn_ok.Bind(wx.EVT_BUTTON, self.OnOk)
def __bind_events(self):
Publisher.subscribe(self.SetNewFocalPoint,'Cross focal point')
def OnOk(self, evt):
try:
slice_number = int(self.goto_slice.GetValue())
orientation = self.orientation = self.goto_orientation.GetClientData(self.goto_orientation.GetSelection())
Publisher.sendMessage(("Set scroll position", orientation), index=slice_number)
Publisher.sendMessage('Set Update cross pos')
except ValueError:
pass
self.Close()
def SetNewFocalPoint(self, coord, spacing):
newCoord = list(coord)
if self.orientation=='AXIAL':
newCoord[2] = int(self.goto_slice.GetValue())*spacing[2]
if self.orientation == 'CORONAL':
newCoord[1] = int(self.goto_slice.GetValue())*spacing[1]
if self.orientation == 'SAGITAL':
newCoord[0] = int(self.goto_slice.GetValue())*spacing[0]
Publisher.sendMessage('Update cross pos', coord = newCoord)
def Close(self):
wx.Dialog.Close(self)
self.Destroy()
class GoToDialogScannerCoord(wx.Dialog):
def __init__(self, title=_("Go to scanner coord...")):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1, title, style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP)
self._init_gui()
def _init_gui(self):
self.goto_sagital = wx.TextCtrl(self, size=(50,-1))
self.goto_coronal = wx.TextCtrl(self, size=(50,-1))
self.goto_axial = wx.TextCtrl(self, size=(50,-1))
btn_ok = wx.Button(self, wx.ID_OK)
btn_ok.SetHelpText("")
btn_ok.SetDefault()
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btn_cancel.SetHelpText("")
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.AddButton(btn_cancel)
btnsizer.Realize()
sizer_create = wx.FlexGridSizer(3, 2, 10, 10)
sizer_create.AddMany([(wx.StaticText(self, 1, _("Sagital coordinate:")), 1, wx.LEFT, 10), (self.goto_sagital, 1, wx.RIGHT, 10),
(wx.StaticText(self, 1, _("Coronal coordinate:")), 1, wx.LEFT, 10), (self.goto_coronal, 1, wx.RIGHT, 10),
(wx.StaticText(self, 1, _("Axial coordinate:")), 1, wx.LEFT, 10), (self.goto_axial, 1, wx.RIGHT, 10)])
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add((5, 5))
main_sizer.Add(sizer_create, proportion=3, flag=wx.CENTER, border=20)
main_sizer.Add(btnsizer, proportion=1, flag=wx.CENTER|wx.TOP, border=5)
main_sizer.Add((5, 5))
self.SetSizer(main_sizer)
main_sizer.Fit(self)
self.orientation = None
self.affine = np.identity(4)
self.__bind_events()
btn_ok.Bind(wx.EVT_BUTTON, self.OnOk)
def __bind_events(self):
Publisher.subscribe(self.SetNewFocalPoint, 'Cross focal point')
def SetNewFocalPoint(self, coord, spacing):
Publisher.sendMessage('Update cross pos', coord=self.result*spacing)
def OnOk(self, evt):
import invesalius.data.slice_ as slc
try:
point = [float(self.goto_sagital.GetValue()),
float(self.goto_coronal.GetValue()),
float(self.goto_axial.GetValue())]
# transformation from scanner coordinates to inv coord system
affine_inverse = np.linalg.inv(slc.Slice().affine)
self.result = np.dot(affine_inverse[:3, :3], np.transpose(point[0:3])) + affine_inverse[:3, 3]
self.result[1] = slc.Slice().GetMaxSliceNumber(const.CORONAL_STR) - self.result[1]
Publisher.sendMessage('Update status text in GUI', label=_("Calculating the transformation ..."))
Publisher.sendMessage('Set Update cross pos')
Publisher.sendMessage("Toggle Cross", id=const.SLICE_STATE_CROSS)
Publisher.sendMessage('Update status text in GUI', label=_("Ready"))
except ValueError:
pass
self.Close()
def Close(self):
wx.Dialog.Close(self)
self.Destroy()
class SetOptitrackconfigs(wx.Dialog):
def __init__(self, title=_("Setting Optitrack configs:")):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1, title, size=wx.Size(1000, 200),
style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP|wx.RESIZE_BORDER)
self._init_gui()
def _init_gui(self):
session = ses.Session()
last_optitrack_cal_dir = session.get('paths', 'last_optitrack_cal_dir', '')
last_optitrack_User_Profile_dir = session.get('paths', 'last_optitrack_User_Profile_dir', '')
if not last_optitrack_cal_dir:
last_optitrack_cal_dir = inv_paths.OPTITRACK_CAL_DIR
if not last_optitrack_User_Profile_dir:
last_optitrack_User_Profile_dir = inv_paths.OPTITRACK_USERPROFILE_DIR
self.dir_cal = wx.FilePickerCtrl(self, path=last_optitrack_cal_dir, style=wx.FLP_USE_TEXTCTRL | wx.FLP_SMALL,
wildcard="Cal files (*.cal)|*.cal", message="Select Calibration file")
row_cal = wx.BoxSizer(wx.VERTICAL)
row_cal.Add(wx.StaticText(self, wx.ID_ANY, "Select Calibration file"), 0, wx.TOP | wx.RIGHT, 5)
row_cal.Add(self.dir_cal, 0, wx.ALL | wx.CENTER | wx.EXPAND)
self.dir_UserProfile = wx.FilePickerCtrl(self, path=last_optitrack_User_Profile_dir, style=wx.FLP_USE_TEXTCTRL | wx.FLP_SMALL,
wildcard="User Profile files (*.motive)|*.motive", message="Select User Profile file")
row_userprofile = wx.BoxSizer(wx.VERTICAL)
row_userprofile.Add(wx.StaticText(self, wx.ID_ANY, "Select User Profile file"), 0, wx.TOP | wx.RIGHT, 5)
row_userprofile.Add(self.dir_UserProfile, 0, wx.ALL | wx.CENTER | wx.EXPAND)
btn_ok = wx.Button(self, wx.ID_OK)
btn_ok.SetHelpText("")
btn_ok.SetDefault()
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btn_cancel.SetHelpText("")
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.AddButton(btn_cancel)
btnsizer.Realize()
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add((5, 5))
main_sizer.Add(row_cal, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
main_sizer.Add((5, 5))
main_sizer.Add(row_userprofile, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
main_sizer.Add((15, 15))
main_sizer.Add(btnsizer, 0, wx.EXPAND)
main_sizer.Add((5, 5))
self.SetSizer(main_sizer)
main_sizer.Fit(self)
self.CenterOnParent()
def GetValue(self):
fn_cal = self.dir_cal.GetPath()
fn_userprofile = self.dir_UserProfile.GetPath()
if fn_cal and fn_userprofile:
session = ses.Session()
session['paths']['last_optitrack_cal_dir'] = self.dir_cal.GetPath()
session['paths']['last_optitrack_User_Profile_dir'] = self.dir_UserProfile.GetPath()
session.WriteSessionFile()
return fn_cal, fn_userprofile
class SetTrackerDeviceToRobot(wx.Dialog):
"""
Robot navigation requires a tracker device to tracker the head position and the object (coil) position.
A dialog pops up showing a combobox with all trackers but debugs and the robot itself (const.TRACKERS[:-3])
"""
def __init__(self, title=_("Setting tracker device:")):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1, title, size=wx.Size(1000, 200),
style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP|wx.RESIZE_BORDER)
self.tracker_id = const.DEFAULT_TRACKER
self._init_gui()
def _init_gui(self):
# ComboBox for spatial tracker device selection
tooltip = wx.ToolTip(_("Choose the tracking device"))
trackers = const.TRACKERS
if not ses.Session().debug:
del trackers[-3:]
tracker_options = [_("Select tracker:")] + trackers
choice_trck = wx.ComboBox(self, -1, "",
choices=tracker_options, style=wx.CB_DROPDOWN | wx.CB_READONLY)
choice_trck.SetToolTip(tooltip)
choice_trck.SetSelection(const.DEFAULT_TRACKER)
choice_trck.Bind(wx.EVT_COMBOBOX, partial(self.OnChoiceTracker, ctrl=choice_trck))
btn_ok = wx.Button(self, wx.ID_OK)
btn_ok.SetHelpText("")
btn_ok.SetDefault()
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btn_cancel.SetHelpText("")
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.AddButton(btn_cancel)
btnsizer.Realize()
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add((5, 5))
main_sizer.Add(choice_trck, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
main_sizer.Add((15, 15))
main_sizer.Add(btnsizer, 0, wx.EXPAND)
main_sizer.Add((5, 5))
self.SetSizer(main_sizer)
main_sizer.Fit(self)
self.CenterOnParent()
def OnChoiceTracker(self, evt, ctrl):
choice = evt.GetSelection()
self.tracker_id = choice
def GetValue(self):
return self.tracker_id
class SetRobotIP(wx.Dialog):
def __init__(self, title=_("Setting Robot IP")):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1, title, size=wx.Size(1000, 200),
style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP|wx.RESIZE_BORDER)
self.robot_ip = None
self._init_gui()
def _init_gui(self):
# ComboBox for spatial tracker device selection
tooltip = wx.ToolTip(_("Choose or type the robot IP"))
robot_ip_options = [_("Select robot IP:")] + const.ROBOT_ElFIN_IP
choice_IP = wx.ComboBox(self, -1, "",
choices=robot_ip_options, style=wx.CB_DROPDOWN | wx.TE_PROCESS_ENTER)
choice_IP.SetToolTip(tooltip)
choice_IP.SetSelection(const.DEFAULT_TRACKER)
choice_IP.Bind(wx.EVT_COMBOBOX, partial(self.OnChoiceIP, ctrl=choice_IP))
choice_IP.Bind(wx.EVT_TEXT, partial(self.OnTxt_Ent, ctrl=choice_IP))
btn_ok = wx.Button(self, wx.ID_OK)
btn_ok.SetHelpText("")
btn_ok.SetDefault()
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btn_cancel.SetHelpText("")
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.AddButton(btn_cancel)
btnsizer.Realize()
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add((5, 5))
main_sizer.Add(choice_IP, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
main_sizer.Add((15, 15))
main_sizer.Add(btnsizer, 0, wx.EXPAND)
main_sizer.Add((5, 5))
self.SetSizer(main_sizer)
main_sizer.Fit(self)
self.CenterOnParent()
def OnTxt_Ent(self, evt, ctrl):
self.robot_ip = str(ctrl.GetValue())
def OnChoiceIP(self, evt, ctrl):
self.robot_ip = ctrl.GetStringSelection()
def GetValue(self):
return self.robot_ip
class CreateTransformationMatrixRobot(wx.Dialog):
def __init__(self, tracker, title=_("Create transformation matrix to robot space")):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1, title, #size=wx.Size(1000, 200),
style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP|wx.RESIZE_BORDER)
'''
M_robot_2_tracker is created by an affine transformation. Robot TCP should be calibrated to the center of the tracker marker
'''
#TODO: make aboutbox
self.tracker_coord = []
self.tracker_angles = []
self.robot_coord = []
self.robot_angles = []
self.tracker = tracker
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnUpdate, self.timer)
self._init_gui()
def _init_gui(self):
# Buttons to acquire and remove points
txt_acquisition = wx.StaticText(self, -1, _('Poses acquisition for robot registration:'))
btn_create_point = wx.Button(self, -1, label=_('Single'))
btn_create_point.Bind(wx.EVT_BUTTON, self.OnCreatePoint)
btn_cont_point = wx.ToggleButton(self, -1, label=_('Continuous'))
btn_cont_point.Bind(wx.EVT_TOGGLEBUTTON, partial(self.OnContinuousAcquisition, btn=btn_cont_point))
self.btn_cont_point = btn_cont_point
txt_number = wx.StaticText(self, -1, _('0'))
txt_recorded = wx.StaticText(self, -1, _('Poses recorded'))
self.txt_number = txt_number
btn_reset = wx.Button(self, -1, label=_('Reset'))
btn_reset.Bind(wx.EVT_BUTTON, self.OnReset)
btn_apply_reg = wx.Button(self, -1, label=_('Apply'))
btn_apply_reg.Bind(wx.EVT_BUTTON, self.OnApply)
btn_apply_reg.Enable(False)
self.btn_apply_reg = btn_apply_reg
# Buttons to save and load
txt_file = wx.StaticText(self, -1, _('Registration file'))
btn_save = wx.Button(self, -1, label=_('Save'), size=wx.Size(65, 23))
btn_save.Bind(wx.EVT_BUTTON, self.OnSaveReg)
btn_save.Enable(False)
self.btn_save = btn_save
btn_load = wx.Button(self, -1, label=_('Load'), size=wx.Size(65, 23))
btn_load.Bind(wx.EVT_BUTTON, self.OnLoadReg)
# Create a horizontal sizers
border = 1
acquisition = wx.BoxSizer(wx.HORIZONTAL)
acquisition.AddMany([(btn_create_point, 1, wx.EXPAND | wx.GROW | wx.TOP | wx.RIGHT | wx.LEFT, border),
(btn_cont_point, 1, wx.ALL | wx.EXPAND | wx.GROW, border)])
txt_pose = wx.BoxSizer(wx.HORIZONTAL)
txt_pose.AddMany([(txt_number, 1, wx.LEFT, 50),
(txt_recorded, 1, wx.LEFT, border)])
apply_reset = wx.BoxSizer(wx.HORIZONTAL)
apply_reset.AddMany([(btn_reset, 1, wx.EXPAND | wx.GROW | wx.TOP | wx.RIGHT | wx.LEFT, border),
(btn_apply_reg, 1, wx.ALL | wx.EXPAND | wx.GROW, border)])
save_load = wx.BoxSizer(wx.HORIZONTAL)
save_load.AddMany([(btn_save, 1, wx.EXPAND | wx.GROW | wx.TOP | wx.RIGHT | wx.LEFT, border),
(btn_load, 1, wx.ALL | wx.EXPAND | wx.GROW, border)])
btn_ok = wx.Button(self, wx.ID_OK)
btn_ok.SetHelpText("")
btn_ok.SetDefault()
btn_ok.Enable(False)
self.btn_ok = btn_ok
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btn_cancel.SetHelpText("")
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.AddButton(btn_cancel)
btnsizer.Realize()
# Add line sizers into main sizer
border = 10
border_last = 10
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, border)
main_sizer.Add(txt_acquisition, 0, wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_HORIZONTAL , border)
main_sizer.Add(acquisition, 0, wx.GROW | wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border)
main_sizer.Add(txt_pose, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.TOP | wx.BOTTOM, border)
main_sizer.Add(apply_reset, 0, wx.GROW | wx.EXPAND | wx.LEFT | wx.RIGHT , border_last)
main_sizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, border)
main_sizer.Add(txt_file, 0, wx.GROW | wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border/2)
main_sizer.Add(save_load, 0, wx.GROW | wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border)
main_sizer.Add(wx.StaticLine(self, -1), 0, wx.EXPAND | wx.TOP | wx.BOTTOM, border)
main_sizer.Add(btnsizer, 0, wx.GROW | wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, border)
main_sizer.Fit(self)
self.SetSizer(main_sizer)
self.Update()
main_sizer.Fit(self)
self.CenterOnParent()
def affine_correg(self, tracker, robot):
m_change = tr.affine_matrix_from_points(robot[:].T, tracker[:].T,
shear=False, scale=False, usesvd=False)
return m_change
def OnContinuousAcquisition(self, evt=None, btn=None):
value = btn.GetValue()
if value:
self.timer.Start(500)
else:
self.timer.Stop()
def OnUpdate(self, evt):
self.OnCreatePoint(evt=None)
def OnCreatePoint(self, evt):
coord_raw, markers_flag = self.tracker.TrackerCoordinates.GetCoordinates()
#robot thread is not initialized yet
coord_raw_robot = self.tracker.trk_init[0][1][0].Run()
coord_raw_tracker_obj = coord_raw[3]
if markers_flag[2]:
self.tracker_coord.append(coord_raw_tracker_obj[:3])
self.tracker_angles.append(coord_raw_tracker_obj[3:])
self.robot_coord.append(coord_raw_robot[:3])
self.robot_angles.append(coord_raw_robot[3:])
self.txt_number.SetLabel(str(int(self.txt_number.GetLabel())+1))
else:
print('Cannot detect the coil markers, pls try again')
if len(self.tracker_coord) >= 3:
self.btn_apply_reg.Enable(True)
def OnReset(self, evt):
if self.btn_cont_point:
self.btn_cont_point.SetValue(False)
self.OnContinuousAcquisition(evt=None, btn=self.btn_cont_point)
self.tracker_coord = []
self.tracker_angles = []
self.robot_coord = []
self.robot_angles = []
self.M_tracker_2_robot = []
self.txt_number.SetLabel('0')
self.btn_apply_reg.Enable(False)
self.btn_save.Enable(False)
self.btn_ok.Enable(False)
def OnApply(self, evt):
if self.btn_cont_point:
self.btn_cont_point.SetValue(False)
self.OnContinuousAcquisition(evt=None, btn=self.btn_cont_point)
tracker_coord = np.array(self.tracker_coord)
robot_coord = np.array(self.robot_coord)
M_robot_2_tracker = self.affine_correg(tracker_coord, robot_coord)
M_tracker_2_robot = tr.inverse_matrix(M_robot_2_tracker)
self.M_tracker_2_robot = M_tracker_2_robot
self.btn_save.Enable(True)
self.btn_ok.Enable(True)
#TODO: make a colored circle to sinalize that the transformation was made (green) (red if not)
def OnSaveReg(self, evt):
filename = ShowLoadSaveDialog(message=_(u"Save robot transformation file as..."),
wildcard=_("Robot transformation files (*.rbtf)|*.rbtf"),
style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
default_filename="robottransform.rbtf", save_ext="rbtf")
if filename:
if self.M_tracker_2_robot is not None:
with open(filename, 'w', newline='') as file:
writer = csv.writer(file, delimiter='\t')
writer.writerows(self.M_tracker_2_robot)
def OnLoadReg(self, evt):
filename = ShowLoadSaveDialog(message=_(u"Load robot transformation"),
wildcard=_("Robot transformation files (*.rbtf)|*.rbtf"))
if filename:
with open(filename, 'r') as file:
reader = csv.reader(file, delimiter='\t')
content = [row for row in reader]
self.M_tracker_2_robot = np.vstack(list(np.float_(content)))
print("Matrix tracker to robot:", self.M_tracker_2_robot)
self.btn_ok.Enable(True)
def GetValue(self):
return self.M_tracker_2_robot
class SetNDIconfigs(wx.Dialog):
def __init__(self, title=_("Setting NDI polaris configs:")):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1, title, size=wx.Size(1000, 200),
style=wx.DEFAULT_DIALOG_STYLE|wx.FRAME_FLOAT_ON_PARENT|wx.STAY_ON_TOP|wx.RESIZE_BORDER)
self._init_gui()
def serial_ports(self):
"""
Lists serial port names and pre-select the description containing NDI
"""
import serial.tools.list_ports
ports = serial.tools.list_ports.comports()
if sys.platform.startswith('win'):
port_list = []
desc_list = []
for port, desc, hwid in sorted(ports):
port_list.append(port)
desc_list.append(desc)
port_selec = [i for i, e in enumerate(desc_list) if 'NDI' in e]
else:
raise EnvironmentError('Unsupported platform')
#print("Here is the chosen port: {} with id {}".format(port_selec[0], port_selec[1]))
return port_list, port_selec
def _init_gui(self):
com_ports = wx.ComboBox(self, -1, style=wx.CB_DROPDOWN|wx.CB_READONLY)
com_ports.Bind(wx.EVT_COMBOBOX, partial(self.OnChoicePort, ctrl=com_ports))
row_com = wx.BoxSizer(wx.VERTICAL)
row_com.Add(wx.StaticText(self, wx.ID_ANY, "Select the COM port"), 0, wx.TOP|wx.RIGHT,5)
row_com.Add(com_ports, 0, wx.EXPAND)
port_list, port_selec = self.serial_ports()
com_ports.Append(port_list)
if port_selec:
com_ports.SetSelection(port_selec[0])
self.com_ports = com_ports
session = ses.Session()
last_ndi_probe_marker = session.get('paths', 'last_ndi_probe_marker', '')
last_ndi_ref_marker = session.get('paths', 'last_ndi_ref_marker', '')
last_ndi_obj_marker = session.get('paths', 'last_ndi_obj_marker', '')
if not last_ndi_probe_marker:
last_ndi_probe_marker = inv_paths.NDI_MAR_DIR_PROBE
if not last_ndi_ref_marker:
last_ndi_ref_marker = inv_paths.NDI_MAR_DIR_REF
if not last_ndi_obj_marker:
last_ndi_obj_marker = inv_paths.NDI_MAR_DIR_OBJ
self.dir_probe = wx.FilePickerCtrl(self, path=last_ndi_probe_marker, style=wx.FLP_USE_TEXTCTRL|wx.FLP_SMALL,
wildcard="Rom files (*.rom)|*.rom", message="Select probe's rom file")
row_probe = wx.BoxSizer(wx.VERTICAL)
row_probe.Add(wx.StaticText(self, wx.ID_ANY, "Set probe's rom file"), 0, wx.TOP|wx.RIGHT, 5)
row_probe.Add(self.dir_probe, 0, wx.ALL | wx.CENTER | wx.EXPAND)
self.dir_ref = wx.FilePickerCtrl(self, path=last_ndi_ref_marker, style=wx.FLP_USE_TEXTCTRL|wx.FLP_SMALL,
wildcard="Rom files (*.rom)|*.rom", message="Select reference's rom file")
row_ref = wx.BoxSizer(wx.VERTICAL)
row_ref.Add(wx.StaticText(self, wx.ID_ANY, "Set reference's rom file"), 0, wx.TOP | wx.RIGHT, 5)
row_ref.Add(self.dir_ref, 0, wx.ALL | wx.CENTER | wx.EXPAND)
self.dir_obj = wx.FilePickerCtrl(self, path=last_ndi_obj_marker, style=wx.FLP_USE_TEXTCTRL|wx.FLP_SMALL,
wildcard="Rom files (*.rom)|*.rom", message="Select object's rom file")
#self.dir_probe.Bind(wx.EVT_FILEPICKER_CHANGED, self.Selected)
row_obj = wx.BoxSizer(wx.VERTICAL)
row_obj.Add(wx.StaticText(self, wx.ID_ANY, "Set object's rom file"), 0, wx.TOP|wx.RIGHT, 5)
row_obj.Add(self.dir_obj, 0, wx.ALL | wx.CENTER | wx.EXPAND)
btn_ok = wx.Button(self, wx.ID_OK)
btn_ok.SetHelpText("")
btn_ok.SetDefault()
if not port_selec:
btn_ok.Enable(False)
self.btn_ok = btn_ok
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btn_cancel.SetHelpText("")
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.AddButton(btn_cancel)
btnsizer.Realize()
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add((5, 5))
main_sizer.Add(row_com, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
main_sizer.Add((5, 5))
main_sizer.Add(row_probe, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
main_sizer.Add((5, 5))
main_sizer.Add(row_ref, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
main_sizer.Add((5, 5))
main_sizer.Add(row_obj, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, 5)
main_sizer.Add((15, 15))
main_sizer.Add(btnsizer, 0, wx.EXPAND)
main_sizer.Add((5, 5))
self.SetSizer(main_sizer)
main_sizer.Fit(self)
self.CenterOnParent()
def OnChoicePort(self, evt, ctrl):
self.btn_ok.Enable(True)
def GetValue(self):
fn_probe = self.dir_probe.GetPath().encode(const.FS_ENCODE)
fn_ref = self.dir_ref.GetPath().encode(const.FS_ENCODE)
fn_obj = self.dir_obj.GetPath().encode(const.FS_ENCODE)
if fn_probe and fn_ref and fn_obj:
session = ses.Session()
session['paths']['last_ndi_probe_marker'] = self.dir_probe.GetPath()
session['paths']['last_ndi_ref_marker'] = self.dir_ref.GetPath()
session['paths']['last_ndi_obj_marker'] = self.dir_obj.GetPath()
session.WriteSessionFile()
return self.com_ports.GetString(self.com_ports.GetSelection()).encode(const.FS_ENCODE), fn_probe, fn_ref, fn_obj
class SetCOMPort(wx.Dialog):
def __init__(self, select_baud_rate, title=_("Select COM port")):
wx.Dialog.__init__(self, wx.GetApp().GetTopWindow(), -1, title, style=wx.DEFAULT_DIALOG_STYLE | wx.FRAME_FLOAT_ON_PARENT | wx.STAY_ON_TOP)
self.select_baud_rate = select_baud_rate
self._init_gui()
def serial_ports(self):
"""
Lists serial port names
"""
import serial.tools.list_ports
if sys.platform.startswith('win'):
ports = ([comport.device for comport in serial.tools.list_ports.comports()])
else:
raise EnvironmentError('Unsupported platform')
return ports
def _init_gui(self):
# COM port selection
ports = self.serial_ports()
self.com_port_dropdown = wx.ComboBox(self, -1, choices=ports, style=wx.CB_DROPDOWN | wx.CB_READONLY)
self.com_port_dropdown.SetSelection(0)
com_port_text_and_dropdown = wx.BoxSizer(wx.VERTICAL)
com_port_text_and_dropdown.Add(wx.StaticText(self, wx.ID_ANY, "COM port"), 0, wx.TOP | wx.RIGHT,5)
com_port_text_and_dropdown.Add(self.com_port_dropdown, 0, wx.EXPAND)
# Baud rate selection
if self.select_baud_rate:
baud_rates_as_strings = [str(baud_rate) for baud_rate in const.BAUD_RATES]
self.baud_rate_dropdown = wx.ComboBox(self, -1, choices=baud_rates_as_strings, style=wx.CB_DROPDOWN | wx.CB_READONLY)
self.baud_rate_dropdown.SetSelection(const.BAUD_RATE_DEFAULT_SELECTION)
baud_rate_text_and_dropdown = wx.BoxSizer(wx.VERTICAL)
baud_rate_text_and_dropdown.Add(wx.StaticText(self, wx.ID_ANY, "Baud rate"), 0, wx.TOP | wx.RIGHT,5)
baud_rate_text_and_dropdown.Add(self.baud_rate_dropdown, 0, wx.EXPAND)
# OK and Cancel buttons
btn_ok = wx.Button(self, wx.ID_OK)
btn_ok.SetHelpText("")
btn_ok.SetDefault()
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btn_cancel.SetHelpText("")
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.AddButton(btn_cancel)
btnsizer.Realize()
# Set up the main sizer
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add((5, 5))
main_sizer.Add(com_port_text_and_dropdown, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
if self.select_baud_rate:
main_sizer.Add((5, 5))
main_sizer.Add(baud_rate_text_and_dropdown, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 5)
main_sizer.Add((5, 5))
main_sizer.Add(btnsizer, 0, wx.EXPAND)
main_sizer.Add((5, 5))
self.SetSizer(main_sizer)
main_sizer.Fit(self)
self.CenterOnParent()
def GetCOMPort(self):
com_port = self.com_port_dropdown.GetString(self.com_port_dropdown.GetSelection())
return com_port
def GetBaudRate(self):
if not self.select_baud_rate:
return None
baud_rate = self.baud_rate_dropdown.GetString(self.baud_rate_dropdown.GetSelection())
return baud_rate
class ManualWWWLDialog(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(self, parent, -1, _("Set WW&WL manually"))
self._init_gui()
def _init_gui(self):
import invesalius.data.slice_ as slc
ww = slc.Slice().window_width
wl = slc.Slice().window_level
self.txt_wl = wx.TextCtrl(self, -1, str(int(wl)))
wl_sizer = wx.BoxSizer(wx.HORIZONTAL)
wl_sizer.Add(wx.StaticText(self, -1, _("Window Level")), 0, wx.ALIGN_CENTER_VERTICAL)
wl_sizer.Add(self.txt_wl, 1, wx.ALL | wx.EXPAND, 5)
wl_sizer.Add(wx.StaticText(self, -1, _("WL")), 0, wx.ALIGN_CENTER_VERTICAL)
self.txt_ww = wx.TextCtrl(self, -1, str(int(ww)))
ww_sizer = wx.BoxSizer(wx.HORIZONTAL)
ww_sizer.Add(wx.StaticText(self, -1, _("Window Width")), 0, wx.ALIGN_CENTER_VERTICAL)
ww_sizer.Add(self.txt_ww, 1, wx.ALL | wx.EXPAND, 5)
ww_sizer.Add(wx.StaticText(self, -1, _("WW")), 0, wx.ALIGN_CENTER_VERTICAL)
btn_ok = wx.Button(self, wx.ID_OK)
btn_cancel = wx.Button(self, wx.ID_CANCEL)
btnsizer = wx.StdDialogButtonSizer()
btnsizer.AddButton(btn_ok)
btnsizer.AddButton(btn_cancel)
btnsizer.Realize()
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(wl_sizer, 1, wx.ALL | wx.EXPAND, 5)
main_sizer.Add(ww_sizer, 1, wx.ALL | wx.EXPAND, 5)
main_sizer.Add(btnsizer, 1, wx.ALL | wx.EXPAND, 5)
btn_ok.Bind(wx.EVT_BUTTON, self.OnOK)
btn_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
self.Bind(wx.EVT_CLOSE, self.OnClose)
self.SetSizer(main_sizer)
main_sizer.Fit(self)
main_sizer.SetSizeHints(self)
self.Layout()
self.Center()
def OnOK(self, evt):
try:
ww = int(self.txt_ww.GetValue())
wl = int(self.txt_wl.GetValue())
except ValueError:
self.Close()
return
Publisher.sendMessage('Bright and contrast adjustment image', window=ww, level=wl)
const.WINDOW_LEVEL['Manual'] = (ww, wl)
Publisher.sendMessage('Check window and level other')
Publisher.sendMessage('Update window level value', window=ww, level=wl)
#Necessary update the slice plane in the volume case exists
Publisher.sendMessage('Update slice viewer')
Publisher.sendMessage('Render volume viewer')
self.Close()
def OnCancel(self, evt):
self.Close()
def OnClose(self, evt):
self.Destroy()
class SetSpacingDialog(wx.Dialog):
def __init__(
self,
parent,
sx,
sy,
sz,
title=_("Set spacing"),
style=wx.DEFAULT_DIALOG_STYLE | wx.FRAME_FLOAT_ON_PARENT | wx.STAY_ON_TOP,
):
wx.Dialog.__init__(self, parent, -1, title=title, style=style)
self.spacing_original_x = sx
self.spacing_original_y = sy
self.spacing_original_z = sz
self._init_gui()
self._bind_events()
def _init_gui(self):
self.txt_spacing_new_x = wx.TextCtrl(self, -1, value=str(self.spacing_original_x))
self.txt_spacing_new_y = wx.TextCtrl(self, -1, value=str(self.spacing_original_y))
self.txt_spacing_new_z = wx.TextCtrl(self, -1, value=str(self.spacing_original_z))
sizer_new = wx.FlexGridSizer(3, 2, 5, 5)
sizer_new.AddMany(
(
(wx.StaticText(self, -1, "Spacing X"), 0, wx.ALIGN_CENTER_VERTICAL),
(self.txt_spacing_new_x, 1, wx.EXPAND),
(wx.StaticText(self, -1, "Spacing Y"), 0, wx.ALIGN_CENTER_VERTICAL),
(self.txt_spacing_new_y, 1, wx.EXPAND),
(wx.StaticText(self, -1, "Spacing Z"), 0, wx.ALIGN_CENTER_VERTICAL),
(self.txt_spacing_new_z, 1, wx.EXPAND),
)
)
self.button_ok = wx.Button(self, wx.ID_OK)
self.button_cancel = wx.Button(self, wx.ID_CANCEL)
button_sizer = wx.StdDialogButtonSizer()
button_sizer.AddButton(self.button_ok)
button_sizer.AddButton(self.button_cancel)
button_sizer.Realize()
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(wx.StaticText(self, -1, _("It was not possible to obtain the image spacings.\nPlease set it correctly:")), 0, wx.EXPAND)
main_sizer.Add(sizer_new, 1, wx.EXPAND | wx.ALL, 5)
main_sizer.Add(button_sizer, 0, wx.EXPAND | wx.TOP | wx.BOTTOM, 5)
self.SetSizer(main_sizer)
main_sizer.Fit(self)
self.Layout()
def _bind_events(self):
self.txt_spacing_new_x.Bind(wx.EVT_KILL_FOCUS, self.OnSetNewSpacing)
self.txt_spacing_new_y.Bind(wx.EVT_KILL_FOCUS, self.OnSetNewSpacing)
self.txt_spacing_new_z.Bind(wx.EVT_KILL_FOCUS, self.OnSetNewSpacing)
self.button_ok.Bind(wx.EVT_BUTTON, self.OnOk)
self.button_cancel.Bind(wx.EVT_BUTTON, self.OnCancel)
def OnSetNewSpacing(self, evt):
try:
new_spacing_x = float(self.txt_spacing_new_x.GetValue())
except ValueError:
new_spacing_x = self.spacing_new_x
try:
new_spacing_y = float(self.txt_spacing_new_y.GetValue())
except ValueError:
new_spacing_y = self.spacing_new_y
try:
new_spacing_z = float(self.txt_spacing_new_z.GetValue())
except ValueError:
new_spacing_z = self.spacing_new_z
self.set_new_spacing(new_spacing_x, new_spacing_y, new_spacing_z)
def set_new_spacing(self, sx, sy, sz):
self.spacing_new_x = sx
self.spacing_new_y = sy
self.spacing_new_z = sz
self.txt_spacing_new_x.ChangeValue(str(sx))
self.txt_spacing_new_y.ChangeValue(str(sy))
self.txt_spacing_new_z.ChangeValue(str(sz))
def OnOk(self, evt):
if self.spacing_new_x == 0.0:
self.txt_spacing_new_x.SetFocus()
elif self.spacing_new_y == 0.0:
self.txt_spacing_new_y.SetFocus()
elif self.spacing_new_z == 0.0:
self.txt_spacing_new_z.SetFocus()
else:
self.EndModal(wx.ID_OK)
def OnCancel(self, evt):
self.EndModal(wx.ID_CANCEL)
class PeelsCreationDlg(wx.Dialog):
FROM_MASK = 1
FROM_FILES = 2
def __init__(self, parent, *args, **kwds):
wx.Dialog.__init__(self, parent, *args, **kwds)
self.mask_path = ''
self.method = self.FROM_MASK
self._init_gui()
self._bind_events_wx()
self.get_all_masks()
def _init_gui(self):
self.SetTitle("dialog")
from_mask_stbox = self._from_mask_gui()
from_files_stbox = self._from_files_gui()
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add(from_mask_stbox, 0, wx.EXPAND | wx.ALL, 5)
main_sizer.Add(from_files_stbox, 0, wx.EXPAND | wx.ALL, 5)
btn_sizer = wx.StdDialogButtonSizer()
main_sizer.Add(btn_sizer, 0, wx.ALIGN_RIGHT | wx.ALL, 4)
self.btn_ok = wx.Button(self, wx.ID_OK, "")
self.btn_ok.SetDefault()
btn_sizer.AddButton(self.btn_ok)
self.btn_cancel = wx.Button(self, wx.ID_CANCEL, "")
btn_sizer.AddButton(self.btn_cancel)
btn_sizer.Realize()
self.SetSizer(main_sizer)
main_sizer.Fit(self)
self.SetAffirmativeId(self.btn_ok.GetId())
self.SetEscapeId(self.btn_cancel.GetId())
self.Layout()
def _from_mask_gui(self):
mask_box = wx.StaticBox(self, -1, _("From mask"))
from_mask_stbox = wx.StaticBoxSizer(mask_box, wx.VERTICAL)
self.cb_masks = wx.ComboBox(self, wx.ID_ANY, choices=[])
self.from_mask_rb = wx.RadioButton(self, -1, "", style = wx.RB_GROUP)
internal_sizer = wx.BoxSizer(wx.HORIZONTAL)
internal_sizer.Add(self.from_mask_rb, 0, wx.ALL | wx.EXPAND, 5)
internal_sizer.Add(self.cb_masks, 1, wx.ALL | wx.EXPAND, 5)
from_mask_stbox.Add(internal_sizer, 0, wx.EXPAND)
return from_mask_stbox
def _from_files_gui(self):
session = ses.Session()
last_directory = session.get('paths', 'last_directory_%d' % const.ID_NIFTI_IMPORT, '')
files_box = wx.StaticBox(self, -1, _("From files"))
from_files_stbox = wx.StaticBoxSizer(files_box, wx.VERTICAL)
self.mask_file_browse = filebrowse.FileBrowseButton(self, -1, labelText=_("Mask file"),
fileMask=WILDCARD_NIFTI, dialogTitle=_("Choose Mask file"), startDirectory = last_directory,
changeCallback=lambda evt: self._set_files_callback(mask_path=evt.GetString()))
self.from_files_rb = wx.RadioButton(self, -1, "")
ctrl_sizer = wx.BoxSizer(wx.VERTICAL)
ctrl_sizer.Add(self.mask_file_browse, 0, wx.ALL | wx.EXPAND, 5)
internal_sizer = wx.BoxSizer(wx.HORIZONTAL)
internal_sizer.Add(self.from_files_rb, 0, wx.ALL | wx.EXPAND, 5)
internal_sizer.Add(ctrl_sizer, 0, wx.ALL | wx.EXPAND, 5)
from_files_stbox.Add(internal_sizer, 0, wx.EXPAND)
return from_files_stbox
def _bind_events_wx(self):
self.from_mask_rb.Bind(wx.EVT_RADIOBUTTON, self.on_select_method)
self.from_files_rb.Bind(wx.EVT_RADIOBUTTON, self.on_select_method)
def get_all_masks(self):
import invesalius.project as prj
inv_proj = prj.Project()
choices = [i.name for i in inv_proj.mask_dict.values()]
try:
initial_value = choices[0]
enable = True
except IndexError:
initial_value = ""
enable = False
self.cb_masks.SetItems(choices)
self.cb_masks.SetValue(initial_value)
self.btn_ok.Enable(enable)
def on_select_method(self, evt):
radio_selected = evt.GetEventObject()
if radio_selected is self.from_mask_rb:
self.method = self.FROM_MASK
if self.cb_masks.GetItems():
self.btn_ok.Enable(True)
else:
self.btn_ok.Enable(False)
else:
self.method = self.FROM_FILES
if self._check_if_files_exists():
self.btn_ok.Enable(True)
else:
self.btn_ok.Enable(False)
def _set_files_callback(self, mask_path=''):
if mask_path:
self.mask_path = mask_path
if self.method == self.FROM_FILES:
if self._check_if_files_exists():
self.btn_ok.Enable(True)
else:
self.btn_ok.Enable(False)
def _check_if_files_exists(self):
if self.mask_path and os.path.exists(self.mask_path):
return True
else:
return False<|fim▁end|> | |
<|file_name|>ScopedAliases.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2010 The Closure Compiler 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 com.google.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multiset;
import com.google.common.collect.Sets;
import com.google.javascript.jscomp.CompilerOptions.AliasTransformation;
import com.google.javascript.jscomp.CompilerOptions.AliasTransformationHandler;
import com.google.javascript.jscomp.Scope.Var;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.SourcePosition;
import com.google.javascript.rhino.Token;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Process aliases in goog.scope blocks.
*
* goog.scope(function() {
* var dom = goog.dom;
* var DIV = dom.TagName.DIV;
*
* dom.createElement(DIV);
* });
*
* should become
*
* goog.dom.createElement(goog.dom.TagName.DIV);
*
* The advantage of using goog.scope is that the compiler will *guarantee*
* the anonymous function will be inlined, even if it can't prove
* that it's semantically correct to do so. For example, consider this case:
*
* goog.scope(function() {
* goog.getBar = function () { return alias; };
* ...
* var alias = foo.bar;
* })
*
* In theory, the compiler can't inline 'alias' unless it can prove that
* goog.getBar is called only after 'alias' is defined.
*
* In practice, the compiler will inline 'alias' anyway, at the risk of
* 'fixing' bad code.
*
* @author [email protected] (Robby Walker)
*/
class ScopedAliases implements HotSwapCompilerPass {
/** Name used to denote an scoped function block used for aliasing. */
static final String SCOPING_METHOD_NAME = "goog.scope";
private final AbstractCompiler compiler;
private final PreprocessorSymbolTable preprocessorSymbolTable;
private final AliasTransformationHandler transformationHandler;
// Errors
static final DiagnosticType GOOG_SCOPE_USED_IMPROPERLY = DiagnosticType.error(
"JSC_GOOG_SCOPE_USED_IMPROPERLY",
"The call to goog.scope must be alone in a single statement.");
static final DiagnosticType GOOG_SCOPE_HAS_BAD_PARAMETERS =
DiagnosticType.error(
"JSC_GOOG_SCOPE_HAS_BAD_PARAMETERS",
"The call to goog.scope must take only a single parameter. It must" +
" be an anonymous function that itself takes no parameters.");
static final DiagnosticType GOOG_SCOPE_REFERENCES_THIS = DiagnosticType.error(
"JSC_GOOG_SCOPE_REFERENCES_THIS",
"The body of a goog.scope function cannot reference 'this'.");
static final DiagnosticType GOOG_SCOPE_USES_RETURN = DiagnosticType.error(
"JSC_GOOG_SCOPE_USES_RETURN",
"The body of a goog.scope function cannot use 'return'.");
static final DiagnosticType GOOG_SCOPE_USES_THROW = DiagnosticType.error(
"JSC_GOOG_SCOPE_USES_THROW",
"The body of a goog.scope function cannot use 'throw'.");
static final DiagnosticType GOOG_SCOPE_ALIAS_REDEFINED = DiagnosticType.error(
"JSC_GOOG_SCOPE_ALIAS_REDEFINED",
"The alias {0} is assigned a value more than once.");
static final DiagnosticType GOOG_SCOPE_ALIAS_CYCLE = DiagnosticType.error(
"JSC_GOOG_SCOPE_ALIAS_CYCLE",
"The aliases {0} has a cycle.");
static final DiagnosticType GOOG_SCOPE_NON_ALIAS_LOCAL = DiagnosticType.error(
"JSC_GOOG_SCOPE_NON_ALIAS_LOCAL",
"The local variable {0} is in a goog.scope and is not an alias.");
private Multiset<String> scopedAliasNames = HashMultiset.create();
ScopedAliases(AbstractCompiler compiler,
@Nullable PreprocessorSymbolTable preprocessorSymbolTable,
AliasTransformationHandler transformationHandler) {
this.compiler = compiler;
this.preprocessorSymbolTable = preprocessorSymbolTable;
this.transformationHandler = transformationHandler;
}
@Override
public void process(Node externs, Node root) {
hotSwapScript(root, null);
}
@Override
public void hotSwapScript(Node root, Node originalRoot) {
Traversal traversal = new Traversal();
NodeTraversal.traverse(compiler, root, traversal);
if (!traversal.hasErrors()) {
// Apply the aliases.
List<AliasUsage> aliasWorkQueue =
Lists.newArrayList(traversal.getAliasUsages());
while (!aliasWorkQueue.isEmpty()) {
List<AliasUsage> newQueue = Lists.newArrayList();
for (AliasUsage aliasUsage : aliasWorkQueue) {
if (aliasUsage.referencesOtherAlias()) {
newQueue.add(aliasUsage);
} else {
aliasUsage.applyAlias();
}
}
// Prevent an infinite loop.
if (newQueue.size() == aliasWorkQueue.size()) {
Var cycleVar = newQueue.get(0).aliasVar;
compiler.report(JSError.make(
cycleVar.getNode(), GOOG_SCOPE_ALIAS_CYCLE, cycleVar.getName()));
break;
} else {
aliasWorkQueue = newQueue;
}
}
// Remove the alias definitions.
for (Node aliasDefinition : traversal.getAliasDefinitionsInOrder()) {
if (aliasDefinition.getParent().isVar() &&
aliasDefinition.getParent().hasOneChild()) {
aliasDefinition.getParent().detachFromParent();
} else {
aliasDefinition.detachFromParent();
}
}
// Collapse the scopes.<|fim▁hole|> scopeClosureBlock.detachFromParent();
expressionWithScopeCall.getParent().replaceChild(
expressionWithScopeCall,
scopeClosureBlock);
NodeUtil.tryMergeBlock(scopeClosureBlock);
}
if (traversal.getAliasUsages().size() > 0 ||
traversal.getAliasDefinitionsInOrder().size() > 0 ||
traversal.getScopeCalls().size() > 0) {
compiler.reportCodeChange();
}
}
}
private abstract class AliasUsage {
final Var aliasVar;
final Node aliasReference;
AliasUsage(Var aliasVar, Node aliasReference) {
this.aliasVar = aliasVar;
this.aliasReference = aliasReference;
}
/** Checks to see if this references another alias. */
public boolean referencesOtherAlias() {
Node aliasDefinition = aliasVar.getInitialValue();
Node root = NodeUtil.getRootOfQualifiedName(aliasDefinition);
Var otherAliasVar = aliasVar.getScope().getOwnSlot(root.getString());
return otherAliasVar != null;
}
public abstract void applyAlias();
}
private class AliasedNode extends AliasUsage {
AliasedNode(Var aliasVar, Node aliasReference) {
super(aliasVar, aliasReference);
}
@Override
public void applyAlias() {
Node aliasDefinition = aliasVar.getInitialValue();
aliasReference.getParent().replaceChild(
aliasReference, aliasDefinition.cloneTree());
}
}
private class AliasedTypeNode extends AliasUsage {
AliasedTypeNode(Var aliasVar, Node aliasReference) {
super(aliasVar, aliasReference);
}
@Override
public void applyAlias() {
Node aliasDefinition = aliasVar.getInitialValue();
String aliasName = aliasVar.getName();
String typeName = aliasReference.getString();
String aliasExpanded =
Preconditions.checkNotNull(aliasDefinition.getQualifiedName());
Preconditions.checkState(typeName.startsWith(aliasName));
aliasReference.setString(typeName.replaceFirst(aliasName, aliasExpanded));
}
}
private class Traversal implements NodeTraversal.ScopedCallback {
// The job of this class is to collect these three data sets.
// The order of this list determines the order that aliases are applied.
private final List<Node> aliasDefinitionsInOrder = Lists.newArrayList();
private final List<Node> scopeCalls = Lists.newArrayList();
private final List<AliasUsage> aliasUsages = Lists.newArrayList();
// This map is temporary and cleared for each scope.
private final Map<String, Var> aliases = Maps.newHashMap();
// Suppose you create an alias.
// var x = goog.x;
// As a side-effect, this means you can shadow the namespace 'goog'
// in inner scopes. When we inline the namespaces, we have to rename
// these shadows.
//
// Fortunately, we already have a name uniquifier that runs during tree
// normalization (before optimizations). We run it here on a limited
// set of variables, but only as a last resort (because this will screw
// up warning messages downstream).
private final Set<String> forbiddenLocals = Sets.newHashSet("$jscomp");
private boolean hasNamespaceShadows = false;
private boolean hasErrors = false;
private AliasTransformation transformation = null;
Collection<Node> getAliasDefinitionsInOrder() {
return aliasDefinitionsInOrder;
}
private List<AliasUsage> getAliasUsages() {
return aliasUsages;
}
List<Node> getScopeCalls() {
return scopeCalls;
}
boolean hasErrors() {
return hasErrors;
}
private boolean isCallToScopeMethod(Node n) {
return n.isCall() &&
SCOPING_METHOD_NAME.equals(n.getFirstChild().getQualifiedName());
}
@Override
public void enterScope(NodeTraversal t) {
Node n = t.getCurrentNode().getParent();
if (n != null && isCallToScopeMethod(n)) {
transformation = transformationHandler.logAliasTransformation(
n.getSourceFileName(), getSourceRegion(n));
findAliases(t);
}
}
@Override
public void exitScope(NodeTraversal t) {
if (t.getScopeDepth() > 2) {
findNamespaceShadows(t);
}
if (t.getScopeDepth() == 2) {
renameNamespaceShadows(t);
aliases.clear();
forbiddenLocals.clear();
transformation = null;
hasNamespaceShadows = false;
}
}
@Override
public final boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
if (n.isFunction() && t.inGlobalScope()) {
// Do not traverse in to functions except for goog.scope functions.
if (parent == null || !isCallToScopeMethod(parent)) {
return false;
}
}
return true;
}
private SourcePosition<AliasTransformation> getSourceRegion(Node n) {
Node testNode = n;
Node next = null;
for (; next != null || testNode.isScript();) {
next = testNode.getNext();
testNode = testNode.getParent();
}
int endLine = next == null ? Integer.MAX_VALUE : next.getLineno();
int endChar = next == null ? Integer.MAX_VALUE : next.getCharno();
SourcePosition<AliasTransformation> pos =
new SourcePosition<AliasTransformation>() {};
pos.setPositionInformation(
n.getLineno(), n.getCharno(), endLine, endChar);
return pos;
}
private void report(NodeTraversal t, Node n, DiagnosticType error,
String... arguments) {
compiler.report(t.makeError(n, error, arguments));
hasErrors = true;
}
private void findAliases(NodeTraversal t) {
Scope scope = t.getScope();
for (Var v : scope.getVarIterable()) {
Node n = v.getNode();
Node parent = n.getParent();
boolean isVar = parent.isVar();
boolean isFunctionDecl = NodeUtil.isFunctionDeclaration(parent);
if (isVar && n.getFirstChild() != null && n.getFirstChild().isQualifiedName()) {
recordAlias(v);
} else if (v.isBleedingFunction()) {
// Bleeding functions already get a BAD_PARAMETERS error, so just
// do nothing.
} else if (parent.getType() == Token.LP) {
// Parameters of the scope function also get a BAD_PARAMETERS
// error.
} else if (isVar || isFunctionDecl) {
boolean isHoisted = NodeUtil.isHoistedFunctionDeclaration(parent);
Node grandparent = parent.getParent();
Node value = v.getInitialValue() != null ?
v.getInitialValue() :
null;
Node varNode = null;
String name = n.getString();
int nameCount = scopedAliasNames.count(name);
scopedAliasNames.add(name);
String globalName =
"$jscomp.scope." + name + (nameCount == 0 ? "" : ("$" + nameCount));
compiler.ensureLibraryInjected("base");
// First, we need to free up the function expression (EXPR)
// to be used in another expression.
if (isFunctionDecl) {
// Replace "function NAME() { ... }" with "var NAME;".
Node existingName = v.getNameNode();
// We can't keep the local name on the function expression,
// because IE is buggy and will leak the name into the global
// scope. This is covered in more detail here:
// http://wiki.ecmascript.org/lib/exe/fetch.php?id=resources:resources&cache=cache&media=resources:jscriptdeviationsfromes3.pdf
//
// This will only cause problems if this is a hoisted, recursive
// function, and the programmer is using the hoisting.
Node newName = IR.name("").useSourceInfoFrom(existingName);
value.replaceChild(existingName, newName);
varNode = IR.var(existingName).useSourceInfoFrom(existingName);
grandparent.replaceChild(parent, varNode);
} else {
if (value != null) {
// If this is a VAR, we can just detach the expression and
// the tree will still be valid.
value.detachFromParent();
}
varNode = parent;
}
// Add $jscomp.scope.name = EXPR;
// Make sure we copy over all the jsdoc and debug info.
if (value != null || v.getJSDocInfo() != null) {
Node newDecl = NodeUtil.newQualifiedNameNodeDeclaration(
compiler.getCodingConvention(),
globalName,
value,
v.getJSDocInfo())
.useSourceInfoIfMissingFromForTree(n);
NodeUtil.setDebugInformation(
newDecl.getFirstChild().getFirstChild(), n, name);
if (isHoisted) {
grandparent.addChildToFront(newDecl);
} else {
grandparent.addChildBefore(newDecl, varNode);
}
}
// Rewrite "var name = EXPR;" to "var name = $jscomp.scope.name;"
v.getNameNode().addChildToFront(
NodeUtil.newQualifiedNameNode(
compiler.getCodingConvention(), globalName, n, name));
recordAlias(v);
} else {
// Do not other kinds of local symbols, like catch params.
report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString());
}
}
}
private void recordAlias(Var aliasVar) {
String name = aliasVar.getName();
aliases.put(name, aliasVar);
String qualifiedName =
aliasVar.getInitialValue().getQualifiedName();
transformation.addAlias(name, qualifiedName);
int rootIndex = qualifiedName.indexOf(".");
if (rootIndex != -1) {
String qNameRoot = qualifiedName.substring(0, rootIndex);
if (!aliases.containsKey(qNameRoot)) {
forbiddenLocals.add(qNameRoot);
}
}
}
/** Find out if there are any local shadows of namespaces. */
private void findNamespaceShadows(NodeTraversal t) {
if (hasNamespaceShadows) {
return;
}
Scope scope = t.getScope();
for (Var v : scope.getVarIterable()) {
if (forbiddenLocals.contains(v.getName())) {
hasNamespaceShadows = true;
return;
}
}
}
/**
* Rename any local shadows of namespaces.
* This should be a very rare occurrence, so only do this traversal
* if we know that we need it.
*/
private void renameNamespaceShadows(NodeTraversal t) {
if (hasNamespaceShadows) {
MakeDeclaredNamesUnique.Renamer renamer =
new MakeDeclaredNamesUnique.WhitelistedRenamer(
new MakeDeclaredNamesUnique.ContextualRenamer(),
forbiddenLocals);
for (String s : forbiddenLocals) {
renamer.addDeclaredName(s);
}
MakeDeclaredNamesUnique uniquifier =
new MakeDeclaredNamesUnique(renamer);
NodeTraversal.traverse(compiler, t.getScopeRoot(), uniquifier);
}
}
private void validateScopeCall(NodeTraversal t, Node n, Node parent) {
if (preprocessorSymbolTable != null) {
preprocessorSymbolTable.addReference(n.getFirstChild());
}
if (!parent.isExprResult()) {
report(t, n, GOOG_SCOPE_USED_IMPROPERLY);
}
if (n.getChildCount() != 2) {
// The goog.scope call should have exactly 1 parameter. The first
// child is the "goog.scope" and the second should be the parameter.
report(t, n, GOOG_SCOPE_HAS_BAD_PARAMETERS);
} else {
Node anonymousFnNode = n.getChildAtIndex(1);
if (!anonymousFnNode.isFunction() ||
NodeUtil.getFunctionName(anonymousFnNode) != null ||
NodeUtil.getFunctionParameters(anonymousFnNode).hasChildren()) {
report(t, anonymousFnNode, GOOG_SCOPE_HAS_BAD_PARAMETERS);
} else {
scopeCalls.add(n);
}
}
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (isCallToScopeMethod(n)) {
validateScopeCall(t, n, n.getParent());
}
if (t.getScopeDepth() < 2) {
return;
}
int type = n.getType();
Var aliasVar = null;
if (type == Token.NAME) {
String name = n.getString();
Var lexicalVar = t.getScope().getVar(n.getString());
if (lexicalVar != null && lexicalVar == aliases.get(name)) {
aliasVar = lexicalVar;
}
}
// Validate the top-level of the goog.scope block.
if (t.getScopeDepth() == 2) {
if (aliasVar != null && NodeUtil.isLValue(n)) {
if (aliasVar.getNode() == n) {
aliasDefinitionsInOrder.add(n);
// Return early, to ensure that we don't record a definition
// twice.
return;
} else {
report(t, n, GOOG_SCOPE_ALIAS_REDEFINED, n.getString());
}
}
if (type == Token.RETURN) {
report(t, n, GOOG_SCOPE_USES_RETURN);
} else if (type == Token.THIS) {
report(t, n, GOOG_SCOPE_REFERENCES_THIS);
} else if (type == Token.THROW) {
report(t, n, GOOG_SCOPE_USES_THROW);
}
}
// Validate all descendent scopes of the goog.scope block.
if (t.getScopeDepth() >= 2) {
// Check if this name points to an alias.
if (aliasVar != null) {
// Note, to support the transitive case, it's important we don't
// clone aliasedNode here. For example,
// var g = goog; var d = g.dom; d.createElement('DIV');
// The node in aliasedNode (which is "g") will be replaced in the
// changes pass above with "goog". If we cloned here, we'd end up
// with <code>g.dom.createElement('DIV')</code>.
aliasUsages.add(new AliasedNode(aliasVar, n));
}
JSDocInfo info = n.getJSDocInfo();
if (info != null) {
for (Node node : info.getTypeNodes()) {
fixTypeNode(node);
}
}
// TODO(robbyw): Error for goog.scope not at root.
}
}
private void fixTypeNode(Node typeNode) {
if (typeNode.isString()) {
String name = typeNode.getString();
int endIndex = name.indexOf('.');
if (endIndex == -1) {
endIndex = name.length();
}
String baseName = name.substring(0, endIndex);
Var aliasVar = aliases.get(baseName);
if (aliasVar != null) {
aliasUsages.add(new AliasedTypeNode(aliasVar, typeNode));
}
}
for (Node child = typeNode.getFirstChild(); child != null;
child = child.getNext()) {
fixTypeNode(child);
}
}
}
}<|fim▁end|> | for (Node scopeCall : traversal.getScopeCalls()) {
Node expressionWithScopeCall = scopeCall.getParent();
Node scopeClosureBlock = scopeCall.getLastChild().getLastChild(); |
<|file_name|>footer.component.spec.ts<|end_file_name|><|fim▁begin|><|fim▁hole|>//
// describe('FooterComponent', () => {
// let component: FooterComponent;
// let fixture: ComponentFixture<FooterComponent>;
//
// beforeEach(async(() => {
// TestBed.configureTestingModule({
// declarations: [FooterComponent]
// })
// .compileComponents();
// }));
//
// beforeEach(() => {
// fixture = TestBed.createComponent(FooterComponent);
// component = fixture.componentInstance;
// fixture.detectChanges();
// });
//
// it('should create', () => {
// expect(component).toBeTruthy();
// });
// });<|fim▁end|> | // import { async, ComponentFixture, TestBed } from '@angular/core/testing';
//
// import { FooterComponent } from './footer.component'; |
<|file_name|>ng-grid-tests.ts<|end_file_name|><|fim▁begin|>/// <reference path="ng-grid.d.ts" />
var options1: ngGrid.IGridOptions = {
data: [{ 'Name': 'Bob' }, { 'Name': 'Jane' }]
};
var options2: ngGrid.IGridOptions = {
afterSelectionChange: () => { },
beforeSelectionChange: () => {return true; },
dataUpdated: () => { }
};
var options3: ngGrid.IGridOptions = {
columnDefs: [
{ field: 'name', displayName: 'Name' },
{ field: 'age', displayName: 'Age' }
]
};
var options4: ngGrid.IGridOptions = {<|fim▁hole|> pagingOptions: {
pageSizes: [1, 2, 3, 4],
pageSize: 2,
totalServerItems: 100,
currentPage: 1
}
};<|fim▁end|> | |
<|file_name|>reset.request.controller.js<|end_file_name|><|fim▁begin|>(function() {
'use strict';
angular
.module('fitappApp')
.controller('RequestResetController', RequestResetController);
RequestResetController.$inject = ['$timeout', 'Auth'];
function RequestResetController ($timeout, Auth) {
var vm = this;
vm.error = null;
vm.errorEmailNotExists = null;
vm.requestReset = requestReset;
vm.resetAccount = {};
vm.success = null;
$timeout(function (){angular.element('#email').focus();});
function requestReset () {
vm.error = null;
vm.errorEmailNotExists = null;
Auth.resetPasswordInit(vm.resetAccount.email).then(function () {
vm.success = 'OK';
}).catch(function (response) {
vm.success = null;<|fim▁hole|> vm.error = 'ERROR';
}
});
}
}
})();<|fim▁end|> | if (response.status === 400 && response.data === 'e-mail address not registered') {
vm.errorEmailNotExists = 'ERROR';
} else { |
<|file_name|>configuration-loader.service.ts<|end_file_name|><|fim▁begin|>import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { IConfig } from '../models/config.interface';
export class ConfigurationLoader {
private CONF: { [id: string] : IConfig } = {
"DEV": {
APP_URL: "http://localhost:3000/",
API_URL: "http://localhost:8089" + "/school/",
LOG_LEVEL: "ALL",
MOCK: true
},
"PROD":{
APP_URL: "http://localhost:3000/",
API_URL: window.location.origin + "/school/",
LOG_LEVEL: "NONE",
MOCK: false
}
};
load(env: string): IConfig{
let envConf = this.CONF[env];<|fim▁hole|> APP_URL: envConf.APP_URL,
API_URL: envConf.API_URL,
LOG_LEVEL: envConf.LOG_LEVEL,
MOCK: envConf.MOCK
}
}
}<|fim▁end|> | return { |
<|file_name|>django_1_0.py<|end_file_name|><|fim▁begin|>"""
Hacks for the Django 1.0/1.0.2 releases.
"""
from django.conf import settings
from django.db.backends.creation import BaseDatabaseCreation
from django.db.models.loading import cache
from django.core import management
from django.core.management.commands.flush import Command as FlushCommand
from django.utils.datastructures import SortedDict
class SkipFlushCommand(FlushCommand):
def handle_noargs(self, **options):
# no-op to avoid calling flush
return
class Hacks:
def set_installed_apps(self, apps):
"""
Sets Django's INSTALLED_APPS setting to be effectively the list passed in.
"""
# Make sure it's a list.
apps = list(apps)
# Make sure it contains strings
if apps:
assert isinstance(apps[0], basestring), "The argument to set_installed_apps must be a list of strings."
# Monkeypatch in!
settings.INSTALLED_APPS, settings.OLD_INSTALLED_APPS = (
apps,
settings.INSTALLED_APPS,
)
self._redo_app_cache()
def reset_installed_apps(self):
"""
Undoes the effect of set_installed_apps.
"""
settings.INSTALLED_APPS = settings.OLD_INSTALLED_APPS
self._redo_app_cache()
def _redo_app_cache(self):
"""
Used to repopulate AppCache after fiddling with INSTALLED_APPS.
"""
cache.loaded = False
cache.handled = {}
cache.postponed = []
cache.app_store = SortedDict()
cache.app_models = SortedDict()
cache.app_errors = {}
cache._populate()
def clear_app_cache(self):
"""<|fim▁hole|> """
self.old_app_models, cache.app_models = cache.app_models, {}
def unclear_app_cache(self):
"""
Reversed the effects of clear_app_cache.
"""
cache.app_models = self.old_app_models
cache._get_models_cache = {}
def repopulate_app_cache(self):
"""
Rebuilds AppCache with the real model definitions.
"""
cache._populate()
def store_app_cache_state(self):
self.stored_app_cache_state = dict(**cache.__dict__)
def restore_app_cache_state(self):
cache.__dict__ = self.stored_app_cache_state
def patch_flush_during_test_db_creation(self):
"""
Patches BaseDatabaseCreation.create_test_db to not flush database
"""
def patch(f):
def wrapper(*args, **kwargs):
# hold onto the original and replace flush command with a no-op
original_flush_command = management._commands['flush']
try:
management._commands['flush'] = SkipFlushCommand()
# run create_test_db
f(*args, **kwargs)
finally:
# unpatch flush back to the original
management._commands['flush'] = original_flush_command
return wrapper
BaseDatabaseCreation.create_test_db = patch(BaseDatabaseCreation.create_test_db)<|fim▁end|> | Clears the contents of AppCache to a blank state, so new models
from the ORM can be added. |
<|file_name|>event-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python -u
#
#
#
#################################################################################
# Start off by implementing a general purpose event loop for anyones use
#################################################################################
import sys
import getopt
import os
import libvirt
import select
import errno
import time
import threading
# For the sake of demonstration, this example program includes
# an implementation of a pure python event loop. Most applications
# would be better off just using the default libvirt event loop
# APIs, instead of implementing this in python. The exception is
# where an application wants to integrate with an existing 3rd
# party event loop impl
#
# Change this to 'False' to make the demo use the native
# libvirt event loop impl
use_pure_python_event_loop = True
do_debug = False
def debug(msg):
global do_debug
if do_debug:
print(msg)
#
# This general purpose event loop will support waiting for file handle
# I/O and errors events, as well as scheduling repeatable timers with
# a fixed interval.
#
# It is a pure python implementation based around the poll() API
#
class virEventLoopPure:
# This class contains the data we need to track for a
# single file handle
class virEventLoopPureHandle:
def __init__(self, handle, fd, events, cb, opaque):
self.handle = handle
self.fd = fd
self.events = events
self.cb = cb
self.opaque = opaque
def get_id(self):
return self.handle
def get_fd(self):
return self.fd
def get_events(self):
return self.events
def set_events(self, events):
self.events = events
def dispatch(self, events):
self.cb(self.handle,
self.fd,
events,
self.opaque)
# This class contains the data we need to track for a
# single periodic timer
class virEventLoopPureTimer:
def __init__(self, timer, interval, cb, opaque):
self.timer = timer
self.interval = interval
self.cb = cb
self.opaque = opaque
self.lastfired = 0
def get_id(self):
return self.timer
def get_interval(self):
return self.interval
def set_interval(self, interval):
self.interval = interval
def get_last_fired(self):
return self.lastfired
def set_last_fired(self, now):
self.lastfired = now
def dispatch(self):
self.cb(self.timer,
self.opaque)
def __init__(self):
self.poll = select.poll()
self.pipetrick = os.pipe()
self.pendingWakeup = False
self.runningPoll = False
self.nextHandleID = 1
self.nextTimerID = 1
self.handles = []
self.timers = []
self.quit = False
# The event loop can be used from multiple threads at once.
# Specifically while the main thread is sleeping in poll()
# waiting for events to occur, another thread may come along
# and add/update/remove a file handle, or timer. When this
# happens we need to interrupt the poll() sleep in the other
# thread, so that it'll see the file handle / timer changes.
#
# Using OS level signals for this is very unreliable and
# hard to implement correctly. Thus we use the real classic
# "self pipe" trick. A anonymous pipe, with one end registered
# with the event loop for input events. When we need to force
# the main thread out of a poll() sleep, we simple write a
# single byte of data to the other end of the pipe.
debug("Self pipe watch %d write %d" %(self.pipetrick[0], self.pipetrick[1]))
self.poll.register(self.pipetrick[0], select.POLLIN)
# Calculate when the next timeout is due to occur, returning
# the absolute timestamp for the next timeout, or 0 if there is
# no timeout due
def next_timeout(self):
next = 0
for t in self.timers:
last = t.get_last_fired()
interval = t.get_interval()
if interval < 0:
continue
if next == 0 or (last + interval) < next:
next = last + interval
return next
# Lookup a virEventLoopPureHandle object based on file descriptor
def get_handle_by_fd(self, fd):
for h in self.handles:
if h.get_fd() == fd:
return h
return None
# Lookup a virEventLoopPureHandle object based on its event loop ID
def get_handle_by_id(self, handleID):
for h in self.handles:
if h.get_id() == handleID:
return h
return None
# This is the heart of the event loop, performing one single
# iteration. It asks when the next timeout is due, and then
# calcuates the maximum amount of time it is able to sleep
# for in poll() pending file handle events.
#
# It then goes into the poll() sleep.
#
# When poll() returns, there will zero or more file handle
# events which need to be dispatched to registered callbacks
# It may also be time to fire some periodic timers.
#
# Due to the coarse granularity of schedular timeslices, if
# we ask for a sleep of 500ms in order to satisfy a timer, we
# may return up to 1 schedular timeslice early. So even though
# our sleep timeout was reached, the registered timer may not
# technically be at its expiry point. This leads to us going
# back around the loop with a crazy 5ms sleep. So when checking
# if timeouts are due, we allow a margin of 20ms, to avoid
# these pointless repeated tiny sleeps.
def run_once(self):
sleep = -1
self.runningPoll = True
try:
next = self.next_timeout()
debug("Next timeout due at %d" % next)
if next > 0:
now = int(time.time() * 1000)
if now >= next:
sleep = 0
else:
sleep = (next - now) / 1000.0
debug("Poll with a sleep of %d" % sleep)
events = self.poll.poll(sleep)
# Dispatch any file handle events that occurred
for (fd, revents) in events:
# See if the events was from the self-pipe
# telling us to wakup. if so, then discard
# the data just continue
if fd == self.pipetrick[0]:
self.pendingWakeup = False
data = os.read(fd, 1)
continue
h = self.get_handle_by_fd(fd)
if h:
debug("Dispatch fd %d handle %d events %d" % (fd, h.get_id(), revents))
h.dispatch(self.events_from_poll(revents))
now = int(time.time() * 1000)
for t in self.timers:
interval = t.get_interval()
if interval < 0:
continue
want = t.get_last_fired() + interval
# Deduct 20ms, since scheduler timeslice
# means we could be ever so slightly early
if now >= (want-20):
debug("Dispatch timer %d now %s want %s" % (t.get_id(), str(now), str(want)))
t.set_last_fired(now)
t.dispatch()
except (os.error, select.error), e:
if e.args[0] != errno.EINTR:
raise
finally:
self.runningPoll = False
# Actually the event loop forever
def run_loop(self):
self.quit = False
while not self.quit:
self.run_once()
def interrupt(self):
if self.runningPoll and not self.pendingWakeup:
self.pendingWakeup = True
os.write(self.pipetrick[1], 'c'.encode("UTF-8"))
# Registers a new file handle 'fd', monitoring for 'events' (libvirt
# event constants), firing the callback cb() when an event occurs.
# Returns a unique integer identier for this handle, that should be
# used to later update/remove it
def add_handle(self, fd, events, cb, opaque):
handleID = self.nextHandleID + 1
self.nextHandleID = self.nextHandleID + 1
h = self.virEventLoopPureHandle(handleID, fd, events, cb, opaque)
self.handles.append(h)
self.poll.register(fd, self.events_to_poll(events))
self.interrupt()
debug("Add handle %d fd %d events %d" % (handleID, fd, events))
return handleID
# Registers a new timer with periodic expiry at 'interval' ms,
# firing cb() each time the timer expires. If 'interval' is -1,
# then the timer is registered, but not enabled
# Returns a unique integer identier for this handle, that should be
# used to later update/remove it
def add_timer(self, interval, cb, opaque):
timerID = self.nextTimerID + 1
self.nextTimerID = self.nextTimerID + 1
h = self.virEventLoopPureTimer(timerID, interval, cb, opaque)
self.timers.append(h)
self.interrupt()
debug("Add timer %d interval %d" % (timerID, interval))
return timerID
# Change the set of events to be monitored on the file handle
def update_handle(self, handleID, events):
h = self.get_handle_by_id(handleID)
if h:
h.set_events(events)
self.poll.unregister(h.get_fd())
self.poll.register(h.get_fd(), self.events_to_poll(events))
self.interrupt()
debug("Update handle %d fd %d events %d" % (handleID, h.get_fd(), events))
# Change the periodic frequency of the timer
def update_timer(self, timerID, interval):
for h in self.timers:
if h.get_id() == timerID:
h.set_interval(interval)
self.interrupt()
debug("Update timer %d interval %d" % (timerID, interval))
break
# Stop monitoring for events on the file handle
def remove_handle(self, handleID):
handles = []
for h in self.handles:
if h.get_id() == handleID:
self.poll.unregister(h.get_fd())
debug("Remove handle %d fd %d" % (handleID, h.get_fd()))
else:
handles.append(h)
self.handles = handles
self.interrupt()
# Stop firing the periodic timer
def remove_timer(self, timerID):
timers = []
for h in self.timers:
if h.get_id() != timerID:
timers.append(h)
debug("Remove timer %d" % timerID)
self.timers = timers
self.interrupt()
# Convert from libvirt event constants, to poll() events constants
def events_to_poll(self, events):
ret = 0
if events & libvirt.VIR_EVENT_HANDLE_READABLE:
ret |= select.POLLIN
if events & libvirt.VIR_EVENT_HANDLE_WRITABLE:
ret |= select.POLLOUT
if events & libvirt.VIR_EVENT_HANDLE_ERROR:
ret |= select.POLLERR
if events & libvirt.VIR_EVENT_HANDLE_HANGUP:
ret |= select.POLLHUP
return ret
# Convert from poll() event constants, to libvirt events constants
def events_from_poll(self, events):
ret = 0
if events & select.POLLIN:
ret |= libvirt.VIR_EVENT_HANDLE_READABLE
if events & select.POLLOUT:
ret |= libvirt.VIR_EVENT_HANDLE_WRITABLE
if events & select.POLLNVAL:
ret |= libvirt.VIR_EVENT_HANDLE_ERROR
if events & select.POLLERR:
ret |= libvirt.VIR_EVENT_HANDLE_ERROR
if events & select.POLLHUP:
ret |= libvirt.VIR_EVENT_HANDLE_HANGUP
return ret
###########################################################################
# Now glue an instance of the general event loop into libvirt's event loop
###########################################################################
# This single global instance of the event loop wil be used for
# monitoring libvirt events
eventLoop = virEventLoopPure()
# This keeps track of what thread is running the event loop,
# (if it is run in a background thread)
eventLoopThread = None
# These next set of 6 methods are the glue between the official
# libvirt events API, and our particular impl of the event loop
#
# There is no reason why the 'virEventLoopPure' has to be used.
# An application could easily may these 6 glue methods hook into
# another event loop such as GLib's, or something like the python
# Twisted event framework.
def virEventAddHandleImpl(fd, events, cb, opaque):
global eventLoop<|fim▁hole|> return eventLoop.add_handle(fd, events, cb, opaque)
def virEventUpdateHandleImpl(handleID, events):
global eventLoop
return eventLoop.update_handle(handleID, events)
def virEventRemoveHandleImpl(handleID):
global eventLoop
return eventLoop.remove_handle(handleID)
def virEventAddTimerImpl(interval, cb, opaque):
global eventLoop
return eventLoop.add_timer(interval, cb, opaque)
def virEventUpdateTimerImpl(timerID, interval):
global eventLoop
return eventLoop.update_timer(timerID, interval)
def virEventRemoveTimerImpl(timerID):
global eventLoop
return eventLoop.remove_timer(timerID)
# This tells libvirt what event loop implementation it
# should use
def virEventLoopPureRegister():
libvirt.virEventRegisterImpl(virEventAddHandleImpl,
virEventUpdateHandleImpl,
virEventRemoveHandleImpl,
virEventAddTimerImpl,
virEventUpdateTimerImpl,
virEventRemoveTimerImpl)
# Directly run the event loop in the current thread
def virEventLoopPureRun():
global eventLoop
eventLoop.run_loop()
def virEventLoopNativeRun():
while True:
libvirt.virEventRunDefaultImpl()
# Spawn a background thread to run the event loop
def virEventLoopPureStart():
global eventLoopThread
virEventLoopPureRegister()
eventLoopThread = threading.Thread(target=virEventLoopPureRun, name="libvirtEventLoop")
eventLoopThread.setDaemon(True)
eventLoopThread.start()
def virEventLoopNativeStart():
global eventLoopThread
libvirt.virEventRegisterDefaultImpl()
eventLoopThread = threading.Thread(target=virEventLoopNativeRun, name="libvirtEventLoop")
eventLoopThread.setDaemon(True)
eventLoopThread.start()
##########################################################################
# Everything that now follows is a simple demo of domain lifecycle events
##########################################################################
def eventToString(event):
eventStrings = ( "Defined",
"Undefined",
"Started",
"Suspended",
"Resumed",
"Stopped",
"Shutdown",
"PMSuspended",
"Crashed" )
return eventStrings[event]
def detailToString(event, detail):
eventStrings = (
( "Added", "Updated" ),
( "Removed", ),
( "Booted", "Migrated", "Restored", "Snapshot", "Wakeup" ),
( "Paused", "Migrated", "IOError", "Watchdog", "Restored", "Snapshot", "API error" ),
( "Unpaused", "Migrated", "Snapshot" ),
( "Shutdown", "Destroyed", "Crashed", "Migrated", "Saved", "Failed", "Snapshot"),
( "Finished", ),
( "Memory", "Disk" ),
( "Panicked", )
)
return eventStrings[event][detail]
def myDomainEventCallback1 (conn, dom, event, detail, opaque):
print("myDomainEventCallback1 EVENT: Domain %s(%s) %s %s" % (dom.name(), dom.ID(),
eventToString(event),
detailToString(event, detail)))
def myDomainEventCallback2 (conn, dom, event, detail, opaque):
print("myDomainEventCallback2 EVENT: Domain %s(%s) %s %s" % (dom.name(), dom.ID(),
eventToString(event),
detailToString(event, detail)))
def myDomainEventRebootCallback(conn, dom, opaque):
print("myDomainEventRebootCallback: Domain %s(%s)" % (dom.name(), dom.ID()))
def myDomainEventRTCChangeCallback(conn, dom, utcoffset, opaque):
print("myDomainEventRTCChangeCallback: Domain %s(%s) %d" % (dom.name(), dom.ID(), utcoffset))
def myDomainEventWatchdogCallback(conn, dom, action, opaque):
print("myDomainEventWatchdogCallback: Domain %s(%s) %d" % (dom.name(), dom.ID(), action))
def myDomainEventIOErrorCallback(conn, dom, srcpath, devalias, action, opaque):
print("myDomainEventIOErrorCallback: Domain %s(%s) %s %s %d" % (dom.name(), dom.ID(), srcpath, devalias, action))
def myDomainEventGraphicsCallback(conn, dom, phase, localAddr, remoteAddr, authScheme, subject, opaque):
print("myDomainEventGraphicsCallback: Domain %s(%s) %d %s" % (dom.name(), dom.ID(), phase, authScheme))
def myDomainEventDiskChangeCallback(conn, dom, oldSrcPath, newSrcPath, devAlias, reason, opaque):
print("myDomainEventDiskChangeCallback: Domain %s(%s) disk change oldSrcPath: %s newSrcPath: %s devAlias: %s reason: %s" % (
dom.name(), dom.ID(), oldSrcPath, newSrcPath, devAlias, reason))
def myDomainEventTrayChangeCallback(conn, dom, devAlias, reason, opaque):
print("myDomainEventTrayChangeCallback: Domain %s(%s) tray change devAlias: %s reason: %s" % (
dom.name(), dom.ID(), devAlias, reason))
def myDomainEventPMWakeupCallback(conn, dom, reason, opaque):
print("myDomainEventPMWakeupCallback: Domain %s(%s) system pmwakeup" % (
dom.name(), dom.ID()))
def myDomainEventPMSuspendCallback(conn, dom, reason, opaque):
print("myDomainEventPMSuspendCallback: Domain %s(%s) system pmsuspend" % (
dom.name(), dom.ID()))
def myDomainEventBalloonChangeCallback(conn, dom, actual, opaque):
print("myDomainEventBalloonChangeCallback: Domain %s(%s) %d" % (dom.name(), dom.ID(), actual))
def myDomainEventPMSuspendDiskCallback(conn, dom, reason, opaque):
print("myDomainEventPMSuspendDiskCallback: Domain %s(%s) system pmsuspend_disk" % (
dom.name(), dom.ID()))
def myDomainEventDeviceRemovedCallback(conn, dom, dev, opaque):
print("myDomainEventDeviceRemovedCallback: Domain %s(%s) device removed: %s" % (
dom.name(), dom.ID(), dev))
run = True
def myConnectionCloseCallback(conn, reason, opaque):
reasonStrings = (
"Error", "End-of-file", "Keepalive", "Client",
)
print("myConnectionCloseCallback: %s: %s" % (conn.getURI(), reasonStrings[reason]))
run = False
def usage():
print("usage: "+os.path.basename(sys.argv[0])+" [-hdl] [uri]")
print(" uri will default to qemu:///system")
print(" --help, -h Print(this help message")
print(" --debug, -d Print(debug output")
print(" --loop, -l Toggle event-loop-implementation")
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "hdl", ["help", "debug", "loop"])
except getopt.GetoptError, err:
# print help information and exit:
print(str(err)) # will print something like "option -a not recognized"
usage()
sys.exit(2)
for o, a in opts:
if o in ("-h", "--help"):
usage()
sys.exit()
if o in ("-d", "--debug"):
global do_debug
do_debug = True
if o in ("-l", "--loop"):
global use_pure_python_event_loop
use_pure_python_event_loop ^= True
if len(args) >= 1:
uri = args[0]
else:
uri = "qemu:///system"
print("Using uri:" + uri)
# Run a background thread with the event loop
if use_pure_python_event_loop:
virEventLoopPureStart()
else:
virEventLoopNativeStart()
vc = libvirt.openReadOnly(uri)
# Close connection on exit (to test cleanup paths)
old_exitfunc = getattr(sys, 'exitfunc', None)
def exit():
print("Closing " + vc.getURI())
vc.close()
if (old_exitfunc): old_exitfunc()
sys.exitfunc = exit
vc.registerCloseCallback(myConnectionCloseCallback, None)
#Add 2 callbacks to prove this works with more than just one
vc.domainEventRegister(myDomainEventCallback1,None)
vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE, myDomainEventCallback2, None)
vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_REBOOT, myDomainEventRebootCallback, None)
vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_RTC_CHANGE, myDomainEventRTCChangeCallback, None)
vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_IO_ERROR, myDomainEventIOErrorCallback, None)
vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_WATCHDOG, myDomainEventWatchdogCallback, None)
vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_GRAPHICS, myDomainEventGraphicsCallback, None)
vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_DISK_CHANGE, myDomainEventDiskChangeCallback, None)
vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_TRAY_CHANGE, myDomainEventTrayChangeCallback, None)
vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_PMWAKEUP, myDomainEventPMWakeupCallback, None)
vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_PMSUSPEND, myDomainEventPMSuspendCallback, None)
vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_BALLOON_CHANGE, myDomainEventBalloonChangeCallback, None)
vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_PMSUSPEND_DISK, myDomainEventPMSuspendDiskCallback, None)
vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED, myDomainEventDeviceRemovedCallback, None)
vc.setKeepAlive(5, 3)
# The rest of your app would go here normally, but for sake
# of demo we'll just go to sleep. The other option is to
# run the event loop in your main thread if your app is
# totally event based.
while run:
time.sleep(1)
if __name__ == "__main__":
main()<|fim▁end|> | |
<|file_name|>client.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation
# 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 os
from oslo.serialization import jsonutils as json
from glance.common import client as base_client
from glance.common import exception
from glance import i18n
_ = i18n._
class CacheClient(base_client.BaseClient):
DEFAULT_PORT = 9292
DEFAULT_DOC_ROOT = '/v1'
def delete_cached_image(self, image_id):
"""
Delete a specified image from the cache
"""
self.do_request("DELETE", "/cached_images/%s" % image_id)
return True
def get_cached_images(self, **kwargs):
"""
Returns a list of images stored in the image cache.
"""
res = self.do_request("GET", "/cached_images")
data = json.loads(res.read())['cached_images']
return data
def get_queued_images(self, **kwargs):
"""
Returns a list of images queued for caching
"""
res = self.do_request("GET", "/queued_images")
data = json.loads(res.read())['queued_images']
return data
def delete_all_cached_images(self):
"""
Delete all cached images
"""
res = self.do_request("DELETE", "/cached_images")
data = json.loads(res.read())
num_deleted = data['num_deleted']
return num_deleted
def queue_image_for_caching(self, image_id):
"""
Queue an image for prefetching into cache
"""
self.do_request("PUT", "/queued_images/%s" % image_id)
return True
def delete_queued_image(self, image_id):
"""
Delete a specified image from the cache queue
"""
self.do_request("DELETE", "/queued_images/%s" % image_id)
return True
def delete_all_queued_images(self):
"""
Delete all queued images
"""
res = self.do_request("DELETE", "/queued_images")
data = json.loads(res.read())
num_deleted = data['num_deleted']
return num_deleted
def get_client(host, port=None, timeout=None, use_ssl=False, username=None,
password=None, tenant=None,
auth_url=None, auth_strategy=None,
auth_token=None, region=None,
is_silent_upload=False, insecure=False):
"""
Returns a new client Glance client object based on common kwargs.
If an option isn't specified falls back to common environment variable
defaults.
"""
if auth_url or os.getenv('OS_AUTH_URL'):
force_strategy = 'keystone'
else:
force_strategy = None
creds = {
'username': username or
os.getenv('OS_AUTH_USER', os.getenv('OS_USERNAME')),
'password': password or
os.getenv('OS_AUTH_KEY', os.getenv('OS_PASSWORD')),
'tenant': tenant or
os.getenv('OS_AUTH_TENANT', os.getenv('OS_TENANT_NAME')),
'auth_url': auth_url or
os.getenv('OS_AUTH_URL'),
'strategy': force_strategy or
auth_strategy or
os.getenv('OS_AUTH_STRATEGY', 'noauth'),
'region': region or
os.getenv('OS_REGION_NAME'),
}
if creds['strategy'] == 'keystone' and not creds['auth_url']:
msg = _("--os_auth_url option or OS_AUTH_URL environment variable "
"required when keystone authentication strategy is enabled\n")
raise exception.ClientConfigurationError(msg)
return CacheClient(
host=host,
port=port,<|fim▁hole|> timeout=timeout,
use_ssl=use_ssl,
auth_token=auth_token or
os.getenv('OS_TOKEN'),
creds=creds,
insecure=insecure)<|fim▁end|> | |
<|file_name|>colorpicker-cmyk.ts<|end_file_name|><|fim▁begin|>// spell-checker:ignore cmyk, colorpicker
/**
* Specifies colors as a combination of cyan, magenta, yellow, and black.
*/
export interface SkyColorpickerCmyk {<|fim▁hole|> */
cyan: number;
/**
* Specifies the percentage of magenta to use.
*/
magenta: number;
/**
* Specifies the percentage of yellow to use.
*/
yellow: number;
/**
* Specifies the percentage of black to use.
*/
key: number;
}<|fim▁end|> | /**
* Specifies the percentage of cyan to use. |
<|file_name|>datatype-date-math.js<|end_file_name|><|fim▁begin|>YUI.add('datatype-date-math', function (Y, NAME) {
/**
* Date Math submodule.
*
* @module datatype-date
* @submodule datatype-date-math
* @for Date
*/
var LANG = Y.Lang;
Y.mix(Y.namespace("Date"), {
/**
* Checks whether a native JavaScript Date contains a valid value.
* @for Date
* @method isValidDate
* @param oDate {Date} Date in the month for which the number of days is desired.
* @return {Boolean} True if the date argument contains a valid value.
*/
isValidDate : function (oDate) {
if(LANG.isDate(oDate) && (isFinite(oDate)) && (oDate != "Invalid Date") && !isNaN(oDate) && (oDate != null)) {
return true;
}
else {
return false;
}
},
/**
* Checks whether two dates correspond to the same date and time.
* @for Date
* @method areEqual
* @param aDate {Date} The first date to compare.
* @param bDate {Date} The second date to compare.
* @return {Boolean} True if the two dates correspond to the same
* date and time.
*/
areEqual : function (aDate, bDate) {
return (this.isValidDate(aDate) && this.isValidDate(bDate) && (aDate.getTime() == bDate.getTime()));
},
/**
* Checks whether the first date comes later than the second.
* @for Date
* @method isGreater
* @param aDate {Date} The first date to compare.
* @param bDate {Date} The second date to compare.
* @return {Boolean} True if the first date is later than the second.
*/
isGreater : function (aDate, bDate) {
return (this.isValidDate(aDate) && this.isValidDate(bDate) && (aDate.getTime() > bDate.getTime()));
},
/**
* Checks whether the first date comes later than or is the same as
* the second.
* @for Date
* @method isGreaterOrEqual
* @param aDate {Date} The first date to compare.
* @param bDate {Date} The second date to compare.
* @return {Boolean} True if the first date is later than or
* the same as the second.
*/
isGreaterOrEqual : function (aDate, bDate) {
return (this.isValidDate(aDate) && this.isValidDate(bDate) && (aDate.getTime() >= bDate.getTime()));
},
/**
* Checks whether the date is between two other given dates.
* @for Date
* @method isInRange
* @param aDate {Date} The date to check
* @param bDate {Date} Lower bound of the range.
* @param cDate {Date} Higher bound of the range.
* @return {Boolean} True if the date is between the two other given dates.
*/
isInRange : function (aDate, bDate, cDate) {
return (this.isGreaterOrEqual(aDate, bDate) && this.isGreaterOrEqual(cDate, aDate));
},
/**
* Adds a specified number of days to the given date.
* @for Date
* @method addDays
* @param oDate {Date} The date to add days to.
* @param numDays {Number} The number of days to add (can be negative)
* @return {Date} A new Date with the specified number of days
* added to the original date.
*/
addDays : function (oDate, numDays) {
return new Date(oDate.getTime() + 86400000*numDays);
},
/**
* Adds a specified number of months to the given date.
* @for Date
* @method addMonths
* @param oDate {Date} The date to add months to.
* @param numMonths {Number} The number of months to add (can be negative)
* @return {Date} A new Date with the specified number of months
* added to the original date.
*/
addMonths : function (oDate, numMonths) {
var newYear = oDate.getFullYear();
var newMonth = oDate.getMonth() + numMonths;
newYear = Math.floor(newYear + newMonth / 12);
newMonth = (newMonth % 12 + 12) % 12;
var newDate = new Date (oDate.getTime());<|fim▁hole|> },
/**
* Adds a specified number of years to the given date.
* @for Date
* @method addYears
* @param oDate {Date} The date to add years to.
* @param numYears {Number} The number of years to add (can be negative)
* @return {Date} A new Date with the specified number of years
* added to the original date.
*/
addYears : function (oDate, numYears) {
var newYear = oDate.getFullYear() + numYears;
var newDate = new Date(oDate.getTime());
newDate.setFullYear(newYear);
return newDate;
},
/**
* Lists all dates in a given month.
* @for Date
* @method listOfDatesInMonth
* @param oDate {Date} The date corresponding to the month for
* which a list of dates is required.
* @return {Array} An `Array` of `Date`s from a given month.
*/
listOfDatesInMonth : function (oDate) {
if (!this.isValidDate(oDate)) {
return [];
}
var daysInMonth = this.daysInMonth(oDate),
year = oDate.getFullYear(),
month = oDate.getMonth(),
output = [];
for (var day = 1; day <= daysInMonth; day++) {
output.push(new Date(year, month, day, 12, 0, 0));
}
return output;
},
/**
* Takes a native JavaScript Date and returns the number of days
* in the month that the given date belongs to.
* @for Date
* @method daysInMonth
* @param oDate {Date} Date in the month for which the number
* of days is desired.
* @return {Number} A number (either 28, 29, 30 or 31) of days
* in the given month.
*/
daysInMonth : function (oDate) {
if (!this.isValidDate(oDate)) {
return 0;
}
var mon = oDate.getMonth();
var lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (mon != 1) {
return lengths[mon];
}
else {
var year = oDate.getFullYear();
if (year%400 === 0) {
return 29;
}
else if (year%100 === 0) {
return 28;
}
else if (year%4 === 0) {
return 29;
}
else {
return 28;
}
}
}
});
Y.namespace("DataType");
Y.DataType.Date = Y.Date;
}, '@VERSION@', {"requires": ["yui-base"]});<|fim▁end|> | newDate.setFullYear(newYear);
newDate.setMonth(newMonth);
return newDate; |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.