prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""TailorDev Biblio
Bibliography management with Django.<|fim▁hole|>"""
__version__ = "2.0.0"
default_app_config = "td_biblio.apps.TDBiblioConfig"<|fim▁end|> | |
<|file_name|>gai-print.js<|end_file_name|><|fim▁begin|>#!/usr/bin/env node
'use strict';
var colors = require('ansicolors')
var table = require('text-table')
if (process.argv.length < 3) {<|fim▁hole|>} else {
var steps= require(process.argv[2]).steps
print(steps);
}
function fromStdin() {
var data = [];
function onerror(err) {
console.error('gai-pring-js ', err)
}
process.stdin
.on('data', ondata)
.on('end', onend)
.on('error', onerror)
function ondata(d) {
data.push(d);
}
function onend() {
var json = Buffer.concat(data).toString();
try {
print(JSON.parse(json).steps);
} catch(err) {
console.error(json);
console.error(err);
}
}
}
function tableize(step) {
var first = true;
function toString(acc, k) {
if (k === 'eip') return acc; // instruction pointer always changes and isn't important here
var d = step.diff[k];
var s = acc;
s += first ? ';' : ',';
s += ' ' + k + ': ' + d.prev.hex + ' -> ' + d.curr.hex;
if (k === 'eflags') s += ' ' + d.curr.flagsString;
first = false;
return s;
}
var diffString = step.diff
? Object.keys(step.diff).reduce(toString, '')
: ''
var m = step.instruction.match(/^([a-f0-9]{2} )+/);
var opcodes = m[0].trim()
, inst = step.instruction.replace(opcodes, '').trim();
return [ colors.brightBlack(step.address), colors.brightBlue(opcodes), colors.green(inst), colors.brightBlack(diffString) ];
}
function print(steps) {
var tableized = steps.map(tableize);
console.log(table(tableized));
}<|fim▁end|> | fromStdin(); |
<|file_name|>edit_post.js<|end_file_name|><|fim▁begin|>// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {PostOptions} from '@support/ui/component';
import {isAndroid} from '@support/utils';
class EditPostScreen {
testID = {
editPostScreen: 'edit_post.screen',
closeEditPostButton: 'close.edit_post.button',
messageInput: 'edit_post.message.input',
saveButton: 'edit_post.save.button',
};
editPostScreen = element(by.id(this.testID.editPostScreen));
closeEditPostButton = element(by.id(this.testID.closeEditPostButton));
messageInput = element(by.id(this.testID.messageInput));
saveButton = element(by.id(this.testID.saveButton));
toBeVisible = async () => {
if (isAndroid()) {
await expect(this.editPostScreen).toBeVisible();
} else {
await expect(this.editPostScreen).toExist();
}
return this.editPostScreen;
};
open = async () => {
// # Swipe up panel on Android
if (isAndroid()) {
await PostOptions.slideUpPanel.swipe('up');
}
// # Open edit post screen
await PostOptions.editAction.tap();
return this.toBeVisible();
};
close = async () => {<|fim▁hole|> await expect(this.editPostScreen).not.toBeVisible();
};
}
const editPostScreen = new EditPostScreen();
export default editPostScreen;<|fim▁end|> | await this.closeEditPostButton.tap(); |
<|file_name|>_insert_trc_infoDetail.hpp<|end_file_name|><|fim▁begin|>// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
<|fim▁hole|>START_ATF_NAMESPACE
namespace Detail
{
extern ::std::array<hook_record, 1> _insert_trc_info_functions;
}; // end namespace Detail
END_ATF_NAMESPACE<|fim▁end|> | #include <common/common.h>
#include <_insert_trc_infoInfo.hpp>
|
<|file_name|>target_dashboard.rs<|end_file_name|><|fim▁begin|>// Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
components::{
dashboard::{dashboard_container, performance_container},
datepicker,
grafana_chart::{self, create_chart_params, IML_METRICS_DASHBOARD_ID, IML_METRICS_DASHBOARD_NAME},
},
generated::css_classes::C,
GMsg,
};
use iml_wire_types::warp_drive::ArcCache;
use seed::{prelude::*, *};
#[derive(Default)]
pub struct Model {
pub target_name: String,
pub io_date_picker: datepicker::Model,
}
#[derive(Clone, Debug)]
pub enum Msg {
IoChart(datepicker::Msg),
}<|fim▁hole|> MdtDashboard,
OstDashboard,
}
impl From<&str> for TargetDashboard {
fn from(item: &str) -> Self {
if item.contains("OST") {
Self::OstDashboard
} else {
Self::MdtDashboard
}
}
}
pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg, GMsg>) {
match msg {
Msg::IoChart(msg) => {
datepicker::update(msg, &mut model.io_date_picker, &mut orders.proxy(Msg::IoChart));
}
}
}
pub fn view(_: &ArcCache, model: &Model) -> Node<Msg> {
let dashboard_type: TargetDashboard = (model.target_name.as_str()).into();
div![
class![C.grid, C.lg__grid_cols_2, C.gap_6],
match dashboard_type {
TargetDashboard::MdtDashboard => vec![
dashboard_container::view(
"Metadata Operations",
div![
class![C.h_full, C.min_h_80, C.p_2],
grafana_chart::view(
IML_METRICS_DASHBOARD_ID,
IML_METRICS_DASHBOARD_NAME,
create_chart_params(37, "10s", vec![("target_name", &model.target_name)]),
"90%",
),
],
),
dashboard_container::view(
"Space Usage",
div![
class![C.h_full, C.min_h_80, C.p_2],
grafana_chart::view(
IML_METRICS_DASHBOARD_ID,
IML_METRICS_DASHBOARD_NAME,
create_chart_params(14, "10s", vec![("target_name", &model.target_name)]),
"90%",
),
],
),
dashboard_container::view(
"File Usage",
div![
class![C.h_full, C.min_h_80, C.p_2],
grafana_chart::view(
IML_METRICS_DASHBOARD_ID,
IML_METRICS_DASHBOARD_NAME,
create_chart_params(16, "10s", vec![("target_name", &model.target_name)]),
"90%",
),
],
)
],
TargetDashboard::OstDashboard => vec![
dashboard_container::view(
"I/O Performance",
performance_container(
&model.io_date_picker,
39,
38,
vec![
("target_name", &model.target_name),
("from", &model.io_date_picker.from),
("to", &model.io_date_picker.to)
]
)
.map_msg(Msg::IoChart),
),
dashboard_container::view(
"Space Usage",
div![
class![C.h_full, C.min_h_80, C.p_2],
grafana_chart::view(
IML_METRICS_DASHBOARD_ID,
IML_METRICS_DASHBOARD_NAME,
create_chart_params(14, "10s", vec![("target_name", &model.target_name)]),
"90%",
),
],
),
dashboard_container::view(
"Object Usage",
div![
class![C.h_full, C.min_h_80, C.p_2],
grafana_chart::view(
IML_METRICS_DASHBOARD_ID,
IML_METRICS_DASHBOARD_NAME,
create_chart_params(16, "10s", vec![("target_name", &model.target_name)]),
"90%",
),
],
)
],
}
]
}<|fim▁end|> |
pub enum TargetDashboard { |
<|file_name|>0009_brewpispark_spark_time.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-<|fim▁hole|>
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0008_auto_20150405_1435'),
]
operations = [
migrations.AddField(
model_name='brewpispark',
name='spark_time',
field=models.BigIntegerField(default=0, verbose_name=b'Spark Time'),
preserve_default=True,
),
]<|fim▁end|> | from __future__ import unicode_literals |
<|file_name|>ABI41_0_0AndroidDialogPickerProps.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ABI41_0_0AndroidDialogPickerProps.h"
#include <ABI41_0_0React/components/image/conversions.h>
#include <ABI41_0_0React/core/propsConversions.h>
namespace ABI41_0_0facebook {
namespace ABI41_0_0React {
AndroidDialogPickerProps::AndroidDialogPickerProps(
const AndroidDialogPickerProps &sourceProps,
const RawProps &rawProps)
: ViewProps(sourceProps, rawProps),
color(convertRawProp(rawProps, "color", sourceProps.color, {})),
enabled(convertRawProp(rawProps, "enabled", sourceProps.enabled, {true})),
items(convertRawProp(rawProps, "items", sourceProps.items, {})),
prompt(convertRawProp(rawProps, "prompt", sourceProps.prompt, {""})),
selected(
convertRawProp(rawProps, "selected", sourceProps.selected, {0})) {}
} // namespace ABI41_0_0React<|fim▁hole|><|fim▁end|> | } // namespace ABI41_0_0facebook |
<|file_name|>table_row.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use block::{BlockFlow, ISizeAndMarginsComputer};
use context::LayoutContext;
use cssparser::{Color, RGBA};
use display_list_builder::{BlockFlowDisplayListBuilding, BorderPaintingMode};
use euclid::{Point2D, Rect};
use flow::{self, EarlyAbsolutePositionInfo, Flow, FlowClass, ImmutableFlowUtils, OpaqueFlow};
use flow_list::MutFlowListIterator;
use fragment::{Fragment, FragmentBorderBoxIterator};
use gfx::display_list::DisplayList;
use layout_debug;
use model::MaybeAuto;
use rustc_serialize::{Encodable, Encoder};
use std::cmp::max;
use std::fmt;
use std::iter::{Enumerate, IntoIterator, Peekable};
use std::sync::Arc;
use style::computed_values::{border_collapse, border_spacing, border_top_style};
use style::properties::ComputedValues;
use style::values::computed::LengthOrPercentageOrAuto;
use table::{ColumnComputedInlineSize, ColumnIntrinsicInlineSize, InternalTable, VecExt};
use table_cell::{CollapsedBordersForCell, TableCellFlow};
use util::logical_geometry::{LogicalSize, PhysicalSide, WritingMode};
use util::print_tree::PrintTree;
/// A single row of a table.
pub struct TableRowFlow {
/// Fields common to all block flows.
pub block_flow: BlockFlow,
/// Information about the intrinsic inline-sizes of each cell.
pub cell_intrinsic_inline_sizes: Vec<CellIntrinsicInlineSize>,
/// Information about the computed inline-sizes of each column.
pub column_computed_inline_sizes: Vec<ColumnComputedInlineSize>,
/// The spacing for this row, propagated down from the table during the inline-size assignment
/// phase.
pub spacing: border_spacing::T,
/// The direction of the columns, propagated down from the table during the inline-size
/// assignment phase.
pub table_writing_mode: WritingMode,
/// Information about the borders for each cell that we bubble up to our parent. This is only
/// computed if `border-collapse` is `collapse`.
pub preliminary_collapsed_borders: CollapsedBordersForRow,
/// Information about the borders for each cell, post-collapse. This is only computed if
/// `border-collapse` is `collapse`.
pub final_collapsed_borders: CollapsedBordersForRow,
/// The computed cell spacing widths post-collapse.
pub collapsed_border_spacing: CollapsedBorderSpacingForRow,
}
impl Encodable for TableRowFlow {
fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
self.block_flow.encode(e)
}
}
/// Information about the column inline size and span for each cell.
#[derive(RustcEncodable, Copy, Clone)]
pub struct CellIntrinsicInlineSize {
/// Inline sizes that this cell contributes to the column.
pub column_size: ColumnIntrinsicInlineSize,
/// The column span of this cell.
pub column_span: u32,
}
impl TableRowFlow {
pub fn from_fragment(fragment: Fragment) -> TableRowFlow {
let writing_mode = fragment.style().writing_mode;
TableRowFlow {
block_flow: BlockFlow::from_fragment(fragment, None),
cell_intrinsic_inline_sizes: Vec::new(),
column_computed_inline_sizes: Vec::new(),
spacing: border_spacing::T {
horizontal: Au(0),
vertical: Au(0),
},
table_writing_mode: writing_mode,
preliminary_collapsed_borders: CollapsedBordersForRow::new(),
final_collapsed_borders: CollapsedBordersForRow::new(),
collapsed_border_spacing: CollapsedBorderSpacingForRow::new(),
}
}
/// Assign block-size for table-row flow.
///
/// TODO(pcwalton): This doesn't handle floats and positioned elements right.
///
/// inline(always) because this is only ever called by in-order or non-in-order top-level
/// methods
#[inline(always)]
fn assign_block_size_table_row_base(&mut self, layout_context: &LayoutContext) {
// Per CSS 2.1 § 17.5.3, find max_y = max(computed `block-size`, minimum block-size of all
// cells).
let mut max_block_size = Au(0);
let thread_id = self.block_flow.base.thread_id;
for kid in self.block_flow.base.child_iter() {
kid.place_float_if_applicable(layout_context);
if !flow::base(kid).flags.is_float() {
kid.assign_block_size_for_inorder_child_if_necessary(layout_context, thread_id);
}
{
let child_fragment = kid.as_mut_table_cell().fragment();
// TODO: Percentage block-size
let child_specified_block_size =
MaybeAuto::from_style(child_fragment.style().content_block_size(),
Au(0)).specified_or_zero();
max_block_size =
max(max_block_size,
child_specified_block_size +
child_fragment.border_padding.block_start_end());
}
let child_node = flow::mut_base(kid);
child_node.position.start.b = Au(0);
max_block_size = max(max_block_size, child_node.position.size.block);
}
let mut block_size = max_block_size;
// TODO: Percentage block-size
block_size = match MaybeAuto::from_style(self.block_flow
.fragment
.style()
.content_block_size(),
Au(0)) {
MaybeAuto::Auto => block_size,
MaybeAuto::Specified(value) => max(value, block_size),
};
// Assign the block-size of own fragment
let mut position = self.block_flow.fragment.border_box;
position.size.block = block_size;
self.block_flow.fragment.border_box = position;
self.block_flow.base.position.size.block = block_size;
// Assign the block-size of kid fragments, which is the same value as own block-size.
for kid in self.block_flow.base.child_iter() {
let child_table_cell = kid.as_mut_table_cell();
{
let kid_fragment = child_table_cell.mut_fragment();
let mut position = kid_fragment.border_box;
position.size.block = block_size;
kid_fragment.border_box = position;
}
// Assign the child's block size.
child_table_cell.block_flow.base.position.size.block = block_size;
// Write in the size of the relative containing block for children. (This information
// is also needed to handle RTL.)
child_table_cell.block_flow.base.early_absolute_position_info =
EarlyAbsolutePositionInfo {
relative_containing_block_size: self.block_flow.fragment.content_box().size,
relative_containing_block_mode: self.block_flow.fragment.style().writing_mode,
};
}
}
pub fn populate_collapsed_border_spacing<'a, I>(
&mut self,
collapsed_inline_direction_border_widths_for_table: &[Au],
collapsed_block_direction_border_widths_for_table: &mut Peekable<I>)
where I: Iterator<Item=&'a Au> {
self.collapsed_border_spacing.inline.clear();
self.collapsed_border_spacing
.inline
.extend(collapsed_inline_direction_border_widths_for_table.into_iter().map(|x| *x));
if let Some(collapsed_block_direction_border_width_for_table) =
collapsed_block_direction_border_widths_for_table.next() {
self.collapsed_border_spacing.block_start =
*collapsed_block_direction_border_width_for_table
}
if let Some(collapsed_block_direction_border_width_for_table) =
collapsed_block_direction_border_widths_for_table.peek() {
self.collapsed_border_spacing.block_end =
**collapsed_block_direction_border_width_for_table
}
}
}
impl Flow for TableRowFlow {
fn class(&self) -> FlowClass {
FlowClass::TableRow
}
fn as_mut_table_row(&mut self) -> &mut TableRowFlow {
self
}
fn as_table_row(&self) -> &TableRowFlow {
self
}
fn as_mut_block(&mut self) -> &mut BlockFlow {
&mut self.block_flow
}
fn as_block(&self) -> &BlockFlow {
&self.block_flow
}
fn column_intrinsic_inline_sizes(&mut self) -> &mut Vec<ColumnIntrinsicInlineSize> {
panic!("can't call column_intrinsic_inline_sizes() on table row")
}
fn column_computed_inline_sizes(&mut self) -> &mut Vec<ColumnComputedInlineSize> {
&mut self.column_computed_inline_sizes
}
/// Recursively (bottom-up) determines the context's preferred and minimum inline-sizes. When
/// called on this context, all child contexts have had their min/pref inline-sizes set. This
/// function must decide min/pref inline-sizes based on child context inline-sizes and
/// dimensions of any fragments it is responsible for flowing.
/// Min/pref inline-sizes set by this function are used in automatic table layout calculation.
/// The specified column inline-sizes of children cells are used in fixed table layout
/// calculation.
fn bubble_inline_sizes(&mut self) {
let _scope = layout_debug_scope!("table_row::bubble_inline_sizes {:x}",
self.block_flow.base.debug_id());
// Bubble up the specified inline-sizes from child table cells.
let (mut min_inline_size, mut pref_inline_size) = (Au(0), Au(0));
let collapsing_borders = self.block_flow
.fragment
.style()
.get_inheritedtable()
.border_collapse == border_collapse::T::collapse;
// FIXME(pcwalton): Shouldn't use `CollapsedBorder::new()` here.
self.preliminary_collapsed_borders.reset(CollapsedBorder::new());
{
let mut iterator = self.block_flow.base.child_iter().enumerate().peekable();
while let Some((i, kid)) = iterator.next() {
assert!(kid.is_table_cell());
// Collect the specified column inline-size of the cell. This is used in both
// fixed and automatic table layout calculation.
let child_specified_inline_size;
let child_column_span;
{
let child_table_cell = kid.as_mut_table_cell();
child_specified_inline_size = child_table_cell.block_flow
.fragment
.style
.content_inline_size();
child_column_span = child_table_cell.column_span;
// Perform border collapse if necessary.
if collapsing_borders {
perform_inline_direction_border_collapse_for_row(
i,
child_table_cell,
&mut iterator,
&mut self.preliminary_collapsed_borders)
}
}
// Collect minimum and preferred inline-sizes of the cell for automatic table layout
// calculation.
let child_base = flow::mut_base(kid);
let child_column_inline_size = ColumnIntrinsicInlineSize {
minimum_length: match child_specified_inline_size {
LengthOrPercentageOrAuto::Auto |
LengthOrPercentageOrAuto::Calc(_) |
LengthOrPercentageOrAuto::Percentage(_) => {
child_base.intrinsic_inline_sizes.minimum_inline_size
}
LengthOrPercentageOrAuto::Length(length) => length,
},
percentage: match child_specified_inline_size {
LengthOrPercentageOrAuto::Auto |
LengthOrPercentageOrAuto::Calc(_) |
LengthOrPercentageOrAuto::Length(_) => 0.0,
LengthOrPercentageOrAuto::Percentage(percentage) => percentage,
},
preferred: child_base.intrinsic_inline_sizes.preferred_inline_size,
constrained: match child_specified_inline_size {
LengthOrPercentageOrAuto::Length(_) => true,
LengthOrPercentageOrAuto::Auto |
LengthOrPercentageOrAuto::Calc(_) |
LengthOrPercentageOrAuto::Percentage(_) => false,
},
};
min_inline_size = min_inline_size + child_column_inline_size.minimum_length;
pref_inline_size = pref_inline_size + child_column_inline_size.preferred;
self.cell_intrinsic_inline_sizes.push(CellIntrinsicInlineSize {
column_size: child_column_inline_size,
column_span: child_column_span,
});
}
}
self.block_flow.base.intrinsic_inline_sizes.minimum_inline_size = min_inline_size;
self.block_flow.base.intrinsic_inline_sizes.preferred_inline_size = max(min_inline_size,
pref_inline_size);
}
fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) {
let _scope = layout_debug_scope!("table_row::assign_inline_sizes {:x}",
self.block_flow.base.debug_id());
debug!("assign_inline_sizes({}): assigning inline_size for flow", "table_row");
// The position was set to the containing block by the flow's parent.
let containing_block_inline_size = self.block_flow.base.block_container_inline_size;
// FIXME: In case of border-collapse: collapse, inline_start_content_edge should be
// border_inline_start.
let inline_start_content_edge = Au(0);
let inline_end_content_edge = Au(0);
let inline_size_computer = InternalTable {
border_collapse: self.block_flow.fragment.style.get_inheritedtable().border_collapse,
};
inline_size_computer.compute_used_inline_size(&mut self.block_flow,
layout_context,
containing_block_inline_size);
// Spread out the completed inline sizes among columns with spans > 1.
let mut computed_inline_size_for_cells = Vec::new();
let mut column_computed_inline_size_iterator = self.column_computed_inline_sizes.iter();
for cell_intrinsic_inline_size in &self.cell_intrinsic_inline_sizes {
// Start with the computed inline size for the first column in the span.
let mut column_computed_inline_size =
match column_computed_inline_size_iterator.next() {
Some(column_computed_inline_size) => *column_computed_inline_size,
None => {
// We're in fixed layout mode and there are more cells in this row than
// columns we know about. According to CSS 2.1 § 17.5.2.1, the behavior is
// now undefined. So just use zero.
//
// FIXME(pcwalton): $10 says this isn't Web compatible.
ColumnComputedInlineSize {
size: Au(0),
}
}
};
// Add in computed inline sizes for any extra columns in the span.
for _ in 1..cell_intrinsic_inline_size.column_span {
let extra_column_computed_inline_size =
match column_computed_inline_size_iterator.next() {
Some(column_computed_inline_size) => column_computed_inline_size,
None => break,
};
column_computed_inline_size.size = column_computed_inline_size.size +
extra_column_computed_inline_size.size;
}
computed_inline_size_for_cells.push(column_computed_inline_size)
}
// Set up border collapse info.
let border_collapse_info =
match self.block_flow.fragment.style().get_inheritedtable().border_collapse {
border_collapse::T::collapse => {
Some(BorderCollapseInfoForChildTableCell {
collapsed_borders_for_row: &self.final_collapsed_borders,
collapsed_border_spacing_for_row: &self.collapsed_border_spacing,
})
}
border_collapse::T::separate => None,
};
// Push those inline sizes down to the cells.
let spacing = self.spacing;
let row_writing_mode = self.block_flow.base.writing_mode;
let table_writing_mode = self.table_writing_mode;
self.block_flow.propagate_assigned_inline_size_to_children(layout_context,
inline_start_content_edge,
inline_end_content_edge,
containing_block_inline_size,
|child_flow,
child_index,
content_inline_size,
_writing_mode,
inline_start_margin_edge,
inline_end_margin_edge| {
set_inline_position_of_child_flow(
child_flow,
child_index,
row_writing_mode,
table_writing_mode,
&computed_inline_size_for_cells,
&spacing,
&border_collapse_info,
content_inline_size,
inline_start_margin_edge,
inline_end_margin_edge);
})
}
fn assign_block_size(&mut self, layout_context: &LayoutContext) {
debug!("assign_block_size: assigning block_size for table_row");
self.assign_block_size_table_row_base(layout_context);
}
fn compute_absolute_position(&mut self, layout_context: &LayoutContext) {
self.block_flow.compute_absolute_position(layout_context)
}
fn update_late_computed_inline_position_if_necessary(&mut self, inline_position: Au) {
self.block_flow.update_late_computed_inline_position_if_necessary(inline_position)
}
fn update_late_computed_block_position_if_necessary(&mut self, block_position: Au) {
self.block_flow.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, layout_context: &LayoutContext) {
let border_painting_mode = match self.block_flow
.fragment
.style
.get_inheritedtable()
.border_collapse {
border_collapse::T::separate => BorderPaintingMode::Separate,
border_collapse::T::collapse => BorderPaintingMode::Hidden,
};
self.block_flow.build_display_list_for_block(box DisplayList::new(),
layout_context,
border_painting_mode);
}
fn repair_style(&mut self, new_style: &Arc<ComputedValues>) {
self.block_flow.repair_style(new_style)
}
fn compute_overflow(&self) -> Rect<Au> {
self.block_flow.compute_overflow()
}
fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> {
self.block_flow.generated_containing_block_size(flow)
}
fn iterate_through_fragment_border_boxes(&self,
iterator: &mut FragmentBorderBoxIterator,
level: i32,
stacking_context_position: &Point2D<Au>) {
self.block_flow.iterate_through_fragment_border_boxes(iterator, level, stacking_context_position)
}
fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) {
self.block_flow.mutate_fragments(mutator)
}
fn print_extra_flow_children(&self, print_tree: &mut PrintTree) {
self.block_flow.print_extra_flow_children(print_tree);
}
}
impl fmt::Debug for TableRowFlow {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TableRowFlow: {:?}", self.block_flow)
}
}
#[derive(Clone, Debug)]
pub struct CollapsedBordersForRow {
/// The size of this vector should be equal to the number of cells plus one.
pub inline: Vec<CollapsedBorder>,
/// The size of this vector should be equal to the number of cells.
pub block_start: Vec<CollapsedBorder>,
/// The size of this vector should be equal to the number of cells.
pub block_end: Vec<CollapsedBorder>,
}
impl CollapsedBordersForRow {
pub fn new() -> CollapsedBordersForRow {
CollapsedBordersForRow {
inline: Vec::new(),
block_start: Vec::new(),
block_end: Vec::new(),
}
}
pub fn reset(&mut self, first_inline_border: CollapsedBorder) {
self.inline.clear();
self.inline.push(first_inline_border);
self.block_start.clear();
self.block_end.clear()
}
}
#[derive(Clone, Debug)]
pub struct CollapsedBorderSpacingForRow {
/// The spacing in between each column.
inline: Vec<Au>,
/// The spacing above this row.
pub block_start: Au,
/// The spacing below this row.
block_end: Au,
}
impl CollapsedBorderSpacingForRow {
fn new() -> CollapsedBorderSpacingForRow {
CollapsedBorderSpacingForRow {
inline: Vec::new(),
block_start: Au(0),
block_end: Au(0),
}
}
}
<|fim▁hole|>/// All aspects of a border that can collapse with adjacent borders. See CSS 2.1 § 17.6.2.1.
#[derive(Copy, Clone, Debug)]
pub struct CollapsedBorder {
/// The style of the border.
pub style: border_top_style::T,
/// The width of the border.
pub width: Au,
/// The color of the border.
pub color: Color,
/// The type of item that this border comes from.
pub provenance: CollapsedBorderProvenance,
}
impl Encodable for CollapsedBorder {
fn encode<S: Encoder>(&self, _: &mut S) -> Result<(), S::Error> {
Ok(())
}
}
/// Where a border style comes from.
///
/// The integer values here correspond to the border conflict resolution rules in CSS 2.1 §
/// 17.6.2.1. Higher values override lower values.
// FIXME(#8586): FromTableRow, FromTableRowGroup, FromTableColumn,
// FromTableColumnGroup are unused
#[allow(dead_code)]
#[derive(Copy, Clone, Debug, PartialEq, RustcEncodable)]
pub enum CollapsedBorderProvenance {
FromPreviousTableCell = 6,
FromNextTableCell = 5,
FromTableRow = 4,
FromTableRowGroup = 3,
FromTableColumn = 2,
FromTableColumnGroup = 1,
FromTable = 0,
}
impl CollapsedBorder {
/// Creates a collapsible border style for no border.
pub fn new() -> CollapsedBorder {
CollapsedBorder {
style: border_top_style::T::none,
width: Au(0),
color: Color::RGBA(RGBA {
red: 0.0,
green: 0.0,
blue: 0.0,
alpha: 0.0,
}),
provenance: CollapsedBorderProvenance::FromTable,
}
}
/// Creates a collapsed border from the block-start border described in the given CSS style
/// object.
fn top(css_style: &ComputedValues, provenance: CollapsedBorderProvenance)
-> CollapsedBorder {
CollapsedBorder {
style: css_style.get_border().border_top_style,
width: css_style.get_border().border_top_width,
color: css_style.get_border().border_top_color,
provenance: provenance,
}
}
/// Creates a collapsed border style from the right border described in the given CSS style
/// object.
fn right(css_style: &ComputedValues, provenance: CollapsedBorderProvenance)
-> CollapsedBorder {
CollapsedBorder {
style: css_style.get_border().border_right_style,
width: css_style.get_border().border_right_width,
color: css_style.get_border().border_right_color,
provenance: provenance,
}
}
/// Creates a collapsed border style from the bottom border described in the given CSS style
/// object.
fn bottom(css_style: &ComputedValues, provenance: CollapsedBorderProvenance)
-> CollapsedBorder {
CollapsedBorder {
style: css_style.get_border().border_bottom_style,
width: css_style.get_border().border_bottom_width,
color: css_style.get_border().border_bottom_color,
provenance: provenance,
}
}
/// Creates a collapsed border style from the left border described in the given CSS style
/// object.
fn left(css_style: &ComputedValues, provenance: CollapsedBorderProvenance)
-> CollapsedBorder {
CollapsedBorder {
style: css_style.get_border().border_left_style,
width: css_style.get_border().border_left_width,
color: css_style.get_border().border_left_color,
provenance: provenance,
}
}
/// Creates a collapsed border style from the given physical side.
fn from_side(side: PhysicalSide,
css_style: &ComputedValues,
provenance: CollapsedBorderProvenance)
-> CollapsedBorder {
match side {
PhysicalSide::Top => CollapsedBorder::top(css_style, provenance),
PhysicalSide::Right => CollapsedBorder::right(css_style, provenance),
PhysicalSide::Bottom => CollapsedBorder::bottom(css_style, provenance),
PhysicalSide::Left => CollapsedBorder::left(css_style, provenance),
}
}
/// Creates a collapsed border style from the inline-start border described in the given CSS
/// style object.
pub fn inline_start(css_style: &ComputedValues, provenance: CollapsedBorderProvenance)
-> CollapsedBorder {
CollapsedBorder::from_side(css_style.writing_mode.inline_start_physical_side(),
css_style,
provenance)
}
/// Creates a collapsed border style from the inline-start border described in the given CSS
/// style object.
pub fn inline_end(css_style: &ComputedValues, provenance: CollapsedBorderProvenance)
-> CollapsedBorder {
CollapsedBorder::from_side(css_style.writing_mode.inline_end_physical_side(),
css_style,
provenance)
}
/// Creates a collapsed border style from the block-start border described in the given CSS
/// style object.
pub fn block_start(css_style: &ComputedValues, provenance: CollapsedBorderProvenance)
-> CollapsedBorder {
CollapsedBorder::from_side(css_style.writing_mode.block_start_physical_side(),
css_style,
provenance)
}
/// Creates a collapsed border style from the block-end border described in the given CSS style
/// object.
pub fn block_end(css_style: &ComputedValues, provenance: CollapsedBorderProvenance)
-> CollapsedBorder {
CollapsedBorder::from_side(css_style.writing_mode.block_end_physical_side(),
css_style,
provenance)
}
/// If `other` has a higher priority per CSS 2.1 § 17.6.2.1, replaces `self` with it.
pub fn combine(&mut self, other: &CollapsedBorder) {
match (self.style, other.style) {
// Step 1.
(border_top_style::T::hidden, _) => {}
(_, border_top_style::T::hidden) => *self = *other,
// Step 2.
(border_top_style::T::none, _) => *self = *other,
(_, border_top_style::T::none) => {}
// Step 3.
_ if self.width > other.width => {}
_ if self.width < other.width => *self = *other,
(this_style, other_style) if this_style > other_style => {}
(this_style, other_style) if this_style < other_style => *self = *other,
// Step 4.
_ if (self.provenance as i8) >= other.provenance as i8 => {}
_ => *self = *other,
}
}
}
/// Pushes column inline size and border collapse info down to a child.
pub fn propagate_column_inline_sizes_to_child(
child_flow: &mut Flow,
table_writing_mode: WritingMode,
column_computed_inline_sizes: &[ColumnComputedInlineSize],
border_spacing: &border_spacing::T) {
// If the child is a row group or a row, the column inline-size info should be copied from its
// parent.
//
// FIXME(pcwalton): This seems inefficient. Reference count it instead?
match child_flow.class() {
FlowClass::Table => {
let child_table_flow = child_flow.as_mut_table();
child_table_flow.column_computed_inline_sizes = column_computed_inline_sizes.to_vec();
}
FlowClass::TableRowGroup => {
let child_table_rowgroup_flow = child_flow.as_mut_table_rowgroup();
child_table_rowgroup_flow.column_computed_inline_sizes =
column_computed_inline_sizes.to_vec();
child_table_rowgroup_flow.spacing = *border_spacing;
child_table_rowgroup_flow.table_writing_mode = table_writing_mode;
}
FlowClass::TableRow => {
let child_table_row_flow = child_flow.as_mut_table_row();
child_table_row_flow.column_computed_inline_sizes =
column_computed_inline_sizes.to_vec();
child_table_row_flow.spacing = *border_spacing;
child_table_row_flow.table_writing_mode = table_writing_mode;
}
c => warn!("unexpected flow in table {:?}", c)
}
}
/// Lay out table cells inline according to the computer column sizes.
fn set_inline_position_of_child_flow(
child_flow: &mut Flow,
child_index: usize,
row_writing_mode: WritingMode,
table_writing_mode: WritingMode,
column_computed_inline_sizes: &[ColumnComputedInlineSize],
border_spacing: &border_spacing::T,
border_collapse_info: &Option<BorderCollapseInfoForChildTableCell>,
parent_content_inline_size: Au,
inline_start_margin_edge: &mut Au,
inline_end_margin_edge: &mut Au) {
if !child_flow.is_table_cell() {
return
}
let reverse_column_order = table_writing_mode.is_bidi_ltr() != row_writing_mode.is_bidi_ltr();
// Handle border collapsing, if necessary.
let child_table_cell = child_flow.as_mut_table_cell();
match *border_collapse_info {
Some(ref border_collapse_info) => {
// Write in the child's border collapse state.
child_table_cell.collapsed_borders = CollapsedBordersForCell {
inline_start_border: border_collapse_info.collapsed_borders_for_row
.inline
.get(child_index)
.map_or(CollapsedBorder::new(), |x| *x),
inline_end_border: border_collapse_info.collapsed_borders_for_row
.inline
.get(child_index + 1)
.map_or(CollapsedBorder::new(), |x| *x),
block_start_border: border_collapse_info.collapsed_borders_for_row
.block_start
.get(child_index)
.map_or(CollapsedBorder::new(), |x| *x),
block_end_border: border_collapse_info.collapsed_borders_for_row
.block_end
.get(child_index)
.map_or(CollapsedBorder::new(), |x| *x),
inline_start_width: border_collapse_info.collapsed_border_spacing_for_row
.inline
.get(child_index)
.map_or(Au(0), |x| *x),
inline_end_width: border_collapse_info.collapsed_border_spacing_for_row
.inline
.get(child_index + 1)
.map_or(Au(0), |x| *x),
block_start_width: border_collapse_info.collapsed_border_spacing_for_row
.block_start,
block_end_width: border_collapse_info.collapsed_border_spacing_for_row.block_end,
};
// Move over past the collapsed border.
if reverse_column_order {
*inline_end_margin_edge = *inline_end_margin_edge +
child_table_cell.collapsed_borders.inline_start_width
} else {
*inline_start_margin_edge = *inline_start_margin_edge +
child_table_cell.collapsed_borders.inline_start_width
}
}
None => {
// Take spacing into account.
if reverse_column_order {
*inline_end_margin_edge = *inline_end_margin_edge + border_spacing.horizontal
} else {
*inline_start_margin_edge = *inline_start_margin_edge + border_spacing.horizontal
}
}
}
let column_inline_size = column_computed_inline_sizes[child_index].size;
let kid_base = &mut child_table_cell.block_flow.base;
kid_base.block_container_inline_size = column_inline_size;
if reverse_column_order {
// Columns begin from the inline-end edge.
kid_base.position.start.i =
parent_content_inline_size - *inline_end_margin_edge - column_inline_size;
*inline_end_margin_edge = *inline_end_margin_edge + column_inline_size;
} else {
// Columns begin from the inline-start edge.
kid_base.position.start.i = *inline_start_margin_edge;
*inline_start_margin_edge = *inline_start_margin_edge + column_inline_size;
}
}
#[derive(Copy, Clone)]
pub struct BorderCollapseInfoForChildTableCell<'a> {
collapsed_borders_for_row: &'a CollapsedBordersForRow,
collapsed_border_spacing_for_row: &'a CollapsedBorderSpacingForRow,
}
/// Performs border-collapse in the inline direction for all the cells' inside borders in the
/// inline-direction cells and propagates the outside borders (the far left and right) up to the
/// table row. This is done eagerly here so that at least the inline inside border collapse
/// computations can be parallelized across all the rows of the table.
fn perform_inline_direction_border_collapse_for_row(
child_index: usize,
child_table_cell: &mut TableCellFlow,
iterator: &mut Peekable<Enumerate<MutFlowListIterator>>,
preliminary_collapsed_borders: &mut CollapsedBordersForRow) {
let inline_collapsed_border = preliminary_collapsed_borders.inline.push_or_mutate(
child_index + 1,
CollapsedBorder::inline_end(&*child_table_cell.block_flow.fragment.style,
CollapsedBorderProvenance::FromPreviousTableCell));
if let Some(&(_, ref next_child_flow)) = iterator.peek() {
let next_child_flow = next_child_flow.as_block();
inline_collapsed_border.combine(
&CollapsedBorder::inline_start(&*next_child_flow.fragment.style,
CollapsedBorderProvenance::FromNextTableCell))
};
let block_start_border =
CollapsedBorder::block_start(&*child_table_cell.block_flow.fragment.style,
CollapsedBorderProvenance::FromNextTableCell);
preliminary_collapsed_borders.block_start.push_or_mutate(child_index, block_start_border);
let block_end_border =
CollapsedBorder::block_end(&*child_table_cell.block_flow.fragment.style,
CollapsedBorderProvenance::FromPreviousTableCell);
preliminary_collapsed_borders.block_end.push_or_mutate(child_index, block_end_border);
}<|fim▁end|> | |
<|file_name|>DBParVal.java<|end_file_name|><|fim▁begin|>package br.com.zpi.lrws.conn;
import java.io.Serializable;
<|fim▁hole|> public String value = null;
}<|fim▁end|> | public class DBParVal implements Serializable{
private static final long serialVersionUID = 1L;
public String param = null; |
<|file_name|>run_command_document.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .run_command_document_base import RunCommandDocumentBase
class RunCommandDocument(RunCommandDocumentBase):
"""Describes the properties of a Run Command.
:param schema: The VM run command schema.
:type schema: str
:param id: The VM run command id.
:type id: str
:param os_type: The Operating System type. Possible values include:
'Windows', 'Linux'
:type os_type: str or
~azure.mgmt.compute.v2017_12_01.models.OperatingSystemTypes
:param label: The VM run command label.
:type label: str
:param description: The VM run command description.
:type description: str
:param script: The script to be executed.
:type script: list[str]
:param parameters: The parameters used by the script.
:type parameters:
list[~azure.mgmt.compute.v2017_12_01.models.RunCommandParameterDefinition]
"""
_validation = {
'schema': {'required': True},
'id': {'required': True},
'os_type': {'required': True},
'label': {'required': True},<|fim▁hole|> 'description': {'required': True},
'script': {'required': True},
}
_attribute_map = {
'schema': {'key': '$schema', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'os_type': {'key': 'osType', 'type': 'OperatingSystemTypes'},
'label': {'key': 'label', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'script': {'key': 'script', 'type': '[str]'},
'parameters': {'key': 'parameters', 'type': '[RunCommandParameterDefinition]'},
}
def __init__(self, schema, id, os_type, label, description, script, parameters=None):
super(RunCommandDocument, self).__init__(schema=schema, id=id, os_type=os_type, label=label, description=description)
self.script = script
self.parameters = parameters<|fim▁end|> | |
<|file_name|>ContentService.ts<|end_file_name|><|fim▁begin|>import { Element } from "./Element"
import * as request from "request-promise-native"
import { Environment } from "../environment"
export default class ContentService {
static createContent = function (name: string, typeId: string, elements: any[]) {
let data = {}
elements.forEach((tuple) => {
// [ key, elementData]
data[tuple[0]] = tuple[1]
})
return {
"name": name,
"status": "ready",
"typeId": typeId,
"elements": data
}
}
<|fim▁hole|> let response = await (<any>request).post(`${Environment.base}/authoring/v1/content`,
{
"headers": {
"Cookie": Environment.cookie
},
json: content
}
)
console.log(response)
return response
} catch (err) {
console.log(err)
throw err
}
}
}<|fim▁end|> | static create = async function (content: any) {
console.log("CREATING CONTENT")
console.log("ENVIRONMENT COOKIE" + Environment.cookie)
try { |
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from __future__ import print_function
import os
import sys
import subprocess
import pkg_resources
try:
import pkg_resources
_has_pkg_resources = True
except:
_has_pkg_resources = False
try:
import svn.local
_has_svn_local = True
except:
_has_svn_local = False
def test_helper():
return "test helper text"
def dict_to_str(d):
"""
Given a dictionary d, return a string with
each entry in the form 'key: value' and entries
separated by newlines.
"""
vals = []
for k in d.keys():
vals.append('{}: {}'.format(k, d[k]))
v = '\n'.join(vals)
return v
def module_version(module, label=None):
"""
Helper function for getting the module ("module") in the current
namespace and their versions.
The optional argument 'label' allows you to set the
string used as the dictionary key in the returned dictionary.
By default the key is '[module] version'.
"""
if not _has_pkg_resources:
return {}
version = pkg_resources.get_distribution(module).version
if label:
k = '{}'.format(label)
else:
k = '{} version'.format(module)
return {k: '{}'.format(version)}
def file_contents(filename, label=None):
"""
Helper function for getting the contents of a file,
provided the filename.<|fim▁hole|> where the value is a string containing the contents of the file.
The optional argument 'label' allows you to set the
string used as the dictionary key in the returned dictionary.
"""
if not os.path.isfile(filename):
print('ERROR: {} NOT FOUND.'.format(filename))
return {}
else:
fin = open(filename, 'r')
contents = ''
for l in fin:
contents += l
if label:
d = {'{}'.format(label): contents}
else:
d = {filename: contents}
return d
def svn_information(svndir=None, label=None):
"""
Helper function for obtaining the SVN repository
information for the current directory (default)
or the directory supplied in the svndir argument.
Returns a dictionary keyed (by default) as 'SVN INFO'
where the value is a string containing essentially what
is returned by 'svn info'.
The optional argument 'label' allows you to set the
string used as the dictionary key in the returned dictionary.
"""
if not _has_svn_local:
print('SVN information unavailable.')
print('You do not have the "svn" package installed.')
print('Install "svn" from pip using "pip install svn"')
return {}
if svndir:
repo = svn.local.LocalClient(svndir)
else:
repo = svn.local.LocalClient(os.getcwd())
try:
# Get a dictionary of the SVN repository information
info = repo.info()
except:
print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.')
return {}
v = dict_to_str(info)
if label:
k = '{}'.format(label)
else:
k = 'SVN INFO'
return {k: v}
def get_git_hash(gitpath=None, label=None):
"""
Helper function for obtaining the git repository hash.
for the current directory (default)
or the directory supplied in the gitpath argument.
Returns a dictionary keyed (by default) as 'GIT HASH'
where the value is a string containing essentially what
is returned by subprocess.
The optional argument 'label' allows you to set the string
used as the dictionary key in the returned dictionary.
"""
if gitpath:
thisdir = os.getcwd()
os.chdir(gitpath)
try:
sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip()
except subprocess.CalledProcessError as e:
print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY")
return {}
if label:
l = '{}'.format(label)
else:
l = 'GIT HASH'
return {l:sha}
def get_source_code(scode,sourcepath=None, label=None):
"""
Helper function for obtaining the source code.
for the current directory (default) or the directory
supplied in the sourcepath argument.
Returns a dictionary keyed (by default) as 'source code'
where the value is a string containing the source code.
The optional argument 'label' allows you to set the string
used as the dictionary key in the returned dictionary.
"""
if sourcepath:
os.chdir(sourcepath)
if not os.path.isfile(scode):
print('ERROR: {} NOT FOUND.'.format(scode))
return {}
else:
with open(scode,'r') as f:
s = f.read()
if label:
n = {'{}'.format(label):s}
else:
n = {'source code':s}
return n<|fim▁end|> |
Returns a dictionary keyed (by default) with the filename |
<|file_name|>aci_bd.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: aci_bd
short_description: Manage Bridge Domains (BD) on Cisco ACI Fabrics (fv:BD)
description:
- Manages Bridge Domains (BD) on Cisco ACI Fabrics.
- More information from the internal APIC class
I(fv:BD) at U(https://developer.cisco.com/media/mim-ref/MO-fvBD.html).
author:
- Swetha Chunduri (@schunduri)
- Dag Wieers (@dagwieers)
- Jacob McGill (@jmcgill298)
requirements:
- ACI Fabric 1.0(3f)+
version_added: '2.4'
notes:
- The C(tenant) used must exist before using this module in your playbook.
The M(aci_tenant) module can be used for this.
options:
arp_flooding:
description:
- Determines if the Bridge Domain should flood ARP traffic.
- The APIC defaults new Bridge Domains to C(no).
choices: [ no, yes ]
default: no
bd:
description:
- The name of the Bridge Domain.
aliases: [ bd_name, name ]
bd_type:
description:
- The type of traffic on the Bridge Domain.
- The APIC defaults new Bridge Domains to C(ethernet).
choices: [ ethernet, fc ]
default: ethernet
description:
description:
- Description for the Bridge Domain.
enable_multicast:
description:
- Determines if PIM is enabled
- The APIC defaults new Bridge Domains to C(no).
choices: [ no, yes ]
default: no
enable_routing:
description:
- Determines if IP forwarding should be allowed.
- The APIC defaults new Bridge Domains to C(yes).
choices: [ no, yes ]
default: yes
endpoint_clear:
description:
- Clears all End Points in all Leaves when C(yes).
- The APIC defaults new Bridge Domains to C(no).
- The value is not reset to disabled once End Points have been cleared; that requires a second task.
choices: [ no, yes ]
default: no
endpoint_move_detect:
description:
- Determines if GARP should be enabled to detect when End Points move.
- The APIC defaults new Bridge Domains to C(garp).
choices: [ default, garp ]
default: garp
endpoint_retention_action:
description:
- Determines if the Bridge Domain should inherit or resolve the End Point Retention Policy.
- The APIC defaults new Bridge Domain to End Point Retention Policies to C(resolve).
choices: [ inherit, resolve ]
default: resolve
endpoint_retention_policy:
description:
- The name of the End Point Retention Policy the Bridge Domain should use when
overriding the default End Point Retention Policy.
igmp_snoop_policy:
description:
- The name of the IGMP Snooping Policy the Bridge Domain should use when
overriding the default IGMP Snooping Policy.
ip_learning:
description:
- Determines if the Bridge Domain should learn End Point IPs.
- The APIC defaults new Bridge Domains to C(yes).
choices: [ no, yes ]
ipv6_nd_policy:
description:
- The name of the IPv6 Neighbor Discovery Policy the Bridge Domain should use when
overridding the default IPV6 ND Policy.
l2_unknown_unicast:
description:
- Determines what forwarding method to use for unknown l2 destinations.
- The APIC defaults new Bridge domains to C(proxy).
choices: [ proxy, flood ]
default: proxy
l3_unknown_multicast:
description:
- Determines the forwarding method to use for unknown multicast destinations.
- The APCI defaults new Bridge Domains to C(flood).
choices: [ flood, opt-flood ]
default: flood
limit_ip_learn:
description:
- Determines if the BD should limit IP learning to only subnets owned by the Bridge Domain.
- The APIC defaults new Bridge Domains to C(yes).
choices: [ no, yes ]
default: yes
multi_dest:
description:
- Determines the forwarding method for L2 multicast, broadcast, and link layer traffic.
- The APIC defaults new Bridge Domains to C(bd-flood).
choices: [ bd-flood, drop, encap-flood ]
default: bd-flood
state:
description:
- Use C(present) or C(absent) for adding or removing.
- Use C(query) for listing an object or multiple objects.
choices: [ absent, present, query ]
default: present
tenant:
description:
- The name of the Tenant.
aliases: [ tenant_name ]
vrf:
description:
- The name of the VRF.
aliases: [ vrf_name ]
'''
EXAMPLES = r'''
- name: Add Bridge Domain
aci_bd:
host: "{{ inventory_hostname }}"
username: "{{ username }}"
password: "{{ password }}"
validate_certs: false
state: present
tenant: prod
bd: web_servers
vrf: prod_vrf
- name: Add an FC Bridge Domain
aci_bd:
host: "{{ inventory_hostname }}"
username: "{{ username }}"
password: "{{ password }}"
validate_certs: false
state: present
tenant: prod
bd: storage
bd_type: fc
vrf: fc_vrf
enable_routing: no
- name: Modify a Bridge Domain
aci_bd:
host: "{{ inventory_hostname }}"
username: "{{ username }}"
password: "{{ password }}"
validate_certs: true
state: present
tenant: prod
bd: web_servers
arp_flooding: yes
l2_unknown_unicast: flood
- name: Query All Bridge Domains
aci_bd:
host: "{{ inventory_hostname }}"
username: "{{ username }}"
password: "{{ password }}"
validate_certs: true
state: query
- name: Query a Bridge Domain
aci_bd:
host: "{{ inventory_hostname }}"
username: "{{ username }}"
password: "{{ password }}"
validate_certs: true
state: query
tenant: prod
bd: web_servers
- name: Delete a Bridge Domain
aci_bd:
host: "{{ inventory_hostname }}"
username: "{{ username }}"
password: "{{ password }}"
validate_certs: true<|fim▁hole|>
RETURN = r''' # '''
from ansible.module_utils.aci import ACIModule, aci_argument_spec
from ansible.module_utils.basic import AnsibleModule
def main():
argument_spec = aci_argument_spec
argument_spec.update(
arp_flooding=dict(choices=['no', 'yes']),
bd=dict(type='str', aliases=['bd_name', 'name']),
bd_type=dict(type='str', choices=['ethernet', 'fc']),
description=dict(type='str'),
enable_multicast=dict(type='str', choices=['no', 'yes']),
enable_routing=dict(type='str', choices=['no', 'yes']),
endpoint_clear=dict(type='str', choices=['no', 'yes']),
endpoint_move_detect=dict(type='str', choices=['default', 'garp']),
endpoint_retention_action=dict(type='str', choices=['inherit', 'resolve']),
endpoint_retention_policy=dict(type='str'),
igmp_snoop_policy=dict(type='str'),
ip_learning=dict(type='str', choices=['no', 'yes']),
ipv6_nd_policy=dict(type='str'),
l2_unknown_unicast=dict(choices=['proxy', 'flood']),
l3_unknown_multicast=dict(choices=['flood', 'opt-flood']),
limit_ip_learn=dict(type='str', choices=['no', 'yes']),
multi_dest=dict(choices=['bd-flood', 'drop', 'encap-flood']),
state=dict(choices=['absent', 'present', 'query'], type='str', default='present'),
tenant=dict(type='str', aliases=['tenant_name']),
vrf=dict(type='str', aliases=['vrf_name']),
gateway_ip=dict(type='str', removed_in_version='2.4'), # Deprecated starting from v2.4
method=dict(type='str', choices=['delete', 'get', 'post'], aliases=['action'], removed_in_version='2.6'), # Deprecated starting from v2.6
scope=dict(type='str', removed_in_version='2.4'), # Deprecated starting from v2.4
subnet_mask=dict(type='str', removed_in_version='2.4'), # Deprecated starting from v2.4
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
required_if=[
['state', 'absent', ['bd', 'tenant']],
['state', 'present', ['bd', 'tenant']],
],
)
arp_flooding = module.params['arp_flooding']
bd = module.params['bd']
bd_type = module.params['bd_type']
if bd_type == 'ethernet':
# ethernet type is represented as regular, but that is not clear to the users
bd_type = 'regular'
description = module.params['description']
enable_multicast = module.params['enable_multicast']
enable_routing = module.params['enable_routing']
endpoint_clear = module.params['endpoint_clear']
endpoint_move_detect = module.params['endpoint_move_detect']
if endpoint_move_detect == 'default':
# the ACI default setting is an empty string, but that is not a good input value
endpoint_move_detect = ''
endpoint_retention_action = module.params['endpoint_retention_action']
endpoint_retention_policy = module.params['endpoint_retention_policy']
igmp_snoop_policy = module.params['igmp_snoop_policy']
ip_learning = module.params['ip_learning']
ipv6_nd_policy = module.params['ipv6_nd_policy']
l2_unknown_unicast = module.params['l2_unknown_unicast']
l3_unknown_multicast = module.params['l3_unknown_multicast']
limit_ip_learn = module.params['limit_ip_learn']
multi_dest = module.params['multi_dest']
state = module.params['state']
tenant = module.params['tenant']
vrf = module.params['vrf']
# Give warning when fvSubnet parameters are passed as those have been moved to the aci_subnet module
if module.params['gateway_ip'] or module.params['subnet_mask'] or module.params['scope']:
module._warnings = ["The support for managing Subnets has been moved to its own module, aci_subnet. \
The new modules still supports 'gateway_ip' and 'subnet_mask' along with more features"]
aci = ACIModule(module)
aci.construct_url(
root_class=dict(
aci_class='fvTenant',
aci_rn='tn-{}'.format(tenant),
filter_target='(fvTenant.name, "{}")'.format(tenant),
module_object=tenant,
),
subclass_1=dict(
aci_class='fvBD',
aci_rn='BD-{}'.format(bd),
filter_target='(fvBD.name, "{}")'.format(bd),
module_object=bd,
),
child_classes=['fvRsCtx', 'fvRsIgmpsn', 'fvRsBDToNdP', 'fvRsBdToEpRet'],
)
aci.get_existing()
if state == 'present':
# Filter out module params with null values
aci.payload(
aci_class='fvBD',
class_config=dict(
arpFlood=arp_flooding,
descr=description,
epClear=endpoint_clear,
epMoveDetectMode=endpoint_move_detect,
ipLearning=ip_learning,
limitIpLearnToSubnets=limit_ip_learn,
mcastAllow=enable_multicast,
multiDstPktAct=multi_dest,
name=bd,
type=bd_type,
unicastRoute=enable_routing,
unkMacUcastAct=l2_unknown_unicast,
unkMcastAct=l3_unknown_multicast,
),
child_configs=[
{'fvRsCtx': {'attributes': {'tnFvCtxName': vrf}}},
{'fvRsIgmpsn': {'attributes': {'tnIgmpSnoopPolName': igmp_snoop_policy}}},
{'fvRsBDToNdP': {'attributes': {'tnNdIfPolName': ipv6_nd_policy}}},
{'fvRsBdToEpRet': {'attributes': {'resolveAct': endpoint_retention_action, 'tnFvEpRetPolName': endpoint_retention_policy}}},
],
)
# generate config diff which will be used as POST request body
aci.get_diff(aci_class='fvBD')
# submit changes if module not in check_mode and the proposed is different than existing
aci.post_config()
elif state == 'absent':
aci.delete_config()
module.exit_json(**aci.result)
if __name__ == "__main__":
main()<|fim▁end|> | state: absent
tenant: prod
bd: web_servers
''' |
<|file_name|>SingleLine.after.py<|end_file_name|><|fim▁begin|>def x():<|fim▁hole|><|fim▁end|> | print "bar"
print "foo"
print "xyzzy" |
<|file_name|>xmlhttprequest.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::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::XMLHttpRequestBinding;
use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestMethods;
use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestResponseType;
use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestResponseType::{_empty, Json, Text};
use dom::bindings::codegen::InheritTypes::{EventCast, EventTargetCast, XMLHttpRequestDerived};
use dom::bindings::conversions::ToJSValConvertible;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::error::Error::{InvalidState, InvalidAccess};
use dom::bindings::error::Error::{Network, Syntax, Security, Abort, Timeout};
use dom::bindings::global::{GlobalField, GlobalRef, GlobalRoot};
use dom::bindings::js::{MutNullableJS, JS, JSRef, Temporary, OptionalRootedRootable};
use dom::bindings::refcounted::Trusted;
use dom::bindings::str::ByteString;
use dom::bindings::utils::{Reflectable, reflect_dom_object};
use dom::document::Document;
use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers};
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
use dom::progressevent::ProgressEvent;
use dom::urlsearchparams::URLSearchParamsHelpers;
use dom::xmlhttprequesteventtarget::XMLHttpRequestEventTarget;
use dom::xmlhttprequesteventtarget::XMLHttpRequestEventTargetTypeId;
use dom::xmlhttprequestupload::XMLHttpRequestUpload;
use script_task::{ScriptChan, ScriptMsg, Runnable};
use encoding::all::UTF_8;
use encoding::label::encoding_from_whatwg_label;
use encoding::types::{DecoderTrap, Encoding, EncodingRef, EncoderTrap};
use hyper::header::Headers;
use hyper::header::{Accept, ContentLength, ContentType, qitem};
use hyper::http::RawStatus;
use hyper::mime::{self, Mime};
use hyper::method::Method;
use js::jsapi::{JS_ParseJSON, JSContext};
use js::jsapi::JS_ClearPendingException;
use js::jsval::{JSVal, NullValue, UndefinedValue};
use net_traits::ControlMsg::Load;
use net_traits::ProgressMsg::{Payload, Done};
use net_traits::{ResourceTask, ResourceCORSData, LoadData, LoadResponse};
use cors::{allow_cross_origin_request, CORSRequest, RequestMode};
use util::str::DOMString;
use util::task::spawn_named;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::cell::Cell;
use std::sync::mpsc::{Sender, Receiver, channel};
use std::default::Default;
use std::old_io::Timer;
use std::str::FromStr;
use std::time::duration::Duration;
use time;
use url::{Url, UrlParser};
use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams;
use dom::bindings::codegen::UnionTypes::StringOrURLSearchParams::{eString, eURLSearchParams};
pub type SendParam = StringOrURLSearchParams;
#[derive(PartialEq, Copy)]
#[jstraceable]
enum XMLHttpRequestState {
Unsent = 0,
Opened = 1,
HeadersReceived = 2,
Loading = 3,
Done = 4,
}
struct XHRProgressHandler {
addr: TrustedXHRAddress,
progress: XHRProgress,
}
impl XHRProgressHandler {
fn new(addr: TrustedXHRAddress, progress: XHRProgress) -> XHRProgressHandler {
XHRProgressHandler { addr: addr, progress: progress }
}
}
impl Runnable for XHRProgressHandler {
fn handler(self: Box<XHRProgressHandler>) {
let this = *self;
XMLHttpRequest::handle_progress(this.addr, this.progress);
}
}
#[derive(PartialEq, Clone, Copy)]
#[jstraceable]
pub struct GenerationId(u32);
#[derive(Clone)]
pub enum XHRProgress {
/// Notify that headers have been received
HeadersReceived(GenerationId, Option<Headers>, Option<RawStatus>),
/// Partial progress (after receiving headers), containing portion of the response
Loading(GenerationId, ByteString),
/// Loading is done
Done(GenerationId),
/// There was an error (only Abort, Timeout or Network is used)
Errored(GenerationId, Error),
}
impl XHRProgress {
fn generation_id(&self) -> GenerationId {
match *self {
XHRProgress::HeadersReceived(id, _, _) |
XHRProgress::Loading(id, _) |
XHRProgress::Done(id) |
XHRProgress::Errored(id, _) => id
}
}
}
enum SyncOrAsync<'a> {
Sync(JSRef<'a, XMLHttpRequest>),
Async(TrustedXHRAddress, Box<ScriptChan+Send>)
}
enum TerminateReason {
AbortedOrReopened,
TimedOut,
}
#[dom_struct]
pub struct XMLHttpRequest {
eventtarget: XMLHttpRequestEventTarget,
ready_state: Cell<XMLHttpRequestState>,
timeout: Cell<u32>,
with_credentials: Cell<bool>,
upload: JS<XMLHttpRequestUpload>,
response_url: DOMString,
status: Cell<u16>,
status_text: DOMRefCell<ByteString>,
response: DOMRefCell<ByteString>,
response_type: Cell<XMLHttpRequestResponseType>,
response_xml: MutNullableJS<Document>,
response_headers: DOMRefCell<Headers>,
// Associated concepts
request_method: DOMRefCell<Method>,
request_url: DOMRefCell<Option<Url>>,
request_headers: DOMRefCell<Headers>,
request_body_len: Cell<usize>,
sync: Cell<bool>,
upload_complete: Cell<bool>,
upload_events: Cell<bool>,
send_flag: Cell<bool>,
global: GlobalField,
timer: DOMRefCell<Timer>,
fetch_time: Cell<i64>,
terminate_sender: DOMRefCell<Option<Sender<TerminateReason>>>,
generation_id: Cell<GenerationId>,
}
impl XMLHttpRequest {
fn new_inherited(global: GlobalRef) -> XMLHttpRequest {
XMLHttpRequest {
eventtarget: XMLHttpRequestEventTarget::new_inherited(XMLHttpRequestEventTargetTypeId::XMLHttpRequest),
ready_state: Cell::new(XMLHttpRequestState::Unsent),
timeout: Cell::new(0u32),
with_credentials: Cell::new(false),
upload: JS::from_rooted(XMLHttpRequestUpload::new(global)),
response_url: "".to_owned(),
status: Cell::new(0),
status_text: DOMRefCell::new(ByteString::new(vec!())),
response: DOMRefCell::new(ByteString::new(vec!())),
response_type: Cell::new(_empty),
response_xml: Default::default(),
response_headers: DOMRefCell::new(Headers::new()),
request_method: DOMRefCell::new(Method::Get),
request_url: DOMRefCell::new(None),
request_headers: DOMRefCell::new(Headers::new()),
request_body_len: Cell::new(0),
sync: Cell::new(false),
send_flag: Cell::new(false),
upload_complete: Cell::new(false),
upload_events: Cell::new(false),
global: GlobalField::from_rooted(&global),
timer: DOMRefCell::new(Timer::new().unwrap()),
fetch_time: Cell::new(0),
terminate_sender: DOMRefCell::new(None),
generation_id: Cell::new(GenerationId(0))
}
}
pub fn new(global: GlobalRef) -> Temporary<XMLHttpRequest> {
reflect_dom_object(box XMLHttpRequest::new_inherited(global),
global,
XMLHttpRequestBinding::Wrap)
}
// https://xhr.spec.whatwg.org/#constructors
pub fn Constructor(global: GlobalRef) -> Fallible<Temporary<XMLHttpRequest>> {
Ok(XMLHttpRequest::new(global))
}
pub fn handle_progress(addr: TrustedXHRAddress, progress: XHRProgress) {
let xhr = addr.to_temporary().root();
xhr.r().process_partial_response(progress);
}
#[allow(unsafe_code)]
fn fetch(fetch_type: &SyncOrAsync, resource_task: ResourceTask,
mut load_data: LoadData, terminate_receiver: Receiver<TerminateReason>,
cors_request: Result<Option<CORSRequest>,()>, gen_id: GenerationId,
start_port: Receiver<LoadResponse>) -> ErrorResult {
fn notify_partial_progress(fetch_type: &SyncOrAsync, msg: XHRProgress) {
match *fetch_type {
SyncOrAsync::Sync(xhr) => {
xhr.process_partial_response(msg);
},
SyncOrAsync::Async(ref addr, ref script_chan) => {
script_chan.send(ScriptMsg::RunnableMsg(box XHRProgressHandler::new(addr.clone(), msg))).unwrap();
}
}
}
macro_rules! notify_error_and_return(
($err:expr) => ({
notify_partial_progress(fetch_type, XHRProgress::Errored(gen_id, $err));
return Err($err)
});
);
macro_rules! terminate(
($reason:expr) => (
match $reason {
TerminateReason::AbortedOrReopened => {
return Err(Abort)
}
TerminateReason::TimedOut => {
notify_error_and_return!(Timeout);
}
}
);
);
match cors_request {
Err(_) => {
// Happens in case of cross-origin non-http URIs
notify_error_and_return!(Network);
}
Ok(Some(ref req)) => {
let (chan, cors_port) = channel();
let req2 = req.clone();
// TODO: this exists only to make preflight check non-blocking<|fim▁hole|> chan.send(response).unwrap();
});
select! (
response = cors_port.recv() => {
let response = response.unwrap();
if response.network_error {
notify_error_and_return!(Network);
} else {
load_data.cors = Some(ResourceCORSData {
preflight: req.preflight_flag,
origin: req.origin.clone()
});
}
},
reason = terminate_receiver.recv() => terminate!(reason.unwrap())
);
}
_ => {}
}
// Step 10, 13
resource_task.send(Load(load_data)).unwrap();
let progress_port;
select! (
response = start_port.recv() => {
let response = response.unwrap();
match cors_request {
Ok(Some(ref req)) => {
match response.metadata.headers {
Some(ref h) if allow_cross_origin_request(req, h) => {},
_ => notify_error_and_return!(Network)
}
},
_ => {}
};
// XXXManishearth Clear cache entries in case of a network error
notify_partial_progress(fetch_type, XHRProgress::HeadersReceived(gen_id,
response.metadata.headers.clone(), response.metadata.status.clone()));
progress_port = response.progress_port;
},
reason = terminate_receiver.recv() => terminate!(reason.unwrap())
);
let mut buf = vec!();
loop {
// Under most circumstances, progress_port will contain lots of Payload
// events. Since select! does not have any fairness or priority, it
// might always remove the progress_port event, even when there is
// a terminate event waiting in the terminate_receiver. If this happens,
// a timeout or abort will take too long to be processed. To avoid this,
// in each iteration, we check for a terminate event before we block.
match terminate_receiver.try_recv() {
Ok(reason) => terminate!(reason),
Err(_) => ()
};
select! (
progress = progress_port.recv() => match progress.unwrap() {
Payload(data) => {
buf.push_all(data.as_slice());
notify_partial_progress(fetch_type,
XHRProgress::Loading(gen_id, ByteString::new(buf.clone())));
},
Done(Ok(())) => {
notify_partial_progress(fetch_type, XHRProgress::Done(gen_id));
return Ok(());
},
Done(Err(_)) => {
notify_error_and_return!(Network);
}
},
reason = terminate_receiver.recv() => terminate!(reason.unwrap())
);
}
}
}
impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> {
event_handler!(readystatechange, GetOnreadystatechange, SetOnreadystatechange);
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
fn ReadyState(self) -> u16 {
self.ready_state.get() as u16
}
// https://xhr.spec.whatwg.org/#the-open()-method
fn Open(self, method: ByteString, url: DOMString) -> ErrorResult {
//FIXME(seanmonstar): use a Trie instead?
let maybe_method = method.as_str().and_then(|s| {
// Note: hyper tests against the uppercase versions
// Since we want to pass methods not belonging to the short list above
// without changing capitalization, this will actually sidestep rust-http's type system
// since methods like "patch" or "PaTcH" will be considered extension methods
// despite the there being a rust-http method variant for them
let upper = s.to_ascii_uppercase();
match upper.as_slice() {
"DELETE" | "GET" | "HEAD" | "OPTIONS" |
"POST" | "PUT" | "CONNECT" | "TRACE" |
"TRACK" => upper.parse().ok(),
_ => s.parse().ok()
}
});
// Step 2
match maybe_method {
// Step 4
Some(Method::Connect) | Some(Method::Trace) => Err(Security),
Some(Method::Extension(ref t)) if t.as_slice() == "TRACK" => Err(Security),
Some(parsed_method) => {
// Step 3
if !method.is_token() {
return Err(Syntax)
}
*self.request_method.borrow_mut() = parsed_method;
// Step 6
let base = self.global.root().r().get_url();
let parsed_url = match UrlParser::new().base_url(&base).parse(url.as_slice()) {
Ok(parsed) => parsed,
Err(_) => return Err(Syntax) // Step 7
};
// XXXManishearth Do some handling of username/passwords
if self.sync.get() {
// FIXME: This should only happen if the global environment is a document environment
if self.timeout.get() != 0 || self.with_credentials.get() || self.response_type.get() != _empty {
return Err(InvalidAccess)
}
}
// abort existing requests
self.terminate_ongoing_fetch();
// Step 12
*self.request_url.borrow_mut() = Some(parsed_url);
*self.request_headers.borrow_mut() = Headers::new();
self.send_flag.set(false);
*self.status_text.borrow_mut() = ByteString::new(vec!());
self.status.set(0);
// Step 13
if self.ready_state.get() != XMLHttpRequestState::Opened {
self.change_ready_state(XMLHttpRequestState::Opened);
}
Ok(())
},
// This includes cases where as_str() returns None, and when is_token() returns false,
// both of which indicate invalid extension method names
_ => Err(Syntax), // Step 3
}
}
// https://xhr.spec.whatwg.org/#the-open()-method
fn Open_(self, method: ByteString, url: DOMString, async: bool,
_username: Option<DOMString>, _password: Option<DOMString>) -> ErrorResult {
self.sync.set(!async);
self.Open(method, url)
}
// https://xhr.spec.whatwg.org/#the-setrequestheader()-method
fn SetRequestHeader(self, name: ByteString, mut value: ByteString) -> ErrorResult {
if self.ready_state.get() != XMLHttpRequestState::Opened || self.send_flag.get() {
return Err(InvalidState); // Step 1, 2
}
if !name.is_token() || !value.is_field_value() {
return Err(Syntax); // Step 3, 4
}
let name_lower = name.to_lower();
let name_str = match name_lower.as_str() {
Some(s) => {
match s {
// Disallowed headers
"accept-charset" | "accept-encoding" |
"access-control-request-headers" |
"access-control-request-method" |
"connection" | "content-length" |
"cookie" | "cookie2" | "date" |"dnt" |
"expect" | "host" | "keep-alive" | "origin" |
"referer" | "te" | "trailer" | "transfer-encoding" |
"upgrade" | "user-agent" | "via" => {
return Ok(()); // Step 5
},
_ => s
}
},
None => return Err(Syntax)
};
debug!("SetRequestHeader: name={:?}, value={:?}", name.as_str(), value.as_str());
let mut headers = self.request_headers.borrow_mut();
// Steps 6,7
match headers.get_raw(name_str) {
Some(raw) => {
debug!("SetRequestHeader: old value = {:?}", raw[0]);
let mut buf = raw[0].clone();
buf.push_all(b", ");
buf.push_all(value.as_slice());
debug!("SetRequestHeader: new value = {:?}", buf);
value = ByteString::new(buf);
},
None => {}
}
headers.set_raw(name_str.to_owned(), vec![value.as_slice().to_vec()]);
Ok(())
}
// https://xhr.spec.whatwg.org/#the-timeout-attribute
fn Timeout(self) -> u32 {
self.timeout.get()
}
// https://xhr.spec.whatwg.org/#the-timeout-attribute
fn SetTimeout(self, timeout: u32) -> ErrorResult {
if self.sync.get() {
// FIXME: Not valid for a worker environment
Err(InvalidAccess)
} else {
self.timeout.set(timeout);
if self.send_flag.get() {
if timeout == 0 {
self.cancel_timeout();
return Ok(());
}
let progress = time::now().to_timespec().sec - self.fetch_time.get();
if timeout > (progress * 1000) as u32 {
self.set_timeout(timeout - (progress * 1000) as u32);
} else {
// Immediately execute the timeout steps
self.set_timeout(0);
}
}
Ok(())
}
}
// https://xhr.spec.whatwg.org/#the-withcredentials-attribute
fn WithCredentials(self) -> bool {
self.with_credentials.get()
}
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-withcredentials
fn SetWithCredentials(self, with_credentials: bool) -> ErrorResult {
match self.ready_state.get() {
XMLHttpRequestState::HeadersReceived |
XMLHttpRequestState::Loading |
XMLHttpRequestState::Done => Err(InvalidState),
_ if self.send_flag.get() => Err(InvalidState),
_ => match self.global.root() {
GlobalRoot::Window(_) if self.sync.get() => Err(InvalidAccess),
_ => {
self.with_credentials.set(with_credentials);
Ok(())
},
},
}
}
// https://xhr.spec.whatwg.org/#the-upload-attribute
fn Upload(self) -> Temporary<XMLHttpRequestUpload> {
Temporary::new(self.upload)
}
// https://xhr.spec.whatwg.org/#the-send()-method
fn Send(self, data: Option<SendParam>) -> ErrorResult {
if self.ready_state.get() != XMLHttpRequestState::Opened || self.send_flag.get() {
return Err(InvalidState); // Step 1, 2
}
let data = match *self.request_method.borrow() {
Method::Get | Method::Head => None, // Step 3
_ => data
};
let extracted = data.as_ref().map(|d| d.extract());
self.request_body_len.set(extracted.as_ref().map(|e| e.len()).unwrap_or(0));
// Step 6
self.upload_events.set(false);
// Step 7
self.upload_complete.set(match extracted {
None => true,
Some (ref v) if v.len() == 0 => true,
_ => false
});
if !self.sync.get() {
// Step 8
let upload_target = self.upload.root();
let event_target: JSRef<EventTarget> = EventTargetCast::from_ref(upload_target.r());
if event_target.has_handlers() {
self.upload_events.set(true);
}
// Step 9
self.send_flag.set(true);
// If one of the event handlers below aborts the fetch by calling
// abort or open we will need the current generation id to detect it.
let gen_id = self.generation_id.get();
self.dispatch_response_progress_event("loadstart".to_owned());
if self.generation_id.get() != gen_id {
return Ok(());
}
if !self.upload_complete.get() {
self.dispatch_upload_progress_event("loadstart".to_owned(), Some(0));
if self.generation_id.get() != gen_id {
return Ok(());
}
}
}
let global = self.global.root();
let resource_task = global.r().resource_task();
let (start_chan, start_port) = channel();
let mut load_data = LoadData::new(self.request_url.borrow().clone().unwrap(), start_chan);
load_data.data = extracted;
#[inline]
fn join_raw(a: &str, b: &str) -> Vec<u8> {
let len = a.len() + b.len();
let mut vec = Vec::with_capacity(len);
vec.push_all(a.as_bytes());
vec.push_all(b.as_bytes());
vec
}
// XHR spec differs from http, and says UTF-8 should be in capitals,
// instead of "utf-8", which is what Hyper defaults to.
let params = ";charset=UTF-8";
let n = "content-type";
match data {
Some(eString(_)) =>
load_data.headers.set_raw(n.to_owned(), vec![join_raw("text/plain", params)]),
Some(eURLSearchParams(_)) =>
load_data.headers.set_raw(
n.to_owned(), vec![join_raw("application/x-www-form-urlencoded", params)]),
None => ()
}
load_data.preserved_headers = (*self.request_headers.borrow()).clone();
if !load_data.preserved_headers.has::<Accept>() {
let mime = Mime(mime::TopLevel::Star, mime::SubLevel::Star, vec![]);
load_data.preserved_headers.set(Accept(vec![qitem(mime)]));
}
load_data.method = (*self.request_method.borrow()).clone();
let (terminate_sender, terminate_receiver) = channel();
*self.terminate_sender.borrow_mut() = Some(terminate_sender);
// CORS stuff
let referer_url = self.global.root().r().get_url();
let mode = if self.upload_events.get() {
RequestMode::ForcedPreflight
} else {
RequestMode::CORS
};
let mut combined_headers = load_data.headers.clone();
combined_headers.extend(load_data.preserved_headers.iter());
let cors_request = CORSRequest::maybe_new(referer_url.clone(), load_data.url.clone(), mode,
load_data.method.clone(), combined_headers);
match cors_request {
Ok(None) => {
let mut buf = String::new();
buf.push_str(referer_url.scheme.as_slice());
buf.push_str("://".as_slice());
referer_url.serialize_host().map(|ref h| buf.push_str(h.as_slice()));
referer_url.port().as_ref().map(|&p| {
buf.push_str(":".as_slice());
buf.push_str(p.to_string().as_slice());
});
referer_url.serialize_path().map(|ref h| buf.push_str(h.as_slice()));
self.request_headers.borrow_mut().set_raw("Referer".to_owned(), vec![buf.into_bytes()]);
},
Ok(Some(ref req)) => self.insert_trusted_header("origin".to_owned(),
req.origin.to_string()),
_ => {}
}
debug!("request_headers = {:?}", *self.request_headers.borrow());
let gen_id = self.generation_id.get();
if self.sync.get() {
return XMLHttpRequest::fetch(&mut SyncOrAsync::Sync(self), resource_task, load_data,
terminate_receiver, cors_request, gen_id, start_port);
} else {
self.fetch_time.set(time::now().to_timespec().sec);
let script_chan = global.r().script_chan();
// Pin the object before launching the fetch task. This is to ensure that
// the object will stay alive as long as there are (possibly cancelled)
// inflight events queued up in the script task's port.
let addr = Trusted::new(self.global.root().r().get_cx(), self,
script_chan.clone());
spawn_named("XHRTask".to_owned(), move || {
let _ = XMLHttpRequest::fetch(&mut SyncOrAsync::Async(addr, script_chan),
resource_task,
load_data,
terminate_receiver,
cors_request,
gen_id,
start_port);
});
let timeout = self.timeout.get();
if timeout > 0 {
self.set_timeout(timeout);
}
}
Ok(())
}
// https://xhr.spec.whatwg.org/#the-abort()-method
fn Abort(self) {
self.terminate_ongoing_fetch();
let state = self.ready_state.get();
if (state == XMLHttpRequestState::Opened && self.send_flag.get()) ||
state == XMLHttpRequestState::HeadersReceived ||
state == XMLHttpRequestState::Loading {
let gen_id = self.generation_id.get();
self.process_partial_response(XHRProgress::Errored(gen_id, Abort));
// If open was called in one of the handlers invoked by the
// above call then we should terminate the abort sequence
if self.generation_id.get() != gen_id {
return
}
}
self.ready_state.set(XMLHttpRequestState::Unsent);
}
// https://xhr.spec.whatwg.org/#the-responseurl-attribute
fn ResponseURL(self) -> DOMString {
self.response_url.clone()
}
// https://xhr.spec.whatwg.org/#the-status-attribute
fn Status(self) -> u16 {
self.status.get()
}
// https://xhr.spec.whatwg.org/#the-statustext-attribute
fn StatusText(self) -> ByteString {
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let status_text = self.status_text.borrow();
status_text.clone()
}
// https://xhr.spec.whatwg.org/#the-getresponseheader()-method
fn GetResponseHeader(self, name: ByteString) -> Option<ByteString> {
self.filter_response_headers().iter().find(|h| {
name.eq_ignore_case(&FromStr::from_str(h.name()).unwrap())
}).map(|h| {
ByteString::new(h.value_string().into_bytes())
})
}
// https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method
fn GetAllResponseHeaders(self) -> ByteString {
ByteString::new(self.filter_response_headers().to_string().into_bytes())
}
// https://xhr.spec.whatwg.org/#the-responsetype-attribute
fn ResponseType(self) -> XMLHttpRequestResponseType {
self.response_type.get()
}
// https://xhr.spec.whatwg.org/#the-responsetype-attribute
fn SetResponseType(self, response_type: XMLHttpRequestResponseType) -> ErrorResult {
match self.global.root() {
GlobalRoot::Worker(_) if response_type == XMLHttpRequestResponseType::Document
=> return Ok(()),
_ => {}
}
match self.ready_state.get() {
XMLHttpRequestState::Loading | XMLHttpRequestState::Done => Err(InvalidState),
_ if self.sync.get() => Err(InvalidAccess),
_ => {
self.response_type.set(response_type);
Ok(())
}
}
}
// https://xhr.spec.whatwg.org/#the-response-attribute
#[allow(unsafe_code)]
fn Response(self, cx: *mut JSContext) -> JSVal {
match self.response_type.get() {
_empty | Text => {
let ready_state = self.ready_state.get();
if ready_state == XMLHttpRequestState::Done || ready_state == XMLHttpRequestState::Loading {
self.text_response().to_jsval(cx)
} else {
"".to_jsval(cx)
}
},
_ if self.ready_state.get() != XMLHttpRequestState::Done => NullValue(),
Json => {
let decoded = UTF_8.decode(self.response.borrow().as_slice(), DecoderTrap::Replace).unwrap().to_owned();
let decoded: Vec<u16> = decoded.as_slice().utf16_units().collect();
let mut vp = UndefinedValue();
unsafe {
if JS_ParseJSON(cx, decoded.as_ptr(), decoded.len() as u32, &mut vp) == 0 {
JS_ClearPendingException(cx);
return NullValue();
}
}
vp
}
_ => {
// XXXManishearth handle other response types
self.response.borrow().to_jsval(cx)
}
}
}
// https://xhr.spec.whatwg.org/#the-responsetext-attribute
fn GetResponseText(self) -> Fallible<DOMString> {
match self.response_type.get() {
_empty | Text => {
match self.ready_state.get() {
XMLHttpRequestState::Loading | XMLHttpRequestState::Done => Ok(self.text_response()),
_ => Ok("".to_owned())
}
},
_ => Err(InvalidState)
}
}
// https://xhr.spec.whatwg.org/#the-responsexml-attribute
fn GetResponseXML(self) -> Option<Temporary<Document>> {
self.response_xml.get()
}
}
impl XMLHttpRequestDerived for EventTarget {
fn is_xmlhttprequest(&self) -> bool {
match *self.type_id() {
EventTargetTypeId::XMLHttpRequestEventTarget(XMLHttpRequestEventTargetTypeId::XMLHttpRequest) => true,
_ => false
}
}
}
pub type TrustedXHRAddress = Trusted<XMLHttpRequest>;
trait PrivateXMLHttpRequestHelpers {
fn change_ready_state(self, XMLHttpRequestState);
fn process_partial_response(self, progress: XHRProgress);
fn terminate_ongoing_fetch(self);
fn insert_trusted_header(self, name: String, value: String);
fn dispatch_progress_event(self, upload: bool, type_: DOMString, loaded: u64, total: Option<u64>);
fn dispatch_upload_progress_event(self, type_: DOMString, partial_load: Option<u64>);
fn dispatch_response_progress_event(self, type_: DOMString);
fn text_response(self) -> DOMString;
fn set_timeout(self, timeout:u32);
fn cancel_timeout(self);
fn filter_response_headers(self) -> Headers;
}
impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
fn change_ready_state(self, rs: XMLHttpRequestState) {
assert!(self.ready_state.get() != rs);
self.ready_state.set(rs);
let global = self.global.root();
let event = Event::new(global.r(),
"readystatechange".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::Cancelable).root();
let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
event.r().fire(target);
}
fn process_partial_response(self, progress: XHRProgress) {
let msg_id = progress.generation_id();
// Aborts processing if abort() or open() was called
// (including from one of the event handlers called below)
macro_rules! return_if_fetch_was_terminated(
() => (
if msg_id != self.generation_id.get() {
return
}
);
);
// Ignore message if it belongs to a terminated fetch
return_if_fetch_was_terminated!();
match progress {
XHRProgress::HeadersReceived(_, headers, status) => {
assert!(self.ready_state.get() == XMLHttpRequestState::Opened);
// For synchronous requests, this should not fire any events, and just store data
// XXXManishearth Find a way to track partial progress of the send (onprogresss for XHRUpload)
// Part of step 13, send() (processing request end of file)
// Substep 1
self.upload_complete.set(true);
// Substeps 2-4
if !self.sync.get() {
self.dispatch_upload_progress_event("progress".to_owned(), None);
return_if_fetch_was_terminated!();
self.dispatch_upload_progress_event("load".to_owned(), None);
return_if_fetch_was_terminated!();
self.dispatch_upload_progress_event("loadend".to_owned(), None);
return_if_fetch_was_terminated!();
}
// Part of step 13, send() (processing response)
// XXXManishearth handle errors, if any (substep 1)
// Substep 2
status.map(|RawStatus(code, reason)| {
self.status.set(code);
*self.status_text.borrow_mut() = ByteString::new(reason.into_owned().into_bytes());
});
headers.as_ref().map(|h| *self.response_headers.borrow_mut() = h.clone());
// Substep 3
if !self.sync.get() {
self.change_ready_state(XMLHttpRequestState::HeadersReceived);
}
},
XHRProgress::Loading(_, partial_response) => {
// For synchronous requests, this should not fire any events, and just store data
// Part of step 11, send() (processing response body)
// XXXManishearth handle errors, if any (substep 2)
*self.response.borrow_mut() = partial_response;
if !self.sync.get() {
if self.ready_state.get() == XMLHttpRequestState::HeadersReceived {
self.change_ready_state(XMLHttpRequestState::Loading);
return_if_fetch_was_terminated!();
}
self.dispatch_response_progress_event("progress".to_owned());
}
},
XHRProgress::Done(_) => {
assert!(self.ready_state.get() == XMLHttpRequestState::HeadersReceived ||
self.ready_state.get() == XMLHttpRequestState::Loading ||
self.sync.get());
// Part of step 11, send() (processing response end of file)
// XXXManishearth handle errors, if any (substep 2)
// Subsubsteps 5-7
self.send_flag.set(false);
self.change_ready_state(XMLHttpRequestState::Done);
return_if_fetch_was_terminated!();
// Subsubsteps 10-12
self.dispatch_response_progress_event("progress".to_owned());
return_if_fetch_was_terminated!();
self.dispatch_response_progress_event("load".to_owned());
return_if_fetch_was_terminated!();
self.dispatch_response_progress_event("loadend".to_owned());
},
XHRProgress::Errored(_, e) => {
self.send_flag.set(false);
// XXXManishearth set response to NetworkError
self.change_ready_state(XMLHttpRequestState::Done);
return_if_fetch_was_terminated!();
let errormsg = match e {
Abort => "abort",
Timeout => "timeout",
_ => "error",
};
let upload_complete: &Cell<bool> = &self.upload_complete;
if !upload_complete.get() {
upload_complete.set(true);
self.dispatch_upload_progress_event("progress".to_owned(), None);
return_if_fetch_was_terminated!();
self.dispatch_upload_progress_event(errormsg.to_owned(), None);
return_if_fetch_was_terminated!();
self.dispatch_upload_progress_event("loadend".to_owned(), None);
return_if_fetch_was_terminated!();
}
self.dispatch_response_progress_event("progress".to_owned());
return_if_fetch_was_terminated!();
self.dispatch_response_progress_event(errormsg.to_owned());
return_if_fetch_was_terminated!();
self.dispatch_response_progress_event("loadend".to_owned());
}
}
}
fn terminate_ongoing_fetch(self) {
let GenerationId(prev_id) = self.generation_id.get();
self.generation_id.set(GenerationId(prev_id + 1));
self.terminate_sender.borrow().as_ref().map(|s| s.send(TerminateReason::AbortedOrReopened));
}
fn insert_trusted_header(self, name: String, value: String) {
// Insert a header without checking spec-compliance
// Use for hardcoded headers
self.request_headers.borrow_mut().set_raw(name, vec![value.into_bytes()]);
}
fn dispatch_progress_event(self, upload: bool, type_: DOMString, loaded: u64, total: Option<u64>) {
let global = self.global.root();
let upload_target = self.upload.root();
let progressevent = ProgressEvent::new(global.r(),
type_, false, false,
total.is_some(), loaded,
total.unwrap_or(0)).root();
let target: JSRef<EventTarget> = if upload {
EventTargetCast::from_ref(upload_target.r())
} else {
EventTargetCast::from_ref(self)
};
let event: JSRef<Event> = EventCast::from_ref(progressevent.r());
event.fire(target);
}
fn dispatch_upload_progress_event(self, type_: DOMString, partial_load: Option<u64>) {
// If partial_load is None, loading has completed and we can just use the value from the request body
let total = self.request_body_len.get() as u64;
self.dispatch_progress_event(true, type_, partial_load.unwrap_or(total), Some(total));
}
fn dispatch_response_progress_event(self, type_: DOMString) {
let len = self.response.borrow().len() as u64;
let total = self.response_headers.borrow().get::<ContentLength>().map(|x| {**x as u64});
self.dispatch_progress_event(false, type_, len, total);
}
fn set_timeout(self, timeout: u32) {
// Sets up the object to timeout in a given number of milliseconds
// This will cancel all previous timeouts
let oneshot = self.timer.borrow_mut()
.oneshot(Duration::milliseconds(timeout as i64));
let terminate_sender = (*self.terminate_sender.borrow()).clone();
spawn_named("XHR:Timer".to_owned(), move || {
match oneshot.recv() {
Ok(_) => {
terminate_sender.map(|s| s.send(TerminateReason::TimedOut));
},
Err(_) => {
// This occurs if xhr.timeout (the sender) goes out of scope (i.e, xhr went out of scope)
// or if the oneshot timer was overwritten. The former case should not happen due to pinning.
debug!("XHR timeout was overwritten or canceled")
}
}
}
);
}
fn cancel_timeout(self) {
// oneshot() closes the previous channel, canceling the timeout
self.timer.borrow_mut().oneshot(Duration::zero());
}
fn text_response(self) -> DOMString {
let mut encoding = UTF_8 as EncodingRef;
match self.response_headers.borrow().get() {
Some(&ContentType(mime::Mime(_, _, ref params))) => {
for &(ref name, ref value) in params.iter() {
if name == &mime::Attr::Charset {
encoding = encoding_from_whatwg_label(value.to_string().as_slice()).unwrap_or(encoding);
}
}
},
None => {}
}
// FIXME(https://github.com/rust-lang/rust/issues/23338)
let response = self.response.borrow();
// According to Simon, decode() should never return an error, so unwrap()ing
// the result should be fine. XXXManishearth have a closer look at this later
encoding.decode(response.as_slice(), DecoderTrap::Replace).unwrap().to_owned()
}
fn filter_response_headers(self) -> Headers {
// http://fetch.spec.whatwg.org/#concept-response-header-list
use std::fmt;
use hyper::header::{Header, HeaderFormat};
use hyper::header::SetCookie;
// a dummy header so we can use headers.remove::<SetCookie2>()
#[derive(Clone, Debug)]
struct SetCookie2;
impl Header for SetCookie2 {
fn header_name() -> &'static str {
"set-cookie2"
}
fn parse_header(_: &[Vec<u8>]) -> Option<SetCookie2> {
unimplemented!()
}
}
impl HeaderFormat for SetCookie2 {
fn fmt_header(&self, _f: &mut fmt::Formatter) -> fmt::Result {
unimplemented!()
}
}
let mut headers = self.response_headers.borrow().clone();
headers.remove::<SetCookie>();
headers.remove::<SetCookie2>();
// XXXManishearth additional CORS filtering goes here
headers
}
}
trait Extractable {
fn extract(&self) -> Vec<u8>;
}
impl Extractable for SendParam {
fn extract(&self) -> Vec<u8> {
// http://fetch.spec.whatwg.org/#concept-fetchbodyinit-extract
let encoding = UTF_8 as EncodingRef;
match *self {
eString(ref s) => encoding.encode(s.as_slice(), EncoderTrap::Replace).unwrap(),
eURLSearchParams(ref usp) => usp.root().r().serialize(None) // Default encoding is UTF8
}
}
}<|fim▁end|> | // perhaps should be handled by the resource_loader?
spawn_named("XHR:Cors".to_owned(), move || {
let response = req2.http_fetch(); |
<|file_name|>tuple-struct-destructuring.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or<|fim▁hole|>// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Foo(isize, isize);
pub fn main() {
let x = Foo(1, 2);
let Foo(y, z) = x;
println!("{} {}", y, z);
assert_eq!(y, 1);
assert_eq!(z, 2);
}<|fim▁end|> | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
<|file_name|>facebook_mysql.py<|end_file_name|><|fim▁begin|># __author__ = MelissaChan
# -*- coding: utf-8 -*-
# 16-4-16 下午10:53
import MySQLdb
def connect(id,name,gender,region,status,date,inter):
try:
conn = MySQLdb.connect(host='localhost',user='root',passwd=' ',port=3306)
cur = conn.cursor()
# cur.execute('create database if not exists PythonDB')
conn.select_db('Facebook')
# cur.execute('create table Test(id int,name varchar(20),info varchar(20))')
value = [id,name,gender,region,status,date,inter]
cur.execute('insert into info values(%s,%s,%s,%s,%s,%s,%s)',value)
# values = []
# for i in range(20):
# values.append((i,'Hello World!','My number is '+str(i)))<|fim▁hole|> # cur.executemany('insert into Test values(%s,%s,%s)',values)
# cur.execute('update Test set name="ACdreamer" where id=3')
conn.commit()
cur.close()
conn.close()
print 'insert ok~'
except MySQLdb.Error,msg:
print "MySQL Error %d: %s" %(msg.args[0],msg.args[1])<|fim▁end|> | # |
<|file_name|>gpu_vector.rs<|end_file_name|><|fim▁begin|>//! Wrapper for an OpenGL buffer object.
use std::mem;
use gl;
use gl::types::*;
use resource::gl_primitive::GLPrimitive;
#[path = "../error.rs"]
mod error;
struct GLHandle {
handle: GLuint
}
impl GLHandle {
pub fn new(handle: GLuint) -> GLHandle {
GLHandle {
handle: handle
}
}
pub fn handle(&self) -> GLuint {
self.handle
}
}
impl Drop for GLHandle {
fn drop(&mut self) {
unsafe {<|fim▁hole|> verify!(gl::DeleteBuffers(1, &self.handle))
}
}
}
// FIXME: generalize this for any resource: GPUResource
/// A vector of elements that can be loaded to the GPU, on the RAM, or both.
pub struct GPUVector<T> {
trash: bool,
len: usize,
buf_type: BufferType,
alloc_type: AllocationType,
handle: Option<(usize, GLHandle)>,
data: Option<Vec<T>>,
}
// FIXME: implement Clone
impl<T: GLPrimitive> GPUVector<T> {
/// Creates a new `GPUVector` that is not yet uploaded to the GPU.
pub fn new(data: Vec<T>, buf_type: BufferType, alloc_type: AllocationType) -> GPUVector<T> {
GPUVector {
trash: true,
len: data.len(),
buf_type: buf_type,
alloc_type: alloc_type,
handle: None,
data: Some(data)
}
}
/// The length of this vector.
#[inline]
pub fn len(&self) -> usize {
if self.trash {
match self.data {
Some(ref d) => d.len(),
None => panic!("This should never happend.")
}
}
else {
self.len
}
}
/// Mutably accesses the vector if it is available on RAM.
///
/// This method will mark this vector as `trash`.
#[inline]
pub fn data_mut<'a>(&'a mut self) -> &'a mut Option<Vec<T>> {
self.trash = true;
&mut self.data
}
/// Immutably accesses the vector if it is available on RAM.
#[inline]
pub fn data<'a>(&'a self) -> &'a Option<Vec<T>> {
&self.data
}
/// Returns `true` if this vector is already uploaded to the GPU.
#[inline]
pub fn is_on_gpu(&self) -> bool {
self.handle.is_some()
}
/// Returns `true` if the cpu data and gpu data are out of sync.
#[inline]
pub fn trash(&self) -> bool {
self.trash
}
/// Returns `true` if this vector is available on RAM.
///
/// Note that a `GPUVector` may be both on RAM and on the GPU.
#[inline]
pub fn is_on_ram(&self) -> bool {
self.data.is_some()
}
/// Loads the vector from the RAM to the GPU.
///
/// If the vector is not available on RAM or already loaded to the GPU, nothing will happen.
#[inline]
pub fn load_to_gpu(&mut self) {
if !self.is_on_gpu() {
let buf_type = self.buf_type;
let alloc_type = self.alloc_type;
let len = &mut self.len;
self.handle = self.data.as_ref().map(|d| {
*len = d.len();
(d.len(), GLHandle::new(upload_buffer(&d[..], buf_type, alloc_type)))
});
}
else if self.trash() {
for d in self.data.iter() {
self.len = d.len();
match self.handle {
None => { },
Some((ref mut len, ref handle)) => {
let handle = handle.handle();
*len = update_buffer(&d[..], *len, handle, self.buf_type, self.alloc_type)
}
}
}
}
self.trash = false;
}
/// Binds this vector to the appropriate gpu array.
///
/// This does not associate this buffer with any shader attribute.
#[inline]
pub fn bind(&mut self) {
self.load_to_gpu();
let handle = self.handle.as_ref().map(|&(_, ref h)| h.handle()).expect("Could not bind the vector: data unavailable.");
verify!(gl::BindBuffer(self.buf_type.to_gl(), handle));
}
/// Unbind this vector to the corresponding gpu buffer.
#[inline]
pub fn unbind(&mut self) {
if self.is_on_gpu() {
verify!(gl::BindBuffer(self.buf_type.to_gl(), 0));
}
}
/// Loads the vector from the GPU to the RAM.
///
/// If the vector is not available on the GPU or already loaded to the RAM, nothing will
/// happen.
#[inline]
pub fn load_to_ram(&mut self) {
if !self.is_on_ram() && self.is_on_gpu() {
assert!(!self.trash);
let handle = self.handle.as_ref().map(|&(_, ref h)| h.handle()).unwrap();
let mut data = Vec::with_capacity(self.len);
unsafe { data.set_len(self.len) };
download_buffer(handle, self.buf_type, &mut data[..]);
self.data = Some(data);
}
}
/// Unloads this resource from the GPU.
#[inline]
pub fn unload_from_gpu(&mut self) {
let _ = self.handle.as_ref().map(|&(_, ref h)| unsafe { verify!(gl::DeleteBuffers(1, &h.handle())) });
self.len = self.len();
self.handle = None;
self.trash = false;
}
/// Removes this resource from the RAM.
///
/// This is useful to save memory for vectors required on the GPU only.
#[inline]
pub fn unload_from_ram(&mut self) {
if self.trash && self.is_on_gpu() {
self.load_to_gpu();
}
self.data = None;
}
}
impl<T: Clone + GLPrimitive> GPUVector<T> {
/// Returns this vector as an owned vector if it is available on RAM.
///
/// If it has been uploaded to the GPU, and unloaded from the RAM, call `load_to_ram` first to
/// make the data accessible.
#[inline]
pub fn to_owned(&self) -> Option<Vec<T>> {
self.data.as_ref().map(|d| d.clone())
}
}
/// Type of gpu buffer.
#[derive(Clone, Copy)]
pub enum BufferType {
/// An array buffer bindable to a gl::ARRAY_BUFFER.
Array,
/// An array buffer bindable to a gl::ELEMENT_ARRAY_BUFFER.
ElementArray
}
impl BufferType {
#[inline]
fn to_gl(&self) -> GLuint {
match *self {
BufferType::Array => gl::ARRAY_BUFFER,
BufferType::ElementArray => gl::ELEMENT_ARRAY_BUFFER
}
}
}
/// Allocation type of gpu buffers.
#[derive(Clone, Copy)]
pub enum AllocationType {
/// STATIC_DRAW allocation type.
StaticDraw,
/// DYNAMIC_DRAW allocation type.
DynamicDraw,
/// STREAM_DRAW allocation type.
StreamDraw
}
impl AllocationType {
#[inline]
fn to_gl(&self) -> GLuint {
match *self {
AllocationType::StaticDraw => gl::STATIC_DRAW,
AllocationType::DynamicDraw => gl::DYNAMIC_DRAW,
AllocationType::StreamDraw => gl::STREAM_DRAW
}
}
}
/// Allocates and uploads a buffer to the gpu.
#[inline]
pub fn upload_buffer<T: GLPrimitive>(buf: &[T],
buf_type: BufferType,
allocation_type: AllocationType)
-> GLuint {
// Upload values of vertices
let mut buf_id: GLuint = 0;
unsafe {
verify!(gl::GenBuffers(1, &mut buf_id));
let _ = update_buffer(buf, 0, buf_id, buf_type, allocation_type);
}
buf_id
}
/// Downloads a buffer from the gpu.
///
///
#[inline]
pub fn download_buffer<T: GLPrimitive>(buf_id: GLuint, buf_type: BufferType, out: &mut [T]) {
unsafe {
verify!(gl::BindBuffer(buf_type.to_gl(), buf_id));
verify!(gl::GetBufferSubData(
buf_type.to_gl(),
0,
(out.len() * mem::size_of::<T>()) as GLsizeiptr,
mem::transmute(&out[0])));
}
}
/// Updates a buffer to the gpu.
///
/// Returns the number of element the bufer on the gpu can hold.
#[inline]
pub fn update_buffer<T: GLPrimitive>(buf: &[T],
gpu_buf_len: usize,
gpu_buf_id: GLuint,
gpu_buf_type: BufferType,
gpu_allocation_type: AllocationType)
-> usize {
unsafe {
verify!(gl::BindBuffer(gpu_buf_type.to_gl(), gpu_buf_id));
if buf.len() < gpu_buf_len {
verify!(gl::BufferSubData(
gpu_buf_type.to_gl(),
0,
(buf.len() * mem::size_of::<T>()) as GLsizeiptr,
mem::transmute(&buf[0])));
gpu_buf_len
}
else {
verify!(gl::BufferData(
gpu_buf_type.to_gl(),
(buf.len() * mem::size_of::<T>()) as GLsizeiptr,
mem::transmute(&buf[0]),
gpu_allocation_type.to_gl()));
buf.len()
}
}
}<|fim▁end|> | |
<|file_name|>CWE762_Mismatched_Memory_Management_Routines__delete_wchar_t_malloc_22a.cpp<|end_file_name|><|fim▁begin|>/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_wchar_t_malloc_22a.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml
Template File: sources-sinks-22a.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: malloc Allocate data using malloc()
* GoodSource: Allocate data using new
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete
* Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources.
*
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__delete_wchar_t_malloc_22
{
#ifndef OMITBAD
/* The global variable below is used to drive control flow in the sink function. Since it is in
a C++ namespace, it doesn't need a globally unique name. */
int badGlobal = 0;
void badSink(wchar_t * data);
void bad()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (wchar_t *)malloc(100*sizeof(wchar_t));
badGlobal = 1; /* true */
badSink(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* The global variables below are used to drive control flow in the sink functions. Since they are in
a C++ namespace, they don't need globally unique names. */
int goodB2G1Global = 0;
int goodB2G2Global = 0;
int goodG2B1Global = 0;
<|fim▁hole|>
static void goodB2G1()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (wchar_t *)malloc(100*sizeof(wchar_t));
goodB2G1Global = 0; /* false */
goodB2G1Sink(data);
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */
void goodB2G2Sink(wchar_t * data);
static void goodB2G2()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (wchar_t *)malloc(100*sizeof(wchar_t));
goodB2G2Global = 1; /* true */
goodB2G2Sink(data);
}
/* goodG2B1() - use goodsource and badsink */
void goodG2B1Sink(wchar_t * data);
static void goodG2B1()
{
wchar_t * data;
/* Initialize data*/
data = NULL;
/* FIX: Allocate memory from the heap using new */
data = new wchar_t;
goodG2B1Global = 1; /* true */
goodG2B1Sink(data);
}
void good()
{
goodB2G1();
goodB2G2();
goodG2B1();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE762_Mismatched_Memory_Management_Routines__delete_wchar_t_malloc_22; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif<|fim▁end|> |
/* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */
void goodB2G1Sink(wchar_t * data);
|
<|file_name|>decorators.py<|end_file_name|><|fim▁begin|>from functools import wraps
from django.shortcuts import get_object_or_404, redirect
from django.http import Http404, HttpResponseForbidden, HttpResponseBadRequest
from autodidact.models import *
def needs_course(view):
@wraps(view)
def wrapper(request, course_slug, *args, **kwargs):
if isinstance(course_slug, Course):
course = course_slug
elif request.user.is_staff:
course = get_object_or_404(Course, slug=course_slug)
else:
course = get_object_or_404(Course, slug=course_slug, active=True)
return view(request, course, *args, **kwargs)
return wrapper
def needs_session(view):
@wraps(view)
def wrapper(request, course, session_nr, *args, **kwargs):
if not isinstance(course, Course):
raise TypeError('Course object required')
if isinstance(session_nr, Session):
session = session_nr
else:
session_nr = int(session_nr)
session = course.sessions.filter(number=session_nr).first()
if session is None:
raise Http404()
if not session.active and not request.user.is_staff:
raise Http404()
return view(request, course, session, *args, **kwargs)
return wrapper
def needs_assignment(view):
@wraps(view)
def wrapper(request, course, session, assignment_nr, *args, **kwargs):
if not isinstance(course, Course):
raise TypeError('Course object required')
if not isinstance(session, Session):
raise TypeError('Session object required')
if isinstance(assignment_nr, Assignment):
assignment = assignment_nr
else:
assignment_nr = int(assignment_nr)
assignment = session.assignments.filter(number=assignment_nr).first()
if assignment is None:
raise Http404()
if not assignment.active and not request.user.is_staff:
raise Http404()
if assignment.locked and not request.user.is_staff:
if not request.user.attends.all() & session.classes.all():
return HttpResponseForbidden('Permission Denied')
return view(request, course, session, assignment, *args, **kwargs)
return wrapper
def needs_step(view):
@wraps(view)
def wrapper(request, course, session, assignment, *args, **kwargs):
if not isinstance(course, Course):
raise TypeError('Course object required')
if not isinstance(session, Session):
raise TypeError('Session object required')
if not isinstance(assignment, Assignment):
raise TypeError('Assignment object required')
try:
step = assignment.steps.filter(number=request.GET.get('step')).first()
if step is None:
# Not sure if this is the right place, but let's
# ensure that an assignment has at least one step
if not assignment.steps.exists():
Step(assignment=assignment).save()
return redirect(assignment.steps.first())
except ValueError:
return HttpResponseBadRequest('Invalid step number')
step.fullscreen = 'fullscreen' in request.GET
step.completedstep = request.user.completed.filter(step=step).first()
step.given_values = step.completedstep.answer.split('\x1e') if step.completedstep else []
step.right_values = [a.value for a in step.right_answers.all()]<|fim▁hole|> step.wrong_values = [a.value for a in step.wrong_answers.all()]
step.graded = bool(step.right_values) and step.answer_required
step.multiple_choice = bool(step.wrong_values)
step.multiple_answers = step.multiple_choice and len(step.right_values) > 1
step.please_try_again = False
return view(request, course, session, assignment, step, *args, **kwargs)
return wrapper<|fim▁end|> | |
<|file_name|>checkout.py<|end_file_name|><|fim▁begin|># Copyright 2006 John Duda
# This file is part of Infoshopkeeper.
# Infoshopkeeper 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 any later version.
# Infoshopkeeper 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 Infoshopkeeper; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
from wxPython.wx import *
import os
import datetime
from objects.emprunt import Emprunt
from popups.members import AddMemberPanel, ShowMembersPanel
class CheckoutPopup(wxDialog):
def __init__(self, parent):
self.parent=parent
wxDialog.__init__(self, parent,-1,"Check out items")
self.mastersizer = wxBoxSizer(wxVERTICAL)
self.static1 = wxStaticText(self, -1, "Check out to :")
self.mastersizer.Add(self.static1)
self.notebook = wxNotebook(self, -1, style=wxNB_TOP)
self.new_member_panel = AddMemberPanel(parent=self.notebook, main_window=parent,
on_successful_add=self.Borrow, cancel=self.Close)
self.notebook.AddPage(self.new_member_panel, "New member")
self.show_member_panel = ShowMembersPanel(parent=self.notebook, main_window=parent, motherDialog=self, on_select=self.Borrow)
self.notebook.AddPage(self.show_member_panel, "Existing member")
self.mastersizer.Add(self.notebook)
self.SetSizer(self.mastersizer)
for i in self.parent.orderbox.items:
print i.database_id, "... ", i.id
#self.b = wxButton(self, -1, "Checkout", (15, 80))
#EVT_BUTTON(self, self.b.GetId(), self.Checkout)
#self.b.SetDefault()
self.mastersizer.SetSizeHints(self)
def Borrow(self, id):
borrower = self.parent.membersList.get(id)
print borrower
for i in self.parent.orderbox.items:
# Check if this work on sqlobject 0.7... I got
# lots of problem on 0.6.1, and itemID __isn't__
# defined in emprunt, which is plain weirdness
e = Emprunt(borrower = id, itemID=i.database_id)
print i.database_id
self.parent.orderbox.setBorrowed()
self.parent.orderbox.void()
self.Close()
def OnCancel(self,event):
self.EndModal(1)
def Checkout(self,event):
borrower=self.borrower.GetValue()
if len(borrower)>0:
today="%s" % datetime.date.today()<|fim▁hole|> self.parent.orderbox.change_status(today+"-"+borrower)
self.parent.orderbox.void()
self.Close()<|fim▁end|> | |
<|file_name|>1451-Rearrange Words in a Sentence.py<|end_file_name|><|fim▁begin|>import collections
class Solution:
def arrangeWords(self, text: str) -> str:<|fim▁hole|> table = collections.defaultdict(list)
for word in words:
table[len(word)].append(word)
result = []
for key in sorted(table):
result.extend(table[key])
return ' '.join(result).capitalize()
# Sort is stable
class Solution2:
def arrangeWords(self, text: str) -> str:
return ' '.join(sorted(text.split(), key=len)).capitalize()<|fim▁end|> | words = text.split() |
<|file_name|>viewModelDecorations.js<|end_file_name|><|fim▁begin|>/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Position } from '../core/position';
import { Range } from '../core/range';
import { InlineDecoration, ViewModelDecoration } from './viewModel';
import { filterValidationDecorations } from '../config/editorOptions';
var ViewModelDecorations = /** @class */ (function () {
function ViewModelDecorations(editorId, model, configuration, linesCollection, coordinatesConverter) {
this.editorId = editorId;
this.model = model;
this.configuration = configuration;
this._linesCollection = linesCollection;
this._coordinatesConverter = coordinatesConverter;
this._decorationsCache = Object.create(null);
this._cachedModelDecorationsResolver = null;
this._cachedModelDecorationsResolverViewRange = null;
}
ViewModelDecorations.prototype._clearCachedModelDecorationsResolver = function () {
this._cachedModelDecorationsResolver = null;
this._cachedModelDecorationsResolverViewRange = null;
};
ViewModelDecorations.prototype.dispose = function () {
this._decorationsCache = Object.create(null);
this._clearCachedModelDecorationsResolver();
};
ViewModelDecorations.prototype.reset = function () {
this._decorationsCache = Object.create(null);
this._clearCachedModelDecorationsResolver();
};
ViewModelDecorations.prototype.onModelDecorationsChanged = function () {
this._decorationsCache = Object.create(null);
this._clearCachedModelDecorationsResolver();
};
ViewModelDecorations.prototype.onLineMappingChanged = function () {
this._decorationsCache = Object.create(null);
this._clearCachedModelDecorationsResolver();
};
ViewModelDecorations.prototype._getOrCreateViewModelDecoration = function (modelDecoration) {
var id = modelDecoration.id;
var r = this._decorationsCache[id];
if (!r) {
var modelRange = modelDecoration.range;
var options = modelDecoration.options;
var viewRange = void 0;
if (options.isWholeLine) {
var start = this._coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.startLineNumber, 1));
var end = this._coordinatesConverter.convertModelPositionToViewPosition(new Position(modelRange.endLineNumber, this.model.getLineMaxColumn(modelRange.endLineNumber)));
viewRange = new Range(start.lineNumber, start.column, end.lineNumber, end.column);
}
else {
viewRange = this._coordinatesConverter.convertModelRangeToViewRange(modelRange);
}
r = new ViewModelDecoration(viewRange, options);
this._decorationsCache[id] = r;
}
return r;
};
ViewModelDecorations.prototype.getDecorationsViewportData = function (viewRange) {
var cacheIsValid = (this._cachedModelDecorationsResolver !== null);
cacheIsValid = cacheIsValid && (viewRange.equalsRange(this._cachedModelDecorationsResolverViewRange));
if (!cacheIsValid) {
this._cachedModelDecorationsResolver = this._getDecorationsViewportData(viewRange);
this._cachedModelDecorationsResolverViewRange = viewRange;
}
return this._cachedModelDecorationsResolver;
};
ViewModelDecorations.prototype._getDecorationsViewportData = function (viewportRange) {
var modelDecorations = this._linesCollection.getDecorationsInRange(viewportRange, this.editorId, filterValidationDecorations(this.configuration.options));
var startLineNumber = viewportRange.startLineNumber;
var endLineNumber = viewportRange.endLineNumber;
var decorationsInViewport = [], decorationsInViewportLen = 0;
var inlineDecorations = [];
for (var j = startLineNumber; j <= endLineNumber; j++) {
inlineDecorations[j - startLineNumber] = [];
}
for (var i = 0, len = modelDecorations.length; i < len; i++) {
var modelDecoration = modelDecorations[i];
var decorationOptions = modelDecoration.options;
var viewModelDecoration = this._getOrCreateViewModelDecoration(modelDecoration);
var viewRange = viewModelDecoration.range;
decorationsInViewport[decorationsInViewportLen++] = viewModelDecoration;
if (decorationOptions.inlineClassName) {
var inlineDecoration = new InlineDecoration(viewRange, decorationOptions.inlineClassName, decorationOptions.inlineClassNameAffectsLetterSpacing ? 3 /* RegularAffectingLetterSpacing */ : 0 /* Regular */);
var intersectedStartLineNumber = Math.max(startLineNumber, viewRange.startLineNumber);
var intersectedEndLineNumber = Math.min(endLineNumber, viewRange.endLineNumber);
for (var j = intersectedStartLineNumber; j <= intersectedEndLineNumber; j++) {
inlineDecorations[j - startLineNumber].push(inlineDecoration);
}
}
if (decorationOptions.beforeContentClassName) {
if (startLineNumber <= viewRange.startLineNumber && viewRange.startLineNumber <= endLineNumber) {
var inlineDecoration = new InlineDecoration(new Range(viewRange.startLineNumber, viewRange.startColumn, viewRange.startLineNumber, viewRange.startColumn), decorationOptions.beforeContentClassName, 1 /* Before */);
inlineDecorations[viewRange.startLineNumber - startLineNumber].push(inlineDecoration);
}
}
if (decorationOptions.afterContentClassName) {
if (startLineNumber <= viewRange.endLineNumber && viewRange.endLineNumber <= endLineNumber) {
var inlineDecoration = new InlineDecoration(new Range(viewRange.endLineNumber, viewRange.endColumn, viewRange.endLineNumber, viewRange.endColumn), decorationOptions.afterContentClassName, 2 /* After */);<|fim▁hole|> }
return {
decorations: decorationsInViewport,
inlineDecorations: inlineDecorations
};
};
return ViewModelDecorations;
}());
export { ViewModelDecorations };<|fim▁end|> | inlineDecorations[viewRange.endLineNumber - startLineNumber].push(inlineDecoration);
}
} |
<|file_name|>macro-only-syntax.rs<|end_file_name|><|fim▁begin|>// force-host
// no-prefer-dynamic
// These are tests for syntax that is accepted by the Rust parser but
// unconditionally rejected semantically after macro expansion. Attribute macros
// are permitted to accept such syntax as long as they replace it with something
// that makes sense to Rust.
//
// We also inspect some of the spans to verify the syntax is not triggering the
// lossy string reparse hack (https://github.com/rust-lang/rust/issues/43081).
#![crate_type = "proc-macro"]
#![feature(proc_macro_span)]
extern crate proc_macro;
use proc_macro::{token_stream, Delimiter, TokenStream, TokenTree};
use std::path::Component;
// unsafe mod m {
// pub unsafe mod inner;
// }
#[proc_macro_attribute]
pub fn expect_unsafe_mod(_attrs: TokenStream, input: TokenStream) -> TokenStream {
let tokens = &mut input.into_iter();
expect(tokens, "unsafe");
expect(tokens, "mod");
expect(tokens, "m");
let tokens = &mut expect_brace(tokens);
expect(tokens, "pub");
expect(tokens, "unsafe");
expect(tokens, "mod");
let ident = expect(tokens, "inner");
expect(tokens, ";");
check_useful_span(ident, "unsafe-mod.rs");
TokenStream::new()
}
<|fim▁hole|>// }
#[proc_macro_attribute]
pub fn expect_unsafe_foreign_mod(_attrs: TokenStream, input: TokenStream) -> TokenStream {
let tokens = &mut input.into_iter();
expect(tokens, "unsafe");
expect(tokens, "extern");
let tokens = &mut expect_brace(tokens);
expect(tokens, "type");
let ident = expect(tokens, "T");
expect(tokens, ";");
check_useful_span(ident, "unsafe-foreign-mod.rs");
TokenStream::new()
}
// unsafe extern "C++" {}
#[proc_macro_attribute]
pub fn expect_unsafe_extern_cpp_mod(_attrs: TokenStream, input: TokenStream) -> TokenStream {
let tokens = &mut input.into_iter();
expect(tokens, "unsafe");
expect(tokens, "extern");
let abi = expect(tokens, "\"C++\"");
expect_brace(tokens);
check_useful_span(abi, "unsafe-foreign-mod.rs");
TokenStream::new()
}
fn expect(tokens: &mut token_stream::IntoIter, expected: &str) -> TokenTree {
match tokens.next() {
Some(token) if token.to_string() == expected => token,
wrong => panic!("unexpected token: {:?}, expected `{}`", wrong, expected),
}
}
fn expect_brace(tokens: &mut token_stream::IntoIter) -> token_stream::IntoIter {
match tokens.next() {
Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Brace => {
group.stream().into_iter()
}
wrong => panic!("unexpected token: {:?}, expected `{{`", wrong),
}
}
fn check_useful_span(token: TokenTree, expected_filename: &str) {
let span = token.span();
assert!(span.start().column < span.end().column);
let source_path = span.source_file().path();
let filename = source_path.components().last().unwrap();
assert_eq!(filename, Component::Normal(expected_filename.as_ref()));
}<|fim▁end|> | // unsafe extern {
// type T; |
<|file_name|>expected.js<|end_file_name|><|fim▁begin|>var foo = arr.map(v => ({
x: v.bar,<|fim▁hole|> y: v.bar * 2
}));
var fn = () => ({}).key;<|fim▁end|> | |
<|file_name|>xencreate.py<|end_file_name|><|fim▁begin|>"""
Virtualization installation functions.
Currently somewhat Xen/paravirt specific, will evolve later.
Copyright 2006-2008 Red Hat, Inc.
Michael DeHaan <[email protected]>
Original version based on virtguest-install
Jeremy Katz <[email protected]>
Option handling added by Andrew Puch <[email protected]>
Simplified for use as library by koan, Michael DeHaan <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
"""
import os, sys, time, stat
import tempfile
import random
import exceptions
import errno
import re
import virtinst
import app as koan
try:
import virtinst.DistroManager as DistroManager
except:
# older virtinst, this is probably ok
# but we know we can't do Xen fullvirt installs
pass
import traceback
def random_mac():
"""
from xend/server/netif.py
Generate a random MAC address.
Uses OUI 00-16-3E, allocated to
Xensource, Inc. Last 3 fields are random.
return: MAC address string
"""
mac = [ 0x00, 0x16, 0x3e,
random.randint(0x00, 0x7f),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff) ]
return ':'.join(map(lambda x: "%02x" % x, mac))
def start_install(name=None, ram=None, disks=None,
uuid=None,
extra=None,
vcpus=None,
profile_data=None, arch=None, no_gfx=False, fullvirt=False, bridge=None):
if profile_data.has_key("file"):
raise koan.InfoException("Xen does not work with --image yet")
if fullvirt:
# FIXME: add error handling here to explain when it's not supported
guest = virtinst.FullVirtGuest(installer=DistroManager.PXEInstaller())
else:
guest = virtinst.ParaVirtGuest()
extra = extra.replace("&","&")
if not fullvirt:
guest.set_boot((profile_data["kernel_local"], profile_data["initrd_local"]))
# fullvirt OS's will get this from the PXE config (managed by Cobbler)
guest.extraargs = extra
else:
print "- fullvirt mode"
if profile_data.has_key("breed"):
breed = profile_data["breed"]
if breed != "other" and breed != "":
if breed in [ "debian", "suse", "redhat" ]:
guest.set_os_type("linux")
elif breed in [ "windows" ]:
guest.set_os_type("windows")
else:
guest.set_os_type("unix")
if profile_data.has_key("os_version"):
# FIXME: when os_version is not defined and it's linux, do we use generic24/generic26 ?
version = profile_data["os_version"]
if version != "other" and version != "":
try:
guest.set_os_variant(version)
except:
print "- virtinst library does not understand variant %s, treating as generic" % version
pass
guest.set_name(name)
guest.set_memory(ram)
guest.set_vcpus(vcpus)
<|fim▁hole|>
if uuid is not None:
guest.set_uuid(uuid)
for d in disks:
if d[1] != 0:
guest.disks.append(virtinst.XenDisk(d[0], size=d[1]))
counter = 0
if profile_data.has_key("interfaces"):
interfaces = profile_data["interfaces"].keys()
interfaces.sort()
counter = -1
for iname in interfaces:
counter = counter + 1
intf = profile_data["interfaces"][iname]
mac = intf["mac_address"]
if mac == "":
mac = random_mac()
if not bridge:
profile_bridge = profile_data["virt_bridge"]
intf_bridge = intf["virt_bridge"]
if intf_bridge == "":
if profile_bridge == "":
raise koan.InfoException("virt-bridge setting is not defined in cobbler")
intf_bridge = profile_bridge
else:
if bridge.find(",") == -1:
intf_bridge = bridge
else:
bridges = bridge.split(",")
intf_bridge = bridges[counter]
nic_obj = virtinst.XenNetworkInterface(macaddr=mac, bridge=intf_bridge)
guest.nics.append(nic_obj)
counter = counter + 1
else:
# for --profile you just get one NIC, go define a system if you want more.
# FIXME: can mac still be sent on command line in this case?
if bridge is None:
profile_bridge = profile_data["virt_bridge"]
else:
profile_bridge = bridge
if profile_bridge == "":
raise koan.InfoException("virt-bridge setting is not defined in cobbler")
nic_obj = virtinst.XenNetworkInterface(macaddr=random_mac(), bridge=profile_bridge)
guest.nics.append(nic_obj)
guest.start_install()
return "use virt-manager or reconnect with virsh console %s" % name<|fim▁end|> | if not no_gfx:
guest.set_graphics("vnc")
else:
guest.set_graphics(False) |
<|file_name|>instance_metadata.rs<|end_file_name|><|fim▁begin|>//! The Credentials Provider for an AWS Resource's IAM Role.
use async_trait::async_trait;
use hyper::Uri;
use std::time::Duration;
use crate::request::HttpClient;
use crate::{
parse_credentials_from_aws_service, AwsCredentials, CredentialsError, ProvideAwsCredentials,
};
const AWS_CREDENTIALS_PROVIDER_IP: &str = "169.254.169.254";
const AWS_CREDENTIALS_PROVIDER_PATH: &str = "latest/meta-data/iam/security-credentials";
/// Provides AWS credentials from a resource's IAM role.
///
/// The provider has a default timeout of 30 seconds. While it should work well for most setups,
/// you can change the timeout using the `set_timeout` method.<|fim▁hole|>/// ```rust
/// use std::time::Duration;
///
/// use rusoto_credential::InstanceMetadataProvider;
///
/// let mut provider = InstanceMetadataProvider::new();
/// // you can overwrite the default timeout like this:
/// provider.set_timeout(Duration::from_secs(60));
/// ```
///
/// The source location can be changed from the default of 169.254.169.254:
///
/// ```rust
/// use std::time::Duration;
///
/// use rusoto_credential::InstanceMetadataProvider;
///
/// let mut provider = InstanceMetadataProvider::new();
/// // you can overwrite the default endpoint like this:
/// provider.set_ip_addr_with_port("127.0.0.1", "8080");
/// ```
#[derive(Clone, Debug)]
pub struct InstanceMetadataProvider {
client: HttpClient,
timeout: Duration,
metadata_ip_addr: String,
}
impl InstanceMetadataProvider {
/// Create a new provider with the given handle.
pub fn new() -> Self {
InstanceMetadataProvider {
client: HttpClient::new(),
timeout: Duration::from_secs(30),
metadata_ip_addr: AWS_CREDENTIALS_PROVIDER_IP.to_string(),
}
}
/// Set the timeout on the provider to the specified duration.
pub fn set_timeout(&mut self, timeout: Duration) {
self.timeout = timeout;
}
/// Allow overriding host and port of instance metadata service.
pub fn set_ip_addr_with_port(&mut self, ip: &str, port: &str) {
self.metadata_ip_addr = format!("{}:{}", ip, port);
}
}
impl Default for InstanceMetadataProvider {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl ProvideAwsCredentials for InstanceMetadataProvider {
async fn credentials(&self) -> Result<AwsCredentials, CredentialsError> {
let role_name = get_role_name(&self.client, self.timeout, &self.metadata_ip_addr)
.await
.map_err(|err| CredentialsError {
message: format!("Could not get credentials from iam: {}", err.to_string()),
})?;
let cred_str = get_credentials_from_role(
&self.client,
self.timeout,
&role_name,
&self.metadata_ip_addr,
)
.await
.map_err(|err| CredentialsError {
message: format!("Could not get credentials from iam: {}", err.to_string()),
})?;
parse_credentials_from_aws_service(&cred_str)
}
}
/// Gets the role name to get credentials for using the IAM Metadata Service (169.254.169.254).
async fn get_role_name(
client: &HttpClient,
timeout: Duration,
ip_addr: &str,
) -> Result<String, CredentialsError> {
let role_name_address = format!("http://{}/{}/", ip_addr, AWS_CREDENTIALS_PROVIDER_PATH);
let uri = match role_name_address.parse::<Uri>() {
Ok(u) => u,
Err(e) => return Err(CredentialsError::new(e)),
};
Ok(client.get(uri, timeout).await?)
}
/// Gets the credentials for an EC2 Instances IAM Role.
async fn get_credentials_from_role(
client: &HttpClient,
timeout: Duration,
role_name: &str,
ip_addr: &str,
) -> Result<String, CredentialsError> {
let credentials_provider_url = format!(
"http://{}/{}/{}",
ip_addr, AWS_CREDENTIALS_PROVIDER_PATH, role_name
);
let uri = match credentials_provider_url.parse::<Uri>() {
Ok(u) => u,
Err(e) => return Err(CredentialsError::new(e)),
};
Ok(client.get(uri, timeout).await?)
}<|fim▁end|> | ///
/// # Examples
/// |
<|file_name|>repair_test.py<|end_file_name|><|fim▁begin|>import time
import pytest
import logging
from repair_tests.repair_test import BaseRepairTest
since = pytest.mark.since
logger = logging.getLogger(__name__)
LEGACY_SSTABLES_JVM_ARGS = ["-Dcassandra.streamdes.initial_mem_buffer_size=1",
"-Dcassandra.streamdes.max_mem_buffer_size=5",
"-Dcassandra.streamdes.max_spill_file_size=16"]
# We don't support directly upgrading from 2.2 to 4.0 so disabling this on 4.0.
# TODO: we should probably not hardcode versions?
@pytest.mark.upgrade_test
@since('3.0', max_version='3.99')
class TestUpgradeRepair(BaseRepairTest):
@since('3.0', max_version='3.99')
def test_repair_after_upgrade(self):
"""
@jira_ticket CASSANDRA-10990
"""<|fim▁hole|> cluster = self.cluster
logger.debug("Setting version to 2.2.5")
cluster.set_install_dir(version="2.2.5")
self._populate_cluster()
self._do_upgrade(default_install_dir)
self._repair_and_verify(True)
def _do_upgrade(self, default_install_dir):
cluster = self.cluster
for node in cluster.nodelist():
logger.debug("Upgrading %s to current version" % node.name)
if node.is_running():
node.flush()
time.sleep(1)
node.stop(wait_other_notice=True)
node.set_install_dir(install_dir=default_install_dir)
node.start(wait_other_notice=True, wait_for_binary_proto=True)
cursor = self.patient_cql_connection(node)
cluster.set_install_dir(default_install_dir)<|fim▁end|> | default_install_dir = self.cluster.get_install_dir() |
<|file_name|>pencil_et.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="et" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../app/ui/aboutdialog.ui" line="26"/>
<source>About</source>
<comment>About Dialog Window Title</comment>
<translation>Info</translation>
</message>
<message>
<location filename="../app/ui/aboutdialog.ui" line="52"/>
<source>Official site: <a href="https://www.pencil2d.org">pencil2d.org</a><br>Developed by: <b>Pascal Naidon, Patrick Corrieri, Matt Chang</b><br>Thanks to Qt Framework <a href="https://www.qt.io/download">https://www.qt.io/</a><br>miniz: <a href="https://github.com/richgel999/miniz">https://github.com/richgel999/miniz</a><br>Distributed under the <a href="http://www.gnu.org/licenses/gpl-2.0.html">GNU General Public License, version 2</a></source>
<translation>Ametlik veebisait: <a href="https://www.pencil2d.org">pencil2d.org</a><br>Arendaja: <b>Pascal Naidon, Patrick Corrieri, Matt Chang</b><br>Suur tänu Qt Frameworkile <a href="https://www.qt.io/download">https://www.qt.io/</a><br>miniz: <a href="https://github.com/richgel999/miniz">https://github.com/richgel999/miniz</a><br>Levitatakse <a href="http://www.gnu.org/licenses/gpl-2.0.html">GNU General Public License, version 2</a> alusel</translation>
</message>
<message>
<location filename="../app/src/aboutdialog.cpp" line="43"/>
<source>Version: %1</source>
<comment>Version Number in About Dialog</comment>
<translation>Versioon: %1</translation>
</message>
<message>
<location filename="../app/src/aboutdialog.cpp" line="55"/>
<source>Copy to clipboard</source>
<comment>Copy system info from About Dialog</comment>
<translation>Kopeeri lõikelauale</translation>
</message>
</context>
<context>
<name>ActionCommands</name>
<message>
<location filename="../app/src/actioncommands.cpp" line="68"/>
<source>No sound layer exists as a destination for your import. Create a new sound layer?</source>
<translation>Importimise sihtkohas pole helikihti. Kas loon uue helikihi?</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="69"/>
<source>Create sound layer</source>
<translation>Loo helikiht</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="70"/>
<source>Don't create layer</source>
<translation>Ära loo kihti</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="80"/>
<source>Layer Properties</source>
<comment>Dialog title on creating a sound layer</comment>
<translation>Kihi omadused</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="82"/>
<source>Sound Layer</source>
<comment>Default name on creating a sound layer</comment>
<translation>Helikiht</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="201"/>
<source>Exporting movie</source>
<translation>Video eksportimine</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="253"/>
<source>Finished. Open movie now?</source>
<comment>When movie export done.</comment>
<translation>Lõpetatud. Kas avada video?</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="595"/>
<location filename="../app/src/actioncommands.cpp" line="608"/>
<location filename="../app/src/actioncommands.cpp" line="622"/>
<location filename="../app/src/actioncommands.cpp" line="636"/>
<source>Layer Properties</source>
<translation>Kihi omadused</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="81"/>
<location filename="../app/src/actioncommands.cpp" line="596"/>
<location filename="../app/src/actioncommands.cpp" line="609"/>
<location filename="../app/src/actioncommands.cpp" line="623"/>
<location filename="../app/src/actioncommands.cpp" line="637"/>
<source>Layer name:</source>
<translation>Kihi nimi:</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="108"/>
<source>A sound clip already exists on this frame! Please select another frame or layer.</source>
<translation>Heliklipp on selles kaadris juba olemas! Palun vali teine kaader või kiht.</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="243"/>
<source>Finished. Open file location?</source>
<translation>Lõpetatud. Kas avada faili asukoht?</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="314"/>
<source>Exporting image sequence...</source>
<translation>Pildiseeria importimine...</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="314"/>
<source>Abort</source>
<translation>Katkesta</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="394"/>
<source>Warning</source>
<translation>Hoiatus</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="395"/>
<source>Unable to export image.</source>
<translation>Pildi eksportimine ebaõnnestus.</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="597"/>
<source>Bitmap Layer</source>
<translation>Pildifaili kiht</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="610"/>
<source>Vector Layer</source>
<translation>Vektorkiht</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="624"/>
<source>Camera Layer</source>
<translation>Kaamera kiht</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="638"/>
<source>Sound Layer</source>
<translation>Helikiht</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="655"/>
<source>Delete Layer</source>
<comment>Windows title of Delete current layer pop-up.</comment>
<translation>Kustuta kiht</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="656"/>
<source>Are you sure you want to delete layer: </source>
<translation>Oled sa kindel, et soovid kusutada kihti:</translation>
</message>
<message>
<location filename="../app/src/actioncommands.cpp" line="665"/>
<source>Please keep at least one camera layer in project</source>
<comment>text when failed to delete camera layer</comment>
<translation>Palun hoia projektis alles vähemalt üks kaamerakiht</translation>
</message>
</context>
<context>
<name>BaseTool</name>
<message>
<location filename="../core_lib/src/tool/basetool.cpp" line="41"/>
<source>Pencil</source>
<translation>Pliiats</translation>
</message>
<message>
<location filename="../core_lib/src/tool/basetool.cpp" line="42"/>
<source>Eraser</source>
<translation>Kustukumm</translation>
</message>
<message>
<location filename="../core_lib/src/tool/basetool.cpp" line="43"/>
<source>Select</source>
<translation>Valimine</translation>
</message>
<message>
<location filename="../core_lib/src/tool/basetool.cpp" line="44"/>
<source>Move</source>
<translation>Liigutamine</translation>
</message>
<message>
<location filename="../core_lib/src/tool/basetool.cpp" line="45"/>
<source>Hand</source>
<translation>Käsi</translation>
</message>
<message>
<location filename="../core_lib/src/tool/basetool.cpp" line="46"/>
<source>Smudge</source>
<translation>Hägustamine</translation>
</message>
<message>
<location filename="../core_lib/src/tool/basetool.cpp" line="47"/>
<source>Pen</source>
<translation>Pliiats</translation>
</message>
<message>
<location filename="../core_lib/src/tool/basetool.cpp" line="48"/>
<source>Polyline</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/tool/basetool.cpp" line="49"/>
<source>Bucket</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/tool/basetool.cpp" line="50"/>
<source>Eyedropper</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/tool/basetool.cpp" line="51"/>
<source>Brush</source>
<translation>Pintsel</translation>
</message>
</context>
<context>
<name>CameraPropertiesDialog</name>
<message>
<location filename="../core_lib/ui/camerapropertiesdialog.ui" line="6"/>
<source>Camera Properties</source>
<translation>Kaamera omadused</translation>
</message>
<message>
<location filename="../core_lib/ui/camerapropertiesdialog.ui" line="14"/>
<source>Camera name:</source>
<translation>Kaamera nimi:</translation>
</message>
<message>
<location filename="../core_lib/ui/camerapropertiesdialog.ui" line="38"/>
<source>Camera size:</source>
<translation>Kaamera suurus:</translation>
</message>
</context>
<context>
<name>ColorBox</name>
<message>
<location filename="../app/src/colorbox.cpp" line="26"/>
<source>Color Box</source>
<comment>Color Box window title</comment>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ColorInspector</name>
<message>
<location filename="../app/ui/colorinspector.ui" line="65"/>
<source>HSV</source>
<translation>HSV</translation>
</message>
<message>
<location filename="../app/ui/colorinspector.ui" line="99"/>
<source>RGB</source>
<translation>RGB</translation>
</message>
<message>
<location filename="../app/ui/colorinspector.ui" line="254"/>
<source>R</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/colorinspector.ui" line="161"/>
<source>A</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/colorinspector.ui" line="211"/>
<source>G</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/colorinspector.ui" line="264"/>
<source>B</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colorinspector.cpp" line="35"/>
<source>Color Inspector</source>
<comment>Window title of color inspector</comment>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ColorPalette</name>
<message>
<location filename="../app/ui/colorpalette.ui" line="14"/>
<source>Color Palette</source>
<comment>Window title of color palette.</comment>
<translation>Värvipalett</translation>
</message>
<message>
<location filename="../app/ui/colorpalette.ui" line="47"/>
<source>Add Color</source>
<translation>Lisa värv</translation>
</message>
<message>
<location filename="../app/ui/colorpalette.ui" line="76"/>
<source>Remove Color</source>
<translation>Eemalda värv</translation>
</message>
<message>
<location filename="../app/ui/colorpalette.ui" line="133"/>
<source>Native color dialog window</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/colorpalette.ui" line="258"/>
<source>List Mode</source>
<translation>Nimekirjarežiim</translation>
</message>
<message>
<location filename="../app/ui/colorpalette.ui" line="261"/>
<source>Show palette as a list</source>
<translation>Näita paletti nimekirjana</translation>
</message>
<message>
<location filename="../app/ui/colorpalette.ui" line="269"/>
<source>Grid Mode</source>
<translation>Võrgustiku režiim</translation>
</message>
<message>
<location filename="../app/ui/colorpalette.ui" line="272"/>
<source>Show palette as icons</source>
<translation>Näita palette ikoonidena</translation>
</message>
<message>
<location filename="../app/ui/colorpalette.ui" line="282"/>
<source>Small swatch</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/colorpalette.ui" line="285"/>
<source>Sets swatch size to: 16x16px</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/colorpalette.ui" line="293"/>
<source>Medium Swatch</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/colorpalette.ui" line="296"/>
<source>Sets swatch size to: 26x26px</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/colorpalette.ui" line="307"/>
<source>Large Swatch</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/colorpalette.ui" line="310"/>
<source>Sets swatch size to: 36x36px</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ColorPaletteWidget</name>
<message>
<location filename="../app/src/colorpalettewidget.cpp" line="105"/>
<source>Add</source>
<translation>Lisa</translation>
</message>
<message>
<location filename="../app/src/colorpalettewidget.cpp" line="106"/>
<source>Replace</source>
<translation>Asenda</translation>
</message>
<message>
<location filename="../app/src/colorpalettewidget.cpp" line="107"/>
<source>Remove</source>
<translation>Eemalda</translation>
</message>
<message>
<location filename="../app/src/colorpalettewidget.cpp" line="246"/>
<location filename="../app/src/colorpalettewidget.cpp" line="247"/>
<source>Colour name</source>
<translation>Värvi nimi</translation>
</message>
<message>
<location filename="../app/src/colorpalettewidget.cpp" line="544"/>
<source>The color(s) you are about to delete are currently being used by one or multiple strokes.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colorpalettewidget.cpp" line="545"/>
<source>Cancel</source>
<translation>Loobu</translation>
</message>
<message>
<location filename="../app/src/colorpalettewidget.cpp" line="546"/>
<source>Delete</source>
<translation>Kustuta</translation>
</message>
<message>
<location filename="../app/src/colorpalettewidget.cpp" line="562"/>
<source>Palette Restriction</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colorpalettewidget.cpp" line="563"/>
<source>The palette requires at least one swatch to remain functional</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ColorWheel</name>
<message>
<location filename="../app/src/colorwheel.cpp" line="32"/>
<source>Color Wheel</source>
<comment>Color Wheel's window title</comment>
<translation>Värviratas</translation>
</message>
</context>
<context>
<name>DisplayOption</name>
<message>
<location filename="../app/ui/displayoption.ui" line="67"/>
<source>Horizontal flip</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/displayoption.ui" line="44"/>
<location filename="../app/ui/displayoption.ui" line="102"/>
<location filename="../app/ui/displayoption.ui" line="134"/>
<location filename="../app/ui/displayoption.ui" line="166"/>
<location filename="../app/ui/displayoption.ui" line="192"/>
<location filename="../app/ui/displayoption.ui" line="221"/>
<location filename="../app/ui/displayoption.ui" line="259"/>
<source>...</source>
<translation>...</translation>
</message>
<message>
<location filename="../app/ui/displayoption.ui" line="14"/>
<source>Display</source>
<comment>Window title of display options like .</comment>
<translation>Vaade</translation>
</message>
<message>
<location filename="../app/ui/displayoption.ui" line="125"/>
<location filename="../app/ui/displayoption.ui" line="128"/>
<source>Onion skin previous frame</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/displayoption.ui" line="163"/>
<source>Show invisible lines</source>
<translation>Näita nähtamatuid jooni</translation>
</message>
<message>
<location filename="../app/ui/displayoption.ui" line="250"/>
<location filename="../app/ui/displayoption.ui" line="253"/>
<source>Onion skin color: blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/displayoption.ui" line="38"/>
<location filename="../app/ui/displayoption.ui" line="41"/>
<source>Onion skin next frame</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/displayoption.ui" line="215"/>
<location filename="../app/ui/displayoption.ui" line="218"/>
<source>Onion skin color: red</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/displayoption.ui" line="189"/>
<source>Show outlines only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/displayoption.ui" line="99"/>
<source>Vertical flip</source>
<translation>Vertikaalne peegeldamine</translation>
</message>
</context>
<context>
<name>DoubleProgressDialog</name>
<message>
<location filename="../app/ui/doubleprogressdialog.ui" line="27"/>
<source>Loading...</source>
<translation>Laadimine...</translation>
</message>
<message>
<location filename="../app/ui/doubleprogressdialog.ui" line="56"/>
<source>Cancel</source>
<translation>LOobu</translation>
</message>
</context>
<context>
<name>Editor</name>
<message>
<location filename="../core_lib/src/interface/editor.cpp" line="529"/>
<location filename="../core_lib/src/interface/editor.cpp" line="550"/>
<source>Paste</source>
<translation>Aseta</translation>
</message>
<message>
<location filename="../core_lib/src/interface/editor.cpp" line="926"/>
<source>Remove frame</source>
<translation>Eemalda kaader</translation>
</message>
<message>
<location filename="../core_lib/src/interface/editor.cpp" line="771"/>
<location filename="../core_lib/src/interface/editor.cpp" line="797"/>
<source>Import Image</source>
<translation>Impordi pilt</translation>
</message>
</context>
<context>
<name>ErrorDialog</name>
<message>
<location filename="../app/ui/errordialog.ui" line="20"/>
<source>Dialog</source>
<translation>Dialoog</translation>
</message>
<message>
<location filename="../app/ui/errordialog.ui" line="55"/>
<source><h3>Title</h3></source>
<translation><h3>Pealkiri</h3></translation>
</message>
<message>
<location filename="../app/ui/errordialog.ui" line="68"/>
<source>Description</source>
<translation>Kirjeldus</translation>
</message>
</context>
<context>
<name>ExportImageDialog</name>
<message>
<location filename="../app/src/exportimagedialog.cpp" line="29"/>
<source>Export image sequence</source>
<translation>Ekspordi pildiseeria</translation>
</message>
<message>
<location filename="../app/src/exportimagedialog.cpp" line="33"/>
<source>Export image</source>
<translation>Ekspordi pilt</translation>
</message>
</context>
<context>
<name>ExportImageOptions</name>
<message>
<location filename="../app/ui/exportimageoptions.ui" line="23"/>
<source>Camera</source>
<translation>Kaamera</translation>
</message>
<message>
<location filename="../app/ui/exportimageoptions.ui" line="35"/>
<source>Resolution</source>
<translation>Resolutsioon</translation>
</message>
<message>
<location filename="../app/ui/exportimageoptions.ui" line="76"/>
<source>Format</source>
<translation>Vorming</translation>
</message>
<message>
<location filename="../app/ui/exportimageoptions.ui" line="83"/>
<source>PNG</source>
<translation>PNG</translation>
</message>
<message>
<location filename="../app/ui/exportimageoptions.ui" line="88"/>
<source>JPG</source>
<translation>JPG</translation>
</message>
<message>
<location filename="../app/ui/exportimageoptions.ui" line="93"/>
<source>BMP</source>
<translation>BMP</translation>
</message>
<message>
<location filename="../app/ui/exportimageoptions.ui" line="101"/>
<source>Transparency</source>
<translation>Läbipaistvus</translation>
</message>
<message>
<location filename="../app/ui/exportimageoptions.ui" line="111"/>
<source>Range</source>
<translation>Vahemik</translation>
</message>
<message>
<location filename="../app/ui/exportimageoptions.ui" line="157"/>
<source>The last frame you want to include in the exported movie</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/exportimageoptions.ui" line="160"/>
<source>End Frame</source>
<translation>Lõpukaader</translation>
</message>
<message>
<location filename="../app/ui/exportimageoptions.ui" line="179"/>
<source>The first frame you want to include in the exported movie</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/exportimageoptions.ui" line="182"/>
<source>Start Frame</source>
<translation>Alguse kaader</translation>
</message>
<message>
<location filename="../app/ui/exportimageoptions.ui" line="207"/>
<source><html><head/><body><p>End frame is set to last paintable keyframe (Useful when you only want to export to the last animated frame)</p></body></html></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/exportimageoptions.ui" line="213"/>
<source>To the end of sound clips</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ExportMovieDialog</name>
<message>
<location filename="../app/src/exportmoviedialog.cpp" line="29"/>
<source>Export Animated GIF</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/exportmoviedialog.cpp" line="31"/>
<source>Export Movie</source>
<translation>Ekspordi video</translation>
</message>
</context>
<context>
<name>ExportMovieOptions</name>
<message>
<location filename="../app/ui/exportmovieoptions.ui" line="29"/>
<source>Camera</source>
<translation>Kaamera</translation>
</message>
<message>
<location filename="../app/ui/exportmovieoptions.ui" line="41"/>
<source>Resolution</source>
<translation>Resolutsioon</translation>
</message>
<message>
<location filename="../app/ui/exportmovieoptions.ui" line="59"/>
<source>Width</source>
<translation>Laius</translation>
</message>
<message>
<location filename="../app/ui/exportmovieoptions.ui" line="88"/>
<source>Height</source>
<translation>Kõrgus</translation>
</message>
<message>
<location filename="../app/ui/exportmovieoptions.ui" line="108"/>
<source>Range</source>
<translation>Vahemik</translation>
</message>
<message>
<location filename="../app/ui/exportmovieoptions.ui" line="154"/>
<source>The last frame you want to include in the exported movie</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/exportmovieoptions.ui" line="157"/>
<source>End Frame</source>
<translation>Lõpukaader</translation>
</message>
<message>
<location filename="../app/ui/exportmovieoptions.ui" line="176"/>
<source>The first frame you want to include in the exported movie</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/exportmovieoptions.ui" line="179"/>
<source>Start Frame</source>
<translation>Alguse kaader</translation>
</message>
<message>
<location filename="../app/ui/exportmovieoptions.ui" line="204"/>
<source><html><head/><body><p>End frame is set to last paintable keyframe (Useful when you only want to export to the last animated frame)</p></body></html></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/exportmovieoptions.ui" line="210"/>
<source>To the end of sound clips</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/exportmovieoptions.ui" line="233"/>
<source>GIF and APNG only</source>
<translation>Ainult GIF ja APNG</translation>
</message>
<message>
<location filename="../app/ui/exportmovieoptions.ui" line="236"/>
<source>Loop</source>
<translation>Kordamine</translation>
</message>
</context>
<context>
<name>FileDialog</name>
<message>
<location filename="../app/src/filedialogex.cpp" line="132"/>
<source>Open animation</source>
<translation>Ava animatsioon</translation>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="133"/>
<source>Import image</source>
<translation>Impordi pilt</translation>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="134"/>
<source>Import image sequence</source>
<translation>Impordi pildiseeria</translation>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="135"/>
<source>Import Animated GIF</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="136"/>
<source>Import movie</source>
<translation>Impordi video</translation>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="137"/>
<source>Import sound</source>
<translation>Impordi heli</translation>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="138"/>
<source>Import palette</source>
<translation>Impordi palett</translation>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="148"/>
<source>Save animation</source>
<translation>Salvesta animatsioon</translation>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="149"/>
<source>Export image</source>
<translation>Ekspordi pilt</translation>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="150"/>
<source>Export image sequence</source>
<translation>Ekspordi pildiseeria</translation>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="151"/>
<source>Export Animated GIF</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="152"/>
<source>Export movie</source>
<translation>Ekspordi video</translation>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="153"/>
<source>Export sound</source>
<translation>Ekspordi heli</translation>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="154"/>
<source>Export palette</source>
<translation>Ekspordi palett</translation>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="167"/>
<location filename="../app/src/filedialogex.cpp" line="183"/>
<source>Animated GIF (*.gif)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="169"/>
<source>Sounds (*.wav *.mp3);;WAV (*.wav);;MP3 (*.mp3)</source>
<translation>Helifailid (*.wav *.mp3);;WAV (*.wav);;MP3 (*.mp3)</translation>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="170"/>
<location filename="../app/src/filedialogex.cpp" line="186"/>
<source>Pencil2D Palette (*.xml);; Gimp Palette (*.gpl)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="184"/>
<source>MP4 (*.mp4);; AVI (*.avi);; WebM (*.webm);; APNG (*.apng)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/filedialogex.cpp" line="226"/>
<source>MyAnimation.pclx</source>
<translation>MinuAnimatsioon.pclx</translation>
</message>
</context>
<context>
<name>FileManager</name>
<message>
<location filename="../core_lib/src/structure/filemanager.cpp" line="56"/>
<location filename="../core_lib/src/structure/filemanager.cpp" line="110"/>
<source>Could not open file</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/structure/filemanager.cpp" line="57"/>
<source>The file does not exist, so we are unable to open it. Please check to make sure the path is correct and that the file is accessible and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/structure/filemanager.cpp" line="111"/>
<source>This program does not have permission to read the file you have selected. Please check that you have read permissions for this file and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/structure/filemanager.cpp" line="230"/>
<location filename="../core_lib/src/structure/filemanager.cpp" line="238"/>
<location filename="../core_lib/src/structure/filemanager.cpp" line="245"/>
<source>Invalid Save Path</source>
<translation>Vigane salvestamise asukoht</translation>
</message>
<message>
<location filename="../core_lib/src/structure/filemanager.cpp" line="231"/>
<source>The path ("%1") points to a directory.</source>
<translation>Asukoht ("%1") viitab kaustale.</translation>
</message>
<message>
<location filename="../core_lib/src/structure/filemanager.cpp" line="239"/>
<source>The directory ("%1") does not exist.</source>
<translation>Kausta ("%1") pole olemas.</translation>
</message>
<message>
<location filename="../core_lib/src/structure/filemanager.cpp" line="246"/>
<source>The path ("%1") is not writable.</source>
<translation>Kaust ("%1") pole kirjutatav.</translation>
</message>
<message>
<location filename="../core_lib/src/structure/filemanager.cpp" line="282"/>
<location filename="../core_lib/src/structure/filemanager.cpp" line="291"/>
<source>Cannot Create Data Directory</source>
<translation>Andmete kausta loomine ebaõnnestus</translation>
</message>
<message>
<location filename="../core_lib/src/structure/filemanager.cpp" line="283"/>
<source>Failed to create directory "%1". Please make sure you have sufficient permissions.</source>
<translation>Kausta "%1" loomine ebaõnnestus. Palun veendu, et sul oleks piisavalt õiguseid.</translation>
</message>
<message>
<location filename="../core_lib/src/structure/filemanager.cpp" line="292"/>
<source>"%1" is a file. Please delete the file and try again.</source>
<translation>"%1" on fail. Palun kustuta see fail ja proovi siis uuesti.</translation>
</message>
<message>
<location filename="../core_lib/src/structure/filemanager.cpp" line="382"/>
<source>Miniz Error</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/structure/filemanager.cpp" line="399"/>
<source>Internal Error</source>
<translation>Sisemine tõrge</translation>
</message>
<message>
<location filename="../core_lib/src/structure/filemanager.cpp" line="383"/>
<location filename="../core_lib/src/structure/filemanager.cpp" line="400"/>
<source>An internal error occurred. Your file may not be saved successfully.</source>
<translation>Tekkis sisemine tõrge. Võimalik, et sinu faili ei salvestatud korrektselt.</translation>
</message>
</context>
<context>
<name>FilesPage</name>
<message>
<location filename="../app/ui/filespage.ui" line="17"/>
<source>Autosave documents</source>
<comment>Preference</comment>
<translation>Salvesta dokumendid automaatselt</translation>
</message>
<message>
<location filename="../app/ui/filespage.ui" line="23"/>
<source>Enable autosave</source>
<comment>Preference</comment>
<translation>Luba automaatne salvestamine</translation>
</message>
<message>
<location filename="../app/ui/filespage.ui" line="30"/>
<source>Number of modifications before autosaving:</source>
<comment>Preference</comment>
<translation>Muudatuste arv enne automaatset salvestamist:</translation>
</message>
</context>
<context>
<name>GeneralPage</name>
<message>
<location filename="../app/ui/generalpage.ui" line="50"/>
<source>Language</source>
<comment>GroupBox title in Preference</comment>
<translation>Keel</translation>
</message>
<message>
<location filename="../app/ui/generalpage.ui" line="71"/>
<source>Window opacity</source>
<comment>GroupBox title in Preference</comment>
<translation>Akna läbipaistvus</translation>
</message>
<message>
<location filename="../app/ui/generalpage.ui" line="130"/>
<source>Background</source>
<comment>GroupBox title in Preference</comment>
<translation>Taust</translation>
</message>
<message>
<location filename="../app/ui/generalpage.ui" line="100"/>
<source>Appearance</source>
<comment>GroupBox title in Preference</comment>
<translation>Välimus</translation>
</message>
<message>
<location filename="../app/ui/generalpage.ui" line="56"/>
<location filename="../app/ui/generalpage.ui" line="60"/>
<source>[System-Language]</source>
<comment>First item of the language list</comment>
<translation>[Süsteemi keel]</translation>
</message>
<message>
<location filename="../app/ui/generalpage.ui" line="174"/>
<source>Canvas</source>
<comment>GroupBox title in Preference</comment>
<translation>Lõuend</translation>
</message>
<message>
<location filename="../app/ui/generalpage.ui" line="203"/>
<source>Editing</source>
<comment>GroupBox title in Preference</comment>
<translation>Muutmine</translation>
</message>
<message>
<location filename="../app/ui/generalpage.ui" line="239"/>
<source>Grid</source>
<comment>groupBox title in Preference</comment>
<translation>Võrgustik</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="97"/>
<source>Czech</source>
<translation>Tšehhi</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="98"/>
<source>Danish</source>
<translation>Taani</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="100"/>
<source>English</source>
<translation>Inglise</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="99"/>
<source>German</source>
<translation>Saksa</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="101"/>
<source>Estonian</source>
<translation>Eesti</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="102"/>
<source>Spanish</source>
<translation>Hispaania</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="103"/>
<source>French</source>
<translation>Prantsuse</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="104"/>
<source>Hebrew</source>
<translation>eebrea</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="105"/>
<source>Hungarian</source>
<translation>Ungari</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="106"/>
<source>Indonesian</source>
<translation>Indoneesia</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="107"/>
<source>Italian</source>
<translation>Itaalia</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="108"/>
<source>Japanese</source>
<translation>Jaapani</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="109"/>
<source>Polish</source>
<translation>Poola</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="110"/>
<source>Portuguese - Portugal</source>
<translation>Portugali - Portugal</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="111"/>
<source>Portuguese - Brazil</source>
<translation>Portugali - Brasiilia</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="112"/>
<source>Russian</source>
<translation>Vene</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="113"/>
<source>Slovenian</source>
<translation>Sloveenia</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="114"/>
<source>Vietnamese</source>
<translation>Vietnami</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="115"/>
<source>Chinese - China</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="116"/>
<source>Chinese - Taiwan</source>
<translation>Hiina - Taivani</translation>
</message>
<message>
<location filename="../app/ui/generalpage.ui" line="77"/>
<source>Opacity</source>
<translation>Läbipasitmatus</translation>
</message>
<message>
<location filename="../app/ui/generalpage.ui" line="106"/>
<source>Shadows</source>
<translation>Varjud</translation>
</message>
<message>
<location filename="../app/ui/generalpage.ui" line="113"/>
<source>Tool Cursors</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/generalpage.ui" line="180"/>
<source>Antialiasing</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/generalpage.ui" line="120"/>
<source>Dotted Cursor</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/generalpage.ui" line="267"/>
<source>Enable Grid</source>
<translation>Võrgustiku kasutamine</translation>
</message>
<message>
<location filename="../app/ui/generalpage.ui" line="209"/>
<source>Vector curve smoothing</source>
<translation>Vektori kaare sujuvaks muutmine</translation>
</message>
<message>
<location filename="../app/ui/generalpage.ui" line="229"/>
<source>Tablet high-resolution position</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="212"/>
<source>Restart Required</source>
<translation>Nõutud on taaskäivitamine</translation>
</message>
<message>
<location filename="../app/src/preferencesdialog.cpp" line="213"/>
<source>The language change will take effect after a restart of Pencil2D</source>
<translation>Keele muudatus rakendatakse pärast Pencil2D taaskäivitamist</translation>
</message>
</context>
<context>
<name>ImportExportDialog</name>
<message>
<location filename="../app/ui/importexportdialog.ui" line="32"/>
<source>File</source>
<translation>Fail</translation>
</message>
<message>
<location filename="../app/ui/importexportdialog.ui" line="48"/>
<source>Browse...</source>
<translation>Sirvi...</translation>
</message>
<message>
<location filename="../app/ui/importexportdialog.ui" line="58"/>
<source>Options</source>
<translation>Valikud</translation>
</message>
</context>
<context>
<name>ImportImageSeqDialog</name>
<message>
<location filename="../app/src/importimageseqdialog.cpp" line="29"/>
<source>Import Animated GIF</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/importimageseqdialog.cpp" line="31"/>
<source>Import image sequence</source>
<translation>Impordi pildiseeria</translation>
</message>
</context>
<context>
<name>ImportImageSeqOptions</name>
<message>
<location filename="../app/ui/importimageseqoptions.ui" line="15"/>
<source>Import an image every # frame</source>
<translation>Impordi pilt iga # kaadri kohta</translation>
</message>
</context>
<context>
<name>Layer</name>
<message>
<location filename="../core_lib/src/structure/layer.cpp" line="38"/>
<source>Undefined Layer</source>
<translation>Määramata kiht</translation>
</message>
</context>
<context>
<name>LayerBitmap</name>
<message>
<location filename="../core_lib/src/structure/layerbitmap.cpp" line="29"/>
<source>Bitmap Layer</source>
<translation>Pildifaili kiht</translation>
</message>
</context>
<context>
<name>LayerCamera</name>
<message>
<location filename="../core_lib/src/structure/layercamera.cpp" line="79"/>
<source>Camera Layer</source>
<translation>Kaamera kiht</translation>
</message>
</context>
<context>
<name>LayerSound</name>
<message>
<location filename="../core_lib/src/structure/layersound.cpp" line="29"/>
<source>Sound Layer</source>
<translation>Helikiht</translation>
</message>
</context>
<context>
<name>LayerVector</name>
<message>
<location filename="../core_lib/src/structure/layervector.cpp" line="24"/>
<source>Vector Layer</source>
<translation>Vektorkiht</translation>
</message>
</context>
<context>
<name>MainWindow2</name>
<message>
<location filename="../app/ui/mainwindow2.ui" line="14"/>
<source>MainWindow</source>
<translation>PeamineAken</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="57"/>
<source>File</source>
<translation>Fail</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="61"/>
<source>Import</source>
<translation>Impordi</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="74"/>
<source>Export</source>
<translation>Ekspordi</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="97"/>
<source>Edit</source>
<translation>Muuda</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="101"/>
<source>Selection</source>
<translation>Valik</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="123"/>
<source>View</source>
<translation>Vaade</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="127"/>
<source>Onion Skin</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="152"/>
<source>Animation</source>
<translation>Animatsioon</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="172"/>
<location filename="../app/ui/mainwindow2.ui" line="800"/>
<source>Tools</source>
<translation>Tööriistad</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="190"/>
<source>Layer</source>
<translation>Kiht</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="201"/>
<location filename="../app/ui/mainwindow2.ui" line="731"/>
<source>Help</source>
<translation>Aviinfo</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="213"/>
<source>Windows</source>
<translation>Aken</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="232"/>
<source>New</source>
<translation>Uus</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="241"/>
<source>Open</source>
<translation>Ava</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="250"/>
<source>Save</source>
<translation>Salvesta</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="268"/>
<source>Exit</source>
<translation>Välju</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="273"/>
<location filename="../app/ui/mainwindow2.ui" line="301"/>
<source>Image Sequence...</source>
<translation>Pildiseeria...</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="278"/>
<location filename="../app/ui/mainwindow2.ui" line="296"/>
<source>Image...</source>
<translation>Pilt...</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="283"/>
<location filename="../app/ui/mainwindow2.ui" line="306"/>
<source>Movie...</source>
<translation>Video...</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="291"/>
<location filename="../app/ui/mainwindow2.ui" line="319"/>
<source>Palette...</source>
<translation>Palett...</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="314"/>
<source>Sound...</source>
<translation>Heli...</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="328"/>
<source>Undo</source>
<translation>Samm tagasi</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="340"/>
<source>Redo</source>
<translation>Korda</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="349"/>
<source>Cut</source>
<translation>Lõika</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="358"/>
<source>Copy</source>
<translation>Kopeeri</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="367"/>
<source>Paste</source>
<translation>Aseta</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="372"/>
<source>Crop</source>
<translation>Kärbi</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="377"/>
<source>Crop To Selection</source>
<translation>Kärbi valiku järgi</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="382"/>
<source>Select All</source>
<translation>Vali kõik</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="387"/>
<source>Deselect All</source>
<translation>Tühista valik</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="396"/>
<location filename="../app/ui/mainwindow2.ui" line="595"/>
<source>Clear Frame</source>
<translation>Tühjenda kaader</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="401"/>
<source>Preferences</source>
<translation>Eelistused</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="409"/>
<source>Reset Windows</source>
<translation>Nulli aknad</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="418"/>
<source>Zoom In</source>
<translation>Suumi sisse</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="427"/>
<source>Zoom Out</source>
<translation>Suumi välja</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="432"/>
<source>Rotate Clockwise</source>
<translation>Pööra päripäeva</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="437"/>
<source>Rotate AntiClosewise</source>
<translation>Pööra vastupäeva</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="442"/>
<source>Reset Zoom/Rotate</source>
<translation>Nulli suurendus/pööramine</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="451"/>
<source>Horizontal Flip</source>
<translation>Horisontaalne peegeldamine</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="460"/>
<source>Vertical Flip</source>
<translation>Vertikaalne peegeldamine</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="468"/>
<source>Preview</source>
<translation>Eelvaade</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="476"/>
<source>Grid</source>
<translation>Võrgustik</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="488"/>
<source>Previous</source>
<translation>Eelmine</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="491"/>
<source>Show previous onion skin</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="503"/>
<source>Next</source>
<translation>Järgmine</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="506"/>
<source>Show next onion skin</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="515"/>
<location filename="../app/src/mainwindow2.cpp" line="1278"/>
<source>Play</source>
<translation>Esita</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="527"/>
<source>Loop</source>
<translation>Kordamine</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="536"/>
<source>Next Frame</source>
<translation>Järgmine kaader</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="545"/>
<source>Previous Frame</source>
<translation>Eelmine kaader</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="550"/>
<source>Extend Frame</source>
<translation>Laienda kaadrit</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="559"/>
<source>Add Frame</source>
<translation>Lisa kaader</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="568"/>
<source>Duplicate Frame</source>
<translation>Tee kaadrist koopia</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="577"/>
<source>Remove Frame</source>
<translation>Eemalda kaader</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="586"/>
<source>Move</source>
<translation>Liigutamine</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="604"/>
<source>Select</source>
<translation>Valimine</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="613"/>
<source>Brush</source>
<translation>Pintsel</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="622"/>
<source>Polyline</source>
<translation>Hulknurk</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="631"/>
<source>Smudge</source>
<translation>Hägustamine</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="640"/>
<source>Pen</source>
<translation>Pliiats</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="649"/>
<source>Hand</source>
<translation>Käsi</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="658"/>
<source>Pencil</source>
<translation>Pliiats</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="667"/>
<source>Bucket</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="676"/>
<source>Eyedropper</source>
<translation>Värvi valija</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="685"/>
<source>Eraser</source>
<translation>Kustukumm</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="694"/>
<source>New Bitmap Layer</source>
<translation>Uus pildifaili kiht</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="703"/>
<source>New Vector Layer</source>
<translation>Uus vektorkiht</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="712"/>
<source>New Sound Layer</source>
<translation>Uus helikiht</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="721"/>
<source>New Camera Layer</source>
<translation>Uus kaamera kiht</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="726"/>
<source>Delete Current Layer</source>
<translation>Kustuta praegune kiht</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="736"/>
<source>About</source>
<translation>Info</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="741"/>
<location filename="../app/ui/mainwindow2.ui" line="744"/>
<source>Reset to default</source>
<translation>Taasta vaikeväärtused</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="781"/>
<source>MultiLayer Onion Skin</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="792"/>
<source>Range</source>
<translation>Vahemik</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="865"/>
<source>Pencil2D Website</source>
<translation>Pencil2D veebisait</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="870"/>
<source>Report a Bug</source>
<translation>Teavita veast</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="875"/>
<source>Quick Reference Guide</source>
<translation>Kiirjuhend</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="878"/>
<source>F1</source>
<translation>F1</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="883"/>
<location filename="../app/ui/mainwindow2.ui" line="888"/>
<source>Animated GIF...</source>
<translation>Animeeritud GIF...</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="754"/>
<location filename="../app/ui/mainwindow2.ui" line="757"/>
<source>Next KeyFrame</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="259"/>
<source>Save As...</source>
<translation>Salvesta kui ...</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="767"/>
<location filename="../app/ui/mainwindow2.ui" line="770"/>
<source>Previous KeyFrame</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="808"/>
<source>Timeline</source>
<translation>Ajatelg</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="816"/>
<source>Options</source>
<translation>Valikud</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="824"/>
<source>Color Wheel</source>
<translation>Värviratas</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="832"/>
<source>Color Palette</source>
<translation>Värvipalett</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="840"/>
<source>Display Options</source>
<translation>Vaate valikud</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="845"/>
<source>Flip X</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="850"/>
<source>Flip Y</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="855"/>
<source>Move Frame Forward</source>
<translation>Liigut akaadrit edasi</translation>
</message>
<message>
<location filename="../app/ui/mainwindow2.ui" line="860"/>
<source>Move Frame Backward</source>
<translation>Liiguta kaadrit tagasi</translation>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="146"/>
<source>color palette:<br>use <b>(C)</b><br>toggle at cursor</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="150"/>
<source>Color inspector</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="353"/>
<source>Lock Windows</source>
<translation>Lukusta aknad</translation>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="370"/>
<source>Open Recent</source>
<translation>Ava hiljutised</translation>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="404"/>
<source>
You have successfully cleared the list</source>
<translation>
Nimekiri on tühjendatud</translation>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="505"/>
<location filename="../app/src/mainwindow2.cpp" line="515"/>
<location filename="../app/src/mainwindow2.cpp" line="524"/>
<location filename="../app/src/mainwindow2.cpp" line="584"/>
<source>Could not open file</source>
<translation>Faili avamine ebaõnnestus</translation>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="506"/>
<source>The file you have selected is a directory, so we are unable to open it. If you are are trying to open a project that uses the old structure, please open the file ending with .pcl, not the data folder.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="516"/>
<source>The file you have selected does not exist, so we are unable to open it. Please check to make sure that you've entered the correct path and that the file is accessible and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="525"/>
<source>This program does not have permission to read the file you have selected. Please check that you have read permissions for this file and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="534"/>
<location filename="../app/src/mainwindow2.cpp" line="697"/>
<location filename="../app/src/mainwindow2.cpp" line="756"/>
<location filename="../app/src/mainwindow2.cpp" line="830"/>
<location filename="../app/src/mainwindow2.cpp" line="883"/>
<source>Warning</source>
<translation>Hoiatus</translation>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="535"/>
<source>This program does not currently have permission to write to the file you have selected. Please make sure you have write permission for this file before attempting to save it. Alternatively, you can use the Save As... menu option to save to a writable location.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="541"/>
<source>Opening document...</source>
<translation>Dokumendi avamine...</translation>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="541"/>
<location filename="../app/src/mainwindow2.cpp" line="619"/>
<location filename="../app/src/mainwindow2.cpp" line="783"/>
<location filename="../app/src/mainwindow2.cpp" line="858"/>
<source>Abort</source>
<translation>Info</translation>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="585"/>
<source>An unknown error occurred while trying to load the file and we are not able to load your file.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="619"/>
<source>Saving document...</source>
<translation>Dokumendi salvestamine...</translation>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="660"/>
<source><br><br>An error has occurred and your file may not have saved successfully.If you believe that this error is an issue with Pencil2D, please create a new issue at:<br><a href='https://github.com/pencil2d/pencil/issues'>https://github.com/pencil2d/pencil/issues</a><br>Please be sure to include the following details in your issue:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="698"/>
<source>This animation has been modified.
Do you want to save your changes?</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="726"/>
<source>The animation is not saved yet.
Do you want to save now?</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="727"/>
<source>Never ask again</source>
<comment>AutoSave reminder button</comment>
<translation>Ära küsi kunagi uuesti</translation>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="757"/>
<source>Unable to import image.<br><b>TIP:</b> Use Bitmap layer to import bitmaps.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="783"/>
<source>Importing image sequence...</source>
<translation>Pildiseeria importimine...</translation>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="831"/>
<location filename="../app/src/mainwindow2.cpp" line="884"/>
<source>was unable to import</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="858"/>
<source>Importing Animated GIF...</source>
<translation>Animeeritud GIF-i importimine...</translation>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="1103"/>
<location filename="../app/src/mainwindow2.cpp" line="1108"/>
<source>Undo</source>
<comment>Menu item text</comment>
<translation>Samm tagasi</translation>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="1123"/>
<source>Redo</source>
<comment>Menu item text</comment>
<translation>Korda</translation>
</message>
<message>
<location filename="../app/src/mainwindow2.cpp" line="1273"/>
<source>Stop</source>
<translation>Peata</translation>
</message>
</context>
<context>
<name>MoveTool</name>
<message>
<location filename="../core_lib/src/tool/movetool.cpp" line="367"/>
<source>Layer switch</source>
<comment>Windows title of layer switch pop-up.</comment>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/tool/movetool.cpp" line="368"/>
<source>You are about to switch layer, do you want to apply the transformation?</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>Object</name>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="549"/>
<source>Black</source>
<translation>Must</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="550"/>
<source>Red</source>
<translation>Punane</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="551"/>
<source>Dark Red</source>
<translation>Tumepunane</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="552"/>
<source>Orange</source>
<translation>Oraanž</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="553"/>
<source>Dark Orange</source>
<translation>Tumeoraanž</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="554"/>
<source>Yellow</source>
<translation>Kollane</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="555"/>
<source>Dark Yellow</source>
<translation>Tumekollane</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="556"/>
<source>Green</source>
<translation>Roheline</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="557"/>
<source>Dark Green</source>
<translation>Tumeroheline</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="558"/>
<source>Cyan</source>
<translation>Tsüaan</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="559"/>
<source>Dark Cyan</source>
<translation>Tume tsüaan</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="560"/>
<source>Blue</source>
<translation>Sinine</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="561"/>
<source>Dark Blue</source>
<translation>Tumesinine</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="562"/>
<source>White</source>
<translation>Valge</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="563"/>
<source>Very Light Grey</source>
<translation>Väga hele hall</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="564"/>
<source>Light Grey</source>
<translation>Helehall</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="565"/>
<source>Grey</source>
<translation>Hall</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="566"/>
<source>Dark Grey</source>
<translation>Tumehall</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="567"/>
<source>Light Skin</source>
<translation>Hele nahk</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="568"/>
<source>Light Skin - shade</source>
<translation>Hele nahk - varjuga</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="569"/>
<source>Skin</source>
<translation>Nahk</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="570"/>
<source>Skin - shade</source>
<translation>Nahk - varjuga</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="571"/>
<source>Dark Skin</source>
<translation>Tume nahk</translation>
</message>
<message>
<location filename="../core_lib/src/structure/object.cpp" line="572"/>
<source>Dark Skin - shade</source>
<translation>Tume nahk - varjuga</translation>
</message>
</context>
<context>
<name>PencilApplication</name>
<message>
<location filename="../app/src/main.cpp" line="73"/>
<source>Pencil2D is an animation/drawing software for Mac OS X, Windows, and Linux. It lets you create traditional hand-drawn animation (cartoon) using both bitmap and vector graphics.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/main.cpp" line="76"/>
<source>Path to the input pencil file.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/main.cpp" line="79"/>
<location filename="../app/src/main.cpp" line="85"/>
<source>Render the file to <output_path></source>
<translation>Renderda fail kausta <output_path></translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="80"/>
<location filename="../app/src/main.cpp" line="86"/>
<source>output_path</source>
<translation>väljundi_kaust</translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="93"/>
<source>Name of the camera layer to use</source>
<translation>Kasutatava kaamera kihi nimi</translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="94"/>
<source>layer_name</source>
<translation>kihi_nimi</translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="98"/>
<source>Width of the output frames</source>
<translation>Väljundikaadrite laius</translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="99"/>
<location filename="../app/src/main.cpp" line="104"/>
<source>integer</source>
<translation>täisarv</translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="103"/>
<source>Height of the output frames</source>
<translation>Väljundkaadrite kõrgus</translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="108"/>
<source>The first frame you want to include in the exported movie</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/main.cpp" line="109"/>
<location filename="../app/src/main.cpp" line="116"/>
<source>frame</source>
<translation>kaader</translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="113"/>
<source>The last frame you want to include in the exported movie. Can also be last or last-sound to automatically use the last frame containing animation or sound, respectively</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/main.cpp" line="120"/>
<source>Render transparency when possible</source>
<translation>Kui võimalik, siis säilita läbipaistvus</translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="139"/>
<source>Warning: width value %1 is not an integer, ignoring.</source>
<translation>Hoiatus: %1 laiuse väärtus pole täisarv. Seda ignoreeritakse.</translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="149"/>
<source>Warning: height value %1 is not an integer, ignoring.</source>
<translation>Hoiatus: %1 kõrguse väärtus pole täisarv. Seda ignoreeritakse.</translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="159"/>
<source>Warning: start value %1 is not an integer, ignoring.</source>
<translation>Hoiatus: %1 alguse väärtus pole täisarv. Seda ignoreeritakse.</translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="164"/>
<source>Warning: start value must be at least 1, ignoring.</source>
<translation>Hoiatus: alguse väärtus peab olema vähemalt 1. Seda ignoreeritakse.</translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="184"/>
<source>Warning: end value %1 is not an integer, last or last-sound, ignoring.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/main.cpp" line="190"/>
<source>Warning: end value %1 is smaller than start value %2, ignoring.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/main.cpp" line="201"/>
<source>Error: No input file specified.</source>
<translation>Tõrge: Sisendfaili pole määratud.</translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="208"/>
<source>Error: the input file at '%1' does not exist</source>
<comment>Command line error</comment>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/main.cpp" line="213"/>
<source>Error: the input path '%1' is not a file</source>
<comment>Command line error</comment>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/main.cpp" line="241"/>
<source>Warning: the specified camera layer %1 was not found, ignoring.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/main.cpp" line="272"/>
<source>Warning: Output format is not specified or unsupported. Using PNG.</source>
<comment>Command line warning</comment>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/main.cpp" line="292"/>
<source>Warning: Transparency is not currently supported in movie files</source>
<comment>Command line warning</comment>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/main.cpp" line="294"/>
<source>Exporting movie...</source>
<comment>Command line task progress</comment>
<translation>Video eksportimine...</translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="296"/>
<location filename="../app/src/main.cpp" line="301"/>
<source>Done.</source>
<comment>Command line task done</comment>
<translation>Valmis.</translation>
</message>
<message>
<location filename="../app/src/main.cpp" line="299"/>
<source>Exporting image sequence...</source>
<comment>Command line task progress</comment>
<translation>Pildiseeria eksportimine...</translation>
</message>
</context>
<context>
<name>PreferencesDialog</name>
<message>
<location filename="../app/ui/preferencesdialog.ui" line="20"/>
<source>Preferences</source>
<translation>Eelistused</translation>
</message>
<message>
<location filename="../app/ui/preferencesdialog.ui" line="65"/>
<source>General</source>
<translation>Üldine</translation>
</message>
<message>
<location filename="../app/ui/preferencesdialog.ui" line="80"/>
<source>Files</source>
<translation>Failid</translation>
</message>
<message>
<location filename="../app/ui/preferencesdialog.ui" line="95"/>
<source>Timeline</source>
<translation>Ajatelg</translation>
</message>
<message>
<location filename="../app/ui/preferencesdialog.ui" line="110"/>
<source>Tools</source>
<translation>Tööriistad</translation>
</message>
<message>
<location filename="../app/ui/preferencesdialog.ui" line="125"/>
<source>Shortcuts</source>
<translation>Otseteed</translation>
</message>
</context>
<context>
<name>QApplication</name>
<message>
<location filename="../core_lib/src/movieexporter.cpp" line="97"/>
<source>Checking environment...</source>
<translation>Keskkonna kontrollimine...</translation>
</message>
<message>
<location filename="../core_lib/src/movieexporter.cpp" line="148"/>
<source>Done</source>
<translation>Valmis</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../core_lib/src/util/pencildef.h" line="26"/>
<source>AVI (*.avi);;MPEG(*.mpg);;MOV(*.mov);;MP4(*.mp4);;SWF(*.swf);;FLV(*.flv);;WMV(*.wmv)</source>
<translation>AVI (*.avi);;MPEG(*.mpg);;MOV(*.mov);;MP4(*.mp4);;SWF(*.swf);;FLV(*.flv);;WMV(*.wmv)</translation>
</message>
<message>
<location filename="../core_lib/src/util/pencildef.h" line="29"/>
<source>Images (*.png *.jpg *.jpeg *.bmp);;PNG (*.png);;JPG(*.jpg *.jpeg);;BMP(*.bmp)</source>
<translation>PIldid (*.png *.jpg *.jpeg *.bmp);;PNG (*.png);;JPG(*.jpg *.jpeg);;BMP(*.bmp)</translation>
</message>
<message>
<location filename="../core_lib/src/util/pencildef.h" line="32"/>
<source>Images (*.png *.jpg *.jpeg *.bmp);;PNG (*.png);;JPG(*.jpg *.jpeg);;BMP(*.bmp);</source>
<translation>PIldid (*.png *.jpg *.jpeg *.bmp);;PNG (*.png);;JPG(*.jpg *.jpeg);;BMP(*.bmp);</translation>
</message>
<message>
<location filename="../core_lib/src/util/pencilerror.cpp" line="98"/>
<source>Everything ok.</source>
<translation>Kõik on OK.</translation>
</message>
<message>
<location filename="../core_lib/src/util/pencilerror.cpp" line="99"/>
<source>Ooops, Something went wrong.</source>
<translation>Oih, midagi läks valesti.</translation>
</message>
<message>
<location filename="../core_lib/src/util/pencilerror.cpp" line="100"/>
<source>File doesn't exist.</source>
<translation>Faili pole olemas.</translation>
</message>
<message>
<location filename="../core_lib/src/util/pencilerror.cpp" line="101"/>
<source>Cannot open file.</source>
<translation>Faili ei saa avada.</translation>
</message>
<message>
<location filename="../core_lib/src/util/pencilerror.cpp" line="102"/>
<source>The file is not a valid xml document.</source>
<translation>Fail pole korrektne XML dokument.</translation>
</message>
<message>
<location filename="../core_lib/src/util/pencilerror.cpp" line="103"/>
<source>The file is not valid pencil document.</source>
<translation>Fail pole korrektne pencil dokument.</translation>
</message>
<message>
<location filename="../core_lib/src/util/fileformat.h" line="29"/>
<source>All Pencil Files PCLX & PCL(*.pclx *.pcl);;Pencil Animation File PCLX(*.pclx);;Old Pencil Animation File PCL(*.pcl);;Any files (*)</source>
<translation>Kõik Pencil failid PCLX & PCL(*.pclx *.pcl);;Pencil animatsioonifail PCLX(*.pclx);;Vana Pencil animatsioonifail PCL(*.pcl);;Any files (*)</translation>
</message>
<message>
<location filename="../core_lib/src/util/fileformat.h" line="30"/>
<source>Pencil Animation File PCLX(*.pclx);;Old Pencil Animation File PCL(*.pcl)</source>
<translation>Pencil animatsiooni fail PCLX(*.pclx);;Vana Pencil animatsiooni fail PCL(*.pcl)</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="282"/>
<source>Vivid Pink</source>
<translation>Erk roosa</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="283"/>
<source>Strong Pink</source>
<translation>Tugev roosa</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="284"/>
<source>Deep Pink</source>
<translation>Sügav roosa</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="285"/>
<source>Light Pink</source>
<translation>Heleroosa</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="286"/>
<source>Moderate Pink</source>
<translation>Keskmine roosa</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="287"/>
<source>Dark Pink</source>
<translation>Tumeroosa</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="288"/>
<source>Pale Pink</source>
<translation>Kahvatu roosa</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="289"/>
<source>Grayish Pink</source>
<translation>Hallikasroosa</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="290"/>
<source>Pinkish White</source>
<translation>Roosakasvalge</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="291"/>
<source>Pinkish Gray</source>
<translation>Roosakashall</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="292"/>
<source>Vivid Red</source>
<translation>Erk punane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="293"/>
<source>Strong Red</source>
<translation>Tugev punane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="294"/>
<source>Deep Red</source>
<translation>Sügav punane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="295"/>
<source>Very Deep Red</source>
<translation>Väga sügav punane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="296"/>
<source>Moderate Red</source>
<translation>Keskmine punane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="297"/>
<source>Dark Red</source>
<translation>Tumepunane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="298"/>
<source>Very Dark Red</source>
<translation>Väga tume punane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="299"/>
<source>Light Grayish Red</source>
<translation>Hele hallikaspunane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="300"/>
<source>Grayish Red</source>
<translation>Hallikas-punane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="301"/>
<source>Dark Grayish Red</source>
<translation>Tume hallikaspunane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="302"/>
<source>Blackish Red</source>
<translation>Mustjaspunane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="303"/>
<source>Reddish Gray</source>
<translation>Punakas-hall</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="304"/>
<source>Dark Reddish Gray</source>
<translation>Tume punakashall</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="305"/>
<source>Reddish Black</source>
<translation>Punakasmust</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="306"/>
<source>Vivid Yellowish Pink</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="307"/>
<source>Strong Yellowish Pink</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="308"/>
<source>Deep Yellowish Pink</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="309"/>
<source>Light Yellowish Pink</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="310"/>
<source>Moderate Yellowish Pink</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="311"/>
<source>Dark Yellowish Pink</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="312"/>
<source>Pale Yellowish Pink</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="313"/>
<source>Grayish Yellowish Pink</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="314"/>
<source>Brownish Pink</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="315"/>
<source>Vivid Reddish Orange</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="316"/>
<source>Strong Reddish Orange</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="317"/>
<source>Deep Reddish Orange</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="318"/>
<source>Moderate Reddish Orange</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="319"/>
<source>Dark Reddish Orange</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="320"/>
<source>Grayish Reddish Orange</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="321"/>
<source>Strong Reddish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="322"/>
<source>Deep Reddish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="323"/>
<source>Light Reddish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="324"/>
<source>Moderate Reddish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="325"/>
<source>Dark Reddish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="326"/>
<source>Light Grayish Reddish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="327"/>
<source>Grayish Reddish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="328"/>
<source>Dark Grayish Reddish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="329"/>
<source>Vivid Orange</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="330"/>
<source>Brilliant Orange</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="331"/>
<source>Strong Orange</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="332"/>
<source>Deep Orange</source>
<translation>Sügav oraanž</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="333"/>
<source>Light Orange</source>
<translation>Heleoraanž</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="334"/>
<source>Moderate Orange</source>
<translation>Keskmine oraanž</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="335"/>
<source>Brownish Orange</source>
<translation>Pruunikas oraanž</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="336"/>
<source>Strong Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="337"/>
<source>Deep Brown</source>
<translation>Sügav pruun</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="338"/>
<source>Light Brown</source>
<translation>Helepruun</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="339"/>
<source>Moderate Brown</source>
<translation>Keskmine pruun</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="340"/>
<source>Dark Brown</source>
<translation>Tumepruun</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="341"/>
<source>Light Grayish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="342"/>
<source>Grayish Brown</source>
<translation>Hallikaspruun</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="343"/>
<source>Dark Grayish Brown</source>
<translation>Tume hallikaspruun</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="344"/>
<source>Light Brownish Gray</source>
<translation>Hele pruunikashall</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="345"/>
<source>Brownish Gray</source>
<translation>Pruunikashall</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="346"/>
<source>Brownish Black</source>
<translation>Pruunikasmust</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="347"/>
<source>Vivid Orange Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="348"/>
<source>Brilliant Orange Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="349"/>
<source>Strong Orange Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="350"/>
<source>Deep Orange Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="351"/>
<source>Light Orange Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="352"/>
<source>Moderate Orange Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="353"/>
<source>Dark Orange Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="354"/>
<source>Pale Orange Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="355"/>
<source>Strong Yellowish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="356"/>
<source>Deep Yellowish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="357"/>
<source>Light Yellowish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="358"/>
<source>Moderate Yellowish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="359"/>
<source>Dark Yellowish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="360"/>
<source>Light Grayish Yellowish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="361"/>
<source>Grayish Yellowish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="362"/>
<source>Dark Grayish Yellowish Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="363"/>
<source>Vivid Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="364"/>
<source>Brilliant Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="365"/>
<source>Strong Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="366"/>
<source>Deep Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="367"/>
<source>Light Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="368"/>
<source>Moderate Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="369"/>
<source>Dark Yellow</source>
<translation>Tumekollane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="370"/>
<source>Pale Yellow</source>
<translation>Kahvatu kollane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="371"/>
<source>Grayish Yellow</source>
<translation>Hallikaskollane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="372"/>
<source>Dark Grayish Yellow</source>
<translation>Tume hallikaskollane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="373"/>
<source>Yellowish White</source>
<translation>Kollakasvalge</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="374"/>
<source>Yellowish Gray</source>
<translation>ollakashall</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="375"/>
<source>Light Olive Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="376"/>
<source>Moderate Olive Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="377"/>
<source>Dark Olive Brown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="378"/>
<source>Vivid Greenish Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="379"/>
<source>Brilliant Greenish Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="380"/>
<source>Strong Greenish Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="381"/>
<source>Deep Greenish Yellow</source>
<translation>Sügav rohekaskollane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="382"/>
<source>Light Greenish Yellow</source>
<translation>Hele rohekaskollane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="383"/>
<source>Moderate Greenish Yellow</source>
<translation>Keskmine rohekaskollane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="384"/>
<source>Dark Greenish Yellow</source>
<translation>Tume rohekaskollane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="385"/>
<source>Pale Greenish Yellow</source>
<translation>Kahvatu rohekaskollane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="386"/>
<source>Grayish Greenish Yellow</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="387"/>
<source>Light Olive</source>
<translation>Hele oliiv</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="388"/>
<source>Moderate Olive</source>
<translation>Keskmine oliiv</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="389"/>
<source>Dark Olive</source>
<translation>Tume oliiv</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="390"/>
<source>Light Grayish Olive</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="391"/>
<source>Grayish Olive</source>
<translation>Hallikas oliiv</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="392"/>
<source>Dark Grayish Olive</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="393"/>
<source>Light Olive Gray</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="394"/>
<source>Olive Gray</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="395"/>
<source>Olive Black</source>
<translation>Oliivimust</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="396"/>
<source>Vivid Yellow Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="397"/>
<source>Brilliant Yellow Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="398"/>
<source>Strong Yellow Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="399"/>
<source>Deep Yellow Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="400"/>
<source>Light Yellow Green</source>
<translation>Hele kollakasroheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="401"/>
<source>Moderate Yellow Green</source>
<translation>Keskmine kollakasroheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="402"/>
<source>Pale Yellow Green</source>
<translation>Kahvatu kollakasroheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="403"/>
<source>Grayish Yellow Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="404"/>
<source>Strong Olive Green</source>
<translation>Tugev oliiviroheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="405"/>
<source>Deep Olive Green</source>
<translation>Sügav oliiviroheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="406"/>
<source>Moderate Olive Green</source>
<translation>Keskmine oliiviroheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="407"/>
<source>Dark Olive Green</source>
<translation>Tume oliiviroheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="408"/>
<source>Grayish Olive Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="409"/>
<source>Dark Grayish Olive Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="410"/>
<source>Vivid Yellowish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="411"/>
<source>Brilliant Yellowish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="412"/>
<source>Strong Yellowish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="413"/>
<source>Deep Yellowish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="414"/>
<source>Very Deep Yellowish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="415"/>
<source>Very Light Yellowish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="416"/>
<source>Light Yellowish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="417"/>
<source>Moderate Yellowish Green</source>
<translation>Keskmine kollakasroheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="418"/>
<source>Dark Yellowish Green</source>
<translation>Tume kollakasroheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="419"/>
<source>Very Dark Yellowish Green</source>
<translation>Väga tume kollakasroheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="420"/>
<source>Vivid Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="421"/>
<source>Brilliant Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="422"/>
<source>Strong Green</source>
<translation>Tugev roheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="423"/>
<source>Deep Green</source>
<translation>Sügav roheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="424"/>
<source>Very Light Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="425"/>
<source>Light Green</source>
<translation>Heleroheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="426"/>
<source>Moderate Green</source>
<translation>Keskmine roheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="427"/>
<source>Dark Green</source>
<translation>Tumeroheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="428"/>
<source>Very Dark Green</source>
<translation>Väga tume roheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="429"/>
<source>Very Pale Green</source>
<translation>Väga kahvatu roheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="430"/>
<source>Pale Green</source>
<translation>Kahvatu roheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="431"/>
<source>Grayish Green</source>
<translation>Hallikasroheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="432"/>
<source>Dark Grayish Green</source>
<translation>Tume hallikasroheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="433"/>
<source>Blackish Green</source>
<translation>Mustjasroheline</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="434"/>
<source>Greenish White</source>
<translation>Rohekasvalge</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="435"/>
<source>Light Greenish Gray</source>
<translation>Hele rohekasvalge</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="436"/>
<source>Greenish Gray</source>
<translation>Rohekashall</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="437"/>
<source>Dark Greenish Gray</source>
<translation>Tume rohekashall</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="438"/>
<source>Greenish Black</source>
<translation>Rohekasmust</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="439"/>
<source>Vivid Bluish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="440"/>
<source>Brilliant Bluish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="441"/>
<source>Strong Bluish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="442"/>
<source>Deep Bluish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="443"/>
<source>Very Light Bluish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="444"/>
<source>Light Bluish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="445"/>
<source>Moderate Bluish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="446"/>
<source>Dark Bluish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="447"/>
<source>Very Dark Bluish Green</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="448"/>
<source>Vivid Greenish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="449"/>
<source>Brilliant Greenish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="450"/>
<source>Strong Greenish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="451"/>
<source>Deep Greenish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="452"/>
<source>Very Light Greenish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="453"/>
<source>Light Greenish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="454"/>
<source>Moderate Greenish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="455"/>
<source>Dark Greenish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="456"/>
<source>Very Dark Greenish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="457"/>
<source>Vivid Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="458"/>
<source>Brilliant Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="459"/>
<source>Strong Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="460"/>
<source>Deep Blue</source>
<translation>Sügav sinine</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="461"/>
<source>Very Light Blue</source>
<translation>Väga hele sinine</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="462"/>
<source>Light Blue</source>
<translation>Helesinine</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="463"/>
<source>Moderate Blue</source>
<translation>Keskmine sinine</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="464"/>
<source>Dark Blue</source>
<translation>Tumesinine</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="465"/>
<source>Very Pale Blue</source>
<translation>Väga hakvatu sinine</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="466"/>
<source>Pale Blue</source>
<translation>Kahvatu sinine</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="467"/>
<source>Grayish Blue</source>
<translation>Hallikassinine</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="468"/>
<source>Dark Grayish Blue</source>
<translation>Tume hallikassinine</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="469"/>
<source>Blackish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="470"/>
<source>Bluish White</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="471"/>
<source>Light Bluish Gray</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="472"/>
<source>Bluish Gray</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="473"/>
<source>Dark Bluish Gray</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="474"/>
<source>Bluish Black</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="475"/>
<source>Vivid Purplish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="476"/>
<source>Brilliant Purplish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="477"/>
<source>Strong Purplish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="478"/>
<source>Deep Purplish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="479"/>
<source>Very Light Purplish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="480"/>
<source>Light Purplish Blue</source>
<translation>Hele lillakassinine</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="481"/>
<source>Moderate Purplish Blue</source>
<translation>Keskmine lillakassinine</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="482"/>
<source>Dark Purplish Blue</source>
<translation>Tume lillakassinine</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="483"/>
<source>Very Pale Purplish Blue</source>
<translation>Väga kahvatu lillakassinine</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="484"/>
<source>Pale Purplish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="485"/>
<source>Grayish Purplish Blue</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="486"/>
<source>Vivid Violet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="487"/>
<source>Brilliant Violet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="488"/>
<source>Strong Violet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="489"/>
<source>Deep Violet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="490"/>
<source>Very Light Violet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="491"/>
<source>Light Violet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="492"/>
<source>Moderate Violet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="493"/>
<source>Dark Violet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="494"/>
<source>Very Pale Violet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="495"/>
<source>Pale Violet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="496"/>
<source>Grayish Violet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="497"/>
<source>Vivid Purple</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="498"/>
<source>Brilliant Purple</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="499"/>
<source>Strong Purple</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="500"/>
<source>Deep Purple</source>
<translation>Sügav lilla</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="501"/>
<source>Very Deep Purple</source>
<translation>Väga sügav lilla</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="502"/>
<source>Very Light Purple</source>
<translation>Väga hele lilla</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="503"/>
<source>Light Purple</source>
<translation>Helelilla</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="504"/>
<source>Moderate Purple</source>
<translation>Keskmine lilla</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="505"/>
<source>Dark Purple</source>
<translation>Tumelilla</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="506"/>
<source>Very Dark Purple</source>
<translation>Väga tume lilla</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="507"/>
<source>Very Pale Purple</source>
<translation>Väga kahvatu lilla</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="508"/>
<source>Pale Purple</source>
<translation>Kahvatu lilla</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="509"/>
<source>Grayish Purple</source>
<translation>Hallikaslilla</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="510"/>
<source>Dark Grayish Purple</source>
<translation>Tume hallikaslilla</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="511"/>
<source>Blackish Purple</source>
<translation>Mustjaslilla</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="512"/>
<source>Purplish White</source>
<translation>Lillakasvalge</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="513"/>
<source>Light Purplish Gray</source>
<translation>Hele lillakashall</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="514"/>
<source>Purplish Gray</source>
<translation>Lillakashall</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="515"/>
<source>Dark Purplish Gray</source>
<translation>Tume lillakashall</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="516"/>
<source>Purplish Black</source>
<translation>Lillakasmust</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="517"/>
<source>Vivid Reddish Purple</source>
<translation>Erk punakaslilla</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="518"/>
<source>Strong Reddish Purple</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="519"/>
<source>Deep Reddish Purple</source>
<translation>Sügav punakaslilla</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="520"/>
<source>Very Deep Reddish Purple</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="521"/>
<source>Light Reddish Purple</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="522"/>
<source>Moderate Reddish Purple</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="523"/>
<source>Dark Reddish Purple</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="524"/>
<source>Very Dark Reddish Purple</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="525"/>
<source>Pale Reddish Purple</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="526"/>
<source>Grayish Reddish Purple</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="527"/>
<source>Brilliant Purplish Pink</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="528"/>
<source>Strong Purplish Pink</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="529"/>
<source>Deep Purplish Pink</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="530"/>
<source>Light Purplish Pink</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="531"/>
<source>Moderate Purplish Pink</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="532"/>
<source>Dark Purplish Pink</source>
<translation>Tume lillakasroosa</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="533"/>
<source>Pale Purplish Pink</source>
<translation>Hele lillakasroosa</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="534"/>
<source>Grayish Purplish Pink</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="535"/>
<source>Vivid Purplish Red</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="536"/>
<source>Strong Purplish Red</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="537"/>
<source>Deep Purplish Red</source>
<translation>Sügav lillakaspunane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="538"/>
<source>Very Deep Purplish Red</source>
<translation>Väga sügav lillakaspunan</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="539"/>
<source>Moderate Purplish Red</source>
<translation>Keskmine lillakaspunane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="540"/>
<source>Dark Purplish Red</source>
<translation>Tume lillakaspunane</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="541"/>
<source>Very Dark Purplish Red</source>
<translation>Väga tume lillakaspunan</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="542"/>
<source>Light Grayish Purplish Red</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="543"/>
<source>Grayish Purplish Red</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="544"/>
<source>White</source>
<translation>Valge</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="545"/>
<source>Light Gray</source>
<translation>Helehall</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="546"/>
<source>Medium Gray</source>
<translation>Keskmine hall</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="547"/>
<source>Dark Gray</source>
<translation>Tumehall</translation>
</message>
<message>
<location filename="../app/src/colordictionary.h" line="548"/>
<source>Black</source>
<translation>Must</translation>
</message>
<message>
<location filename="../core_lib/src/structure/filemanager.cpp" line="29"/>
<source>Could not open file</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/structure/filemanager.cpp" line="30"/>
<source>There was an error processing your file. This usually means that your project has been at least partially corrupted. You can try again with a newer version of Pencil2D, or you can try to use a backup file if you have one. If you contact us through one of our offical channels we may be able to help you. For reporting issues, the best places to reach us are:</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RecentFileMenu</name>
<message>
<location filename="../core_lib/src/interface/recentfilemenu.h" line="38"/>
<source>Open Recent</source>
<translation>Ava hiljutised</translation>
</message>
<message>
<location filename="../core_lib/src/interface/recentfilemenu.cpp" line="31"/>
<source>Clear</source>
<translation>Tühjenda</translation>
</message>
</context>
<context>
<name>ScribbleArea</name>
<message>
<location filename="../core_lib/src/interface/scribblearea.cpp" line="525"/>
<source>Warning</source>
<translation>Hoiatus</translation>
</message>
<message>
<location filename="../core_lib/src/interface/scribblearea.cpp" line="526"/>
<source>You are drawing on a hidden layer! Please select another layer (or make the current layer visible).</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/interface/scribblearea.cpp" line="1929"/>
<source>Delete Selection</source>
<comment>Undo Step: clear the selection area.</comment>
<translation>Kustuta valik</translation>
</message>
<message>
<location filename="../core_lib/src/interface/scribblearea.cpp" line="1945"/>
<location filename="../core_lib/src/interface/scribblearea.cpp" line="1953"/>
<source>Clear Image</source>
<comment>Undo step text</comment>
<translation>Eemalda pilt</translation>
</message>
<message>
<location filename="../core_lib/src/interface/scribblearea.cpp" line="1980"/>
<source>There is a gap in your drawing (or maybe you have zoomed too much).</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/interface/scribblearea.cpp" line="1981"/>
<source>Sorry! This doesn't always work.Please try again (zoom a bit, click at another location... )<br>if it doesn't work, zoom a bit and check that your paths are connected by pressing F1.).</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/interface/scribblearea.cpp" line="1985"/>
<source>Out of bound.</source>
<translation>Piiridest väljas.</translation>
</message>
<message>
<location filename="../core_lib/src/interface/scribblearea.cpp" line="1986"/>
<source>Could not find a closed path.</source>
<translation>Suletud asukohta ei leitud.</translation>
</message>
<message>
<location filename="../core_lib/src/interface/scribblearea.cpp" line="1987"/>
<source>Could not find the root index.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/interface/scribblearea.cpp" line="1988"/>
<source>%1<br><br>Error: %2</source>
<translation>%1<br><br>Viga: %2</translation>
</message>
<message>
<location filename="../core_lib/src/interface/scribblearea.cpp" line="1988"/>
<source>Flood fill error</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ShortcutsPage</name>
<message>
<location filename="../app/ui/shortcutspage.ui" line="14"/>
<source>Form</source>
<translation>Vorm</translation>
</message>
<message>
<location filename="../app/ui/shortcutspage.ui" line="47"/>
<source>Action:</source>
<translation>Tegevus:</translation>
</message>
<message>
<location filename="../app/ui/shortcutspage.ui" line="54"/>
<source>None</source>
<translation>Pole</translation>
</message>
<message>
<location filename="../app/ui/shortcutspage.ui" line="61"/>
<source>Shortcuts:</source>
<translation>Otseteed:</translation>
</message>
<message>
<location filename="../app/ui/shortcutspage.ui" line="73"/>
<source>clear</source>
<translation>tühjenda</translation>
</message>
<message>
<location filename="../app/ui/shortcutspage.ui" line="100"/>
<source>Restore Default Shortcuts</source>
<translation>Taasta vaikimisi otseteed</translation>
</message>
<message>
<location filename="../app/src/shortcutspage.cpp" line="92"/>
<source>Shortcut Conflict!</source>
<translation>Otsetee konflikt!</translation>
</message>
<message>
<location filename="../app/src/shortcutspage.cpp" line="93"/>
<source>%1 is already used, overwrite?</source>
<translation>%1 on juba kasutusel. Kas kirjutan üle?</translation>
</message>
</context>
<context>
<name>TimeControls</name>
<message>
<location filename="../core_lib/src/interface/timecontrols.cpp" line="64"/>
<source>Range</source>
<translation>Vahemik</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timecontrols.cpp" line="47"/>
<source>Frames per second</source>
<translation>Kaadrit sekundis</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timecontrols.cpp" line="54"/>
<source>Start of playback loop</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/interface/timecontrols.cpp" line="61"/>
<source>End of playback loop</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/interface/timecontrols.cpp" line="66"/>
<source>Playback range</source>
<translation>Esitamise vahemik</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timecontrols.cpp" line="86"/>
<source>Play</source>
<translation>Esita</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timecontrols.cpp" line="87"/>
<source>Loop</source>
<translation>Kordamine</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timecontrols.cpp" line="88"/>
<source>Sound on/off</source>
<translation>Heli sees või väljas</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timecontrols.cpp" line="89"/>
<source>End</source>
<translation>Lõpp</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timecontrols.cpp" line="90"/>
<location filename="../core_lib/src/interface/timecontrols.cpp" line="192"/>
<source>Start</source>
<translation>Algus</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timecontrols.cpp" line="187"/>
<source>Stop</source>
<translation>Peata</translation>
</message>
</context>
<context>
<name>TimeLine</name>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="45"/>
<source>Timeline</source>
<translation>Ajatelg</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="70"/>
<source>Layers:</source>
<translation>Kihid:</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="75"/>
<source>Add Layer</source>
<translation>Lisa kiht</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="80"/>
<source>Remove Layer</source>
<translation>Eemalda kiht</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="93"/>
<source>New Bitmap Layer</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="94"/>
<source>New Vector Layer</source>
<translation>Uus vektorkiht</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="95"/>
<source>New Sound Layer</source>
<translation>Uus helikiht</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="96"/>
<source>New Camera Layer</source>
<translation>Uus kaamerakiht</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="98"/>
<source>&Layer</source>
<comment>Timeline add-layer menu</comment>
<translation>&Kiht</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="116"/>
<source>Keys:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="121"/>
<source>Add Frame</source>
<translation>Lisa kaader</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="126"/>
<source>Remove Frame</source>
<translation>Eemalda kaader</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="131"/>
<source>Duplicate Frame</source>
<translation>Tee kaadrist koopia</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="134"/>
<source>Onion skin:</source>
<translation type="unfinished"/><|fim▁hole|> <message>
<location filename="../core_lib/src/interface/timeline.cpp" line="138"/>
<source>Toggle match keyframes</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="285"/>
<source>Delete Layer</source>
<comment>Windows title of Delete current layer pop-up.</comment>
<translation>Kustuta kiht</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="295"/>
<source>Please keep at least one camera layer in project</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../core_lib/src/interface/timeline.cpp" line="286"/>
<source>Are you sure you want to delete layer: </source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TimeLineCells</name>
<message>
<location filename="../core_lib/src/interface/timelinecells.cpp" line="679"/>
<source>Layer Properties</source>
<translation>Kihi omadused</translation>
</message>
<message>
<location filename="../core_lib/src/interface/timelinecells.cpp" line="680"/>
<source>Layer name:</source>
<translation>Kihi nimi:</translation>
</message>
</context>
<context>
<name>Timeline2</name>
<message>
<location filename="../app/ui/timeline2.ui" line="14"/>
<source>Timeline</source>
<translation>Ajatelg</translation>
</message>
<message>
<location filename="../app/ui/timeline2.ui" line="54"/>
<source>Layers</source>
<translation>Kihid</translation>
</message>
<message>
<location filename="../app/ui/timeline2.ui" line="68"/>
<location filename="../app/ui/timeline2.ui" line="82"/>
<source>...</source>
<translation>...</translation>
</message>
</context>
<context>
<name>TimelinePage</name>
<message>
<location filename="../app/ui/timelinepage.ui" line="20"/>
<source>Timeline</source>
<translation>Ajatelg</translation>
</message>
<message>
<location filename="../app/ui/timelinepage.ui" line="60"/>
<source>Timeline length:</source>
<comment>Preferences</comment>
<translation>Ajatelje pikkus:</translation>
</message>
<message>
<location filename="../app/ui/timelinepage.ui" line="89"/>
<source>Drawing</source>
<translation>Joonistamine</translation>
</message>
<message>
<location filename="../app/ui/timelinepage.ui" line="95"/>
<source>When drawing on an empty frame:</source>
<translation>Kui joonistatakse tühja kaadrisse:</translation>
</message>
<message>
<location filename="../app/ui/timelinepage.ui" line="102"/>
<source>Create a new (blank) key-frame and start drawing on it.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/timelinepage.ui" line="105"/>
<source>Create a new (blank) key-frame</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/timelinepage.ui" line="115"/>
<source>Duplicate the previous key-frame and start drawing on the duplicate.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/timelinepage.ui" line="118"/>
<source>Duplicate the previous key-frame</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/timelinepage.ui" line="125"/>
<source>Keep drawing on the previous key-frame</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/timelinepage.ui" line="137"/>
<source><html><head/><body><p>(Applies to Pencil, Erasor, Pen, Polyline, Bucket and Brush tools)</p></body></html></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/timelinepage.ui" line="162"/>
<source>Playback</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/timelinepage.ui" line="174"/>
<source>Show onion skin while playing</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/timelinepage.ui" line="26"/>
<source>Frame size</source>
<translation>Kaadri suurus</translation>
</message>
<message>
<location filename="../app/ui/timelinepage.ui" line="79"/>
<source>Short scrub</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ToolBoxWidget</name>
<message>
<location filename="../app/ui/toolboxwidget.ui" line="20"/>
<source>Tools</source>
<comment>Window title of tool box</comment>
<translation>Tööriistad</translation>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="77"/>
<source>Pencil Tool (%1): Sketch with pencil</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="79"/>
<source>Select Tool (%1): Select an object</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="81"/>
<source>Move Tool (%1): Move an object</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="83"/>
<source>Hand Tool (%1): Move the canvas</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="85"/>
<source>Pen Tool (%1): Sketch with pen</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="87"/>
<source>Eraser Tool (%1): Erase</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="89"/>
<source>Polyline Tool (%1): Create line/curves</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="91"/>
<source>Paint Bucket Tool (%1): Fill selected area with a color</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="93"/>
<source>Brush Tool (%1): Paint smooth stroke with a brush</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="95"/>
<source>Eyedropper Tool (%1): Set color from the stage<br>[ALT] for instant access</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="98"/>
<source>Clear Frame (%1): Erases content of selected frame</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="100"/>
<source>Smudge Tool (%1):<br>Edit polyline/curves<br>Liquify bitmap pixels<br> (%1)+[Alt]: Smooth</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="104"/>
<source>Pencil Tool (%1)</source>
<translation>Pliiats (%1)</translation>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="106"/>
<source>Select Tool (%1)</source>
<translation>Valimine (%1)</translation>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="108"/>
<source>Move Tool (%1)</source>
<translation>Liigutamine (%1)</translation>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="110"/>
<source>Hand Tool (%1)</source>
<translation>Käsi (%1)</translation>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="112"/>
<source>Pen Tool (%1)</source>
<translation>Pastakas (%1)</translation>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="114"/>
<source>Eraser Tool (%1)</source>
<translation>Kustutkumm (%1)</translation>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="116"/>
<source>Polyline Tool (%1)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="118"/>
<source>Paint Bucket Tool (%1)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="120"/>
<source>Brush Tool (%1)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="122"/>
<source>Eyedropper Tool (%1)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="124"/>
<source>Clear Tool (%1)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/toolbox.cpp" line="126"/>
<source>Smudge Tool (%1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ToolOptionWidget</name>
<message>
<location filename="../app/src/tooloptionwidget.cpp" line="48"/>
<source>Brush</source>
<translation>Pintsel</translation>
</message>
<message>
<location filename="../app/src/tooloptionwidget.cpp" line="52"/>
<source>Feather</source>
<translation>Sujuv üleminek</translation>
</message>
<message>
<location filename="../app/src/tooloptionwidget.cpp" line="56"/>
<source>Color Tolerance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/src/tooloptionwidget.cpp" line="32"/>
<source>Options</source>
<comment>Window title of tool option panel like pen width, feather etc..</comment>
<translation>Valikud</translation>
</message>
<message>
<location filename="../app/src/tooloptionwidget.cpp" line="183"/>
<source>Stroke Thickness</source>
<translation>Joone paksus</translation>
</message>
<message>
<location filename="../app/src/tooloptionwidget.cpp" line="188"/>
<source>Width</source>
<translation>Laius</translation>
</message>
</context>
<context>
<name>ToolOptions</name>
<message>
<location filename="../app/ui/tooloptions.ui" line="14"/>
<source>Form</source>
<translation>Vorm</translation>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="22"/>
<source>Set Pen Width <br><b>[SHIFT]+drag</b><br>for quick adjustment</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="58"/>
<source>Set Pen Feather <br><b>[CTRL]+drag</b><br>for quick adjustment</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="92"/>
<source>Enable or disable feathering</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="95"/>
<source>Use Feather</source>
<translation>Kasuta sujuvat üleminekut</translation>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="102"/>
<source>Contour will be filled</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="105"/>
<source>Fill Contour</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="114"/>
<source>The extend to which the color variation will be treated as being equal</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="133"/>
<source>Bezier</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="140"/>
<source>Pressure</source>
<comment>Brush</comment>
<translation>Surve</translation>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="147"/>
<source>Anti-Aliasing</source>
<comment>Brush AA</comment>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="177"/>
<source>Merge</source>
<comment>Vector line merge</comment>
<translation>Liida</translation>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="200"/>
<source>None</source>
<comment>Stabilizer option</comment>
<translation>Pole</translation>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="205"/>
<source>Simple</source>
<comment>Stabilizer option</comment>
<translation>Lihtne</translation>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="210"/>
<source>Strong</source>
<comment>Stabilizer option</comment>
<translation>Tugev</translation>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="154"/>
<source>Make invisible</source>
<translation>Tee nähtamatuks</translation>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="157"/>
<source>Invisible</source>
<translation>Nähtamatu</translation>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="164"/>
<source>Preserve Alpha</source>
<translation>Säilita alfakanal</translation>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="167"/>
<source>Alpha</source>
<translation>Alfa</translation>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="174"/>
<source>Merge vector lines when they are close together</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/tooloptions.ui" line="192"/>
<source>Stabilizer</source>
<translation>Stabiliseerija</translation>
</message>
</context>
<context>
<name>ToolsPage</name>
<message>
<location filename="../app/ui/toolspage.ui" line="17"/>
<source>Onion skin</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/toolspage.ui" line="23"/>
<source>Maximum onion opacity %</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/toolspage.ui" line="49"/>
<source>Minimum onion opacity %</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/toolspage.ui" line="75"/>
<source>Number of previous onion frames shown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/toolspage.ui" line="104"/>
<source>Number of next onion frames shown</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/toolspage.ui" line="136"/>
<source>Brush Tools</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../app/ui/toolspage.ui" line="142"/>
<source>Use Quick Sizing</source>
<translation type="unfinished"/>
</message>
</context>
</TS><|fim▁end|> | </message> |
<|file_name|>TreeHasher.py<|end_file_name|><|fim▁begin|>import itertools
import os<|fim▁hole|>class TreeHasher():
"""uses BlockHasher recursively on a directory tree
Input and output generators are in the format: ( relative-filepath, chunk_nr, hexdigest)
"""
def __init__(self, block_hasher):
"""
:type block_hasher: BlockHasher
"""
self.block_hasher=block_hasher
def generate(self, start_path):
"""Use BlockHasher on every file in a tree, yielding the results
note that it only checks the contents of actual files. It ignores metadata like permissions and mtimes.
It also ignores empty directories, symlinks and special files.
"""
def walkerror(e):
raise e
for (dirpath, dirnames, filenames) in os.walk(start_path, onerror=walkerror):
for f in filenames:
file_path=os.path.join(dirpath, f)
if (not os.path.islink(file_path)) and os.path.isfile(file_path):
for (chunk_nr, hash) in self.block_hasher.generate(file_path):
yield ( os.path.relpath(file_path,start_path), chunk_nr, hash )
def compare(self, start_path, generator):
"""reads from generator and compares blocks
yields mismatches in the form: ( relative_filename, chunk_nr, compare_hexdigest, actual_hexdigest )
yields errors in the form: ( relative_filename, chunk_nr, compare_hexdigest, "message" )
"""
count=0
def filter_file_name( file_name, chunk_nr, hexdigest):
return ( chunk_nr, hexdigest )
for file_name, group_generator in itertools.groupby(generator, lambda x: x[0]):
count=count+1
block_generator=itertools.starmap(filter_file_name, group_generator)
for ( chunk_nr, compare_hexdigest, actual_hexdigest) in self.block_hasher.compare(os.path.join(start_path,file_name), block_generator):
yield ( file_name, chunk_nr, compare_hexdigest, actual_hexdigest )<|fim▁end|> | |
<|file_name|>xbmc.js<|end_file_name|><|fim▁begin|>angular.module( 'remote.xbmc-service' , [] )
.service( 'XBMCService', function( $log,$http,Storage ){
//http://kodi.wiki/view/JSON-RPC_API/v6
var XBMC = this,
settings = (new Storage("settings")).get();
url = 'http://' + settings.ip + '/',<|fim▁hole|>
//url = 'http://localhost:8200/'
function cmd(){
return _.cloneDeep( command );
}
function sendRequest( data ){
$log.debug("Sending " , data , " to " , url + 'jsonrpc');
return $http.post( url + 'jsonrpc' , data );
}
XBMC.sendText = function( text ){
var data = cmd();
data.params = { method: "Player.SendText", item: { text: text, done: true } };
return sendRequest( data );
}
XBMC.input = function( what ){
var data = cmd();
switch( what ){
case 'back':
data.method = "Input.Back";
break;
case 'left':
data.method = "Input.Left";
break;
case 'right':
data.method = "Input.right";
break;
case 'up':
data.method = "Input.Up";
break;
case 'down':
data.method = "Input.Down";
break;
case 'select':
data.method = "Input.Select";
break;
case 'info':
data.method = "Input.Info";
break;
case 'context':
data.method = "Input.ContextMenu";
break;
}
return sendRequest( data );
}
XBMC.sendToPlayer = function( link ){
var data = cmd();
data.params = { method: "Player.Open", item: { file: link } };
return sendRequest( data );
}
})<|fim▁end|> | command = {id: 1, jsonrpc: "2.0" };
|
<|file_name|>ProcessManagedBean.java<|end_file_name|><|fim▁begin|>/*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package javax.enterprise.inject.spi;
/**
* {@link javax.enterprise.inject.spi.Extension} callback while processing
* a managed bean.
*
* <code><pre>
* public class MyExtension implements Extension
* {
* <X> public void
* processManagedBean(@Observes ProcessManagedBean<X> event)
* {<|fim▁hole|> * ...
* }
* }
* </pre></code>
*/
public interface ProcessManagedBean<X> extends ProcessBean<X>
{
public AnnotatedType<X> getAnnotatedBeanClass();
}<|fim▁end|> | |
<|file_name|>search.py<|end_file_name|><|fim▁begin|># Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import packaging.version
from elasticsearch_dsl import Date, Document, Float, Keyword, Text, analyzer
from warehouse.search.utils import doc_type
EmailAnalyzer = analyzer(
"email",
tokenizer="uax_url_email",
filter=["lowercase", "stop", "snowball"],
)
NameAnalyzer = analyzer(
"normalized_name",
tokenizer="lowercase",
filter=["lowercase", "word_delimiter"],
)
@doc_type
class Project(Document):
name = Text()
normalized_name = Text(analyzer=NameAnalyzer)
version = Keyword(multi=True)
latest_version = Keyword()
summary = Text(analyzer="snowball")
description = Text(analyzer="snowball")
author = Text()
author_email = Text(analyzer=EmailAnalyzer)
maintainer = Text()
maintainer_email = Text(analyzer=EmailAnalyzer)
license = Text()
home_page = Keyword()
download_url = Keyword()
keywords = Text(analyzer="snowball")
platform = Keyword()
created = Date()
classifiers = Keyword(multi=True)
zscore = Float()
@classmethod
def from_db(cls, release):
obj = cls(meta={"id": release.normalized_name})
obj["name"] = release.name
obj["normalized_name"] = release.normalized_name
obj["version"] = sorted(<|fim▁hole|> obj["summary"] = release.summary
obj["description"] = release.description
obj["author"] = release.author
obj["author_email"] = release.author_email
obj["maintainer"] = release.maintainer
obj["maintainer_email"] = release.maintainer_email
obj["home_page"] = release.home_page
obj["download_url"] = release.download_url
obj["keywords"] = release.keywords
obj["platform"] = release.platform
obj["created"] = release.created
obj["classifiers"] = release.classifiers
obj["zscore"] = release.zscore
return obj
class Index:
# make sure this class can match any index so it will always be used to
# deserialize data coming from elasticsearch.
name = "*"<|fim▁end|> | release.all_versions, key=lambda r: packaging.version.parse(r), reverse=True
)
obj["latest_version"] = release.latest_version |
<|file_name|>messages.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012 Nebula, 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.
"""
Drop-in replacement for django.contrib.messages which handles Horizon's
messaging needs (e.g. AJAX communication, etc.).
"""
from django.contrib import messages as _messages
from django.contrib.messages import constants
from django.utils.encoding import force_unicode # noqa
from django.utils.safestring import SafeData # noqa
def add_message(request, level, message, extra_tags='', fail_silently=False):
"""Attempts to add a message to the request using the 'messages' app."""
if request.is_ajax():
tag = constants.DEFAULT_TAGS[level]
# if message is marked as safe, pass "safe" tag as extra_tags so that
# client can skip HTML escape for the message when rendering
if isinstance(message, SafeData):
extra_tags = extra_tags + ' safe'
request.horizon['async_messages'].append([tag,
force_unicode(message),
extra_tags])
else:
return _messages.add_message(request, level, message,
extra_tags, fail_silently)
<|fim▁hole|> add_message(request, constants.DEBUG, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def info(request, message, extra_tags='', fail_silently=False):
"""Adds a message with the ``INFO`` level."""
add_message(request, constants.INFO, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def success(request, message, extra_tags='', fail_silently=False):
"""Adds a message with the ``SUCCESS`` level."""
add_message(request, constants.SUCCESS, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def warning(request, message, extra_tags='', fail_silently=False):
"""Adds a message with the ``WARNING`` level."""
add_message(request, constants.WARNING, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def error(request, message, extra_tags='', fail_silently=False):
"""Adds a message with the ``ERROR`` level."""
add_message(request, constants.ERROR, message, extra_tags=extra_tags,
fail_silently=fail_silently)<|fim▁end|> |
def debug(request, message, extra_tags='', fail_silently=False):
"""Adds a message with the ``DEBUG`` level.""" |
<|file_name|>jquery.countdown.min.js<|end_file_name|><|fim▁begin|>/*
* jQuery The Final Countdown plugin v1.0.0 beta
* http://github.com/hilios/jquery.countdown
*
* Copyright (c) 2011 Edson Hilios
*
* 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.
*/
(function($) {
$.fn.countdown = function(toDate, callback) {
var handlers = ['seconds', 'minutes', 'hours', 'days', 'weeks', 'daysLeft'];
function delegate(scope, method) {
return function() { return method.call(scope) }
}
return this.each(function() {
// Convert
var $this = $(this),
values = {},
lasting = {},
interval = $this.data('countdownInterval'),
secondsLeft = Math.floor((toDate - upcoming_data.c_time) );
function triggerEvents() {
secondsLeft--;
if(secondsLeft < 0) {
secondsLeft = 0;
}
lasting = {
seconds : secondsLeft % 60,
minutes : Math.floor(secondsLeft / 60) % 60,
hours : Math.floor(secondsLeft / 60 / 60) % 24,
days : Math.floor(secondsLeft / 60 / 60 / 24),
weeks : Math.floor(secondsLeft / 60 / 60 / 24 / 7),
daysLeft: Math.floor(secondsLeft / 60 / 60 / 24) % 7
}
for(var i=0; i<handlers.length; i++) {
var eventName = handlers[i];
if(values[eventName] != lasting[eventName]) {
values[eventName] = lasting[eventName];
dispatchEvent(eventName);
}
}
if(secondsLeft == 0) {
stop();
dispatchEvent('finished');
}
}
triggerEvents();
function dispatchEvent(eventName) {
var event = $.Event(eventName);
event.date = new Date(new Date().valueOf() + secondsLeft);
event.value = values[eventName] || "0";
event.toDate = toDate;
event.lasting = lasting;
switch(eventName) {
case "seconds":
case "minutes":
case "hours":
event.value = event.value < 10 ? '0'+event.value.toString() : event.value.toString();
break;
default:<|fim▁hole|> }
callback.call($this, event);
}
$this.bind('remove', function() {
stop(); // If the selector is removed clear the interval for memory sake!
dispatchEvent('removed');
});
function stop() {
clearInterval(interval);
}
function start() {
$this.data('countdownInterval', setInterval(delegate($this, triggerEvents), 1000));
interval = $this.data('countdownInterval');
}
if(interval) stop();
start();
});
}
// Wrap the remove method to trigger an event when called
var removeEvent = new $.Event('remove'),
removeFunction = $.fn.remove;
$.fn.remove = function() {
$(this).trigger(removeEvent);
return removeFunction.apply(this, arguments);
}
})(jQuery);<|fim▁end|> | if(event.value) {
event.value = event.value.toString();
}
break; |
<|file_name|>_FactoryFinderProviderFactory.java<|end_file_name|><|fim▁begin|>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* 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 javax.faces;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.ExternalContext;
/**
* Provide utility methods used by FactoryFinder class to lookup for SPI interface FactoryFinderProvider.
*
* @since 2.0.5
*/
class _FactoryFinderProviderFactory
{
public static final String FACTORY_FINDER_PROVIDER_FACTORY_CLASS_NAME = "org.apache.myfaces.spi" +
".FactoryFinderProviderFactory";
public static final String FACTORY_FINDER_PROVIDER_CLASS_NAME = "org.apache.myfaces.spi.FactoryFinderProvider";
public static final String INJECTION_PROVIDER_FACTORY_CLASS_NAME =
"org.apache.myfaces.spi.InjectionProviderFactory";
// INJECTION_PROVIDER_CLASS_NAME to provide use of new Injection Provider methods which take a
// a class as an input. This is required for CDI 1.2, particularly in regard to constructor injection/
public static final String INJECTION_PROVIDER_CLASS_NAME = "com.ibm.ws.jsf.spi.WASInjectionProvider";
// MANAGED_OBJECT_CLASS_NAME added for CDI 1.2 support. Because CDI now creates the class, inject needs
// to return two objects : the instance of the required class and the creational context. To do this
// an Managed object is returned from which both of the required objects can be obtained.
public static final String MANAGED_OBJECT_CLASS_NAME = "com.ibm.ws.managedobject.ManagedObject";
public static final Class<?> FACTORY_FINDER_PROVIDER_FACTORY_CLASS;
public static final Method FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD;
public static final Method FACTORY_FINDER_PROVIDER_FACTORY_GET_FACTORY_FINDER_METHOD;
public static final Class<?> FACTORY_FINDER_PROVIDER_CLASS;
public static final Method FACTORY_FINDER_PROVIDER_GET_FACTORY_METHOD;
public static final Method FACTORY_FINDER_PROVIDER_SET_FACTORY_METHOD;
public static final Method FACTORY_FINDER_PROVIDER_RELEASE_FACTORIES_METHOD;
public static final Class<?> INJECTION_PROVIDER_FACTORY_CLASS;
public static final Method INJECTION_PROVIDER_FACTORY_GET_INSTANCE_METHOD;
public static final Method INJECTION_PROVIDER_FACTORY_GET_INJECTION_PROVIDER_METHOD;
public static final Class<?> INJECTION_PROVIDER_CLASS;
public static final Method INJECTION_PROVIDER_INJECT_OBJECT_METHOD;
public static final Method INJECTION_PROVIDER_INJECT_CLASS_METHOD;
public static final Method INJECTION_PROVIDER_POST_CONSTRUCT_METHOD;
public static final Method INJECTION_PROVIDER_PRE_DESTROY_METHOD;
// New for CDI 1.2
public static final Class<?> MANAGED_OBJECT_CLASS;
public static final Method MANAGED_OBJECT_GET_OBJECT_METHOD;
public static final Method MANAGED_OBJECT_GET_CONTEXT_DATA_METHOD;
static
{
Class factoryFinderFactoryClass = null;
Method factoryFinderproviderFactoryGetMethod = null;
Method factoryFinderproviderFactoryGetFactoryFinderMethod = null;
Class<?> factoryFinderProviderClass = null;
Method factoryFinderProviderGetFactoryMethod = null;
Method factoryFinderProviderSetFactoryMethod = null;
Method factoryFinderProviderReleaseFactoriesMethod = null;
Class injectionProviderFactoryClass = null;
Method injectionProviderFactoryGetInstanceMethod = null;
Method injectionProviderFactoryGetInjectionProviderMethod = null;
Class injectionProviderClass = null;
Method injectionProviderInjectObjectMethod = null;
Method injectionProviderInjectClassMethod = null;
Method injectionProviderPostConstructMethod = null;
Method injectionProviderPreDestroyMethod = null;
Class managedObjectClass = null;
Method managedObjectGetObjectMethod = null;
Method managedObjectGetContextDataMethod = null;
try
{
factoryFinderFactoryClass = classForName(FACTORY_FINDER_PROVIDER_FACTORY_CLASS_NAME);
if (factoryFinderFactoryClass != null)
{
factoryFinderproviderFactoryGetMethod = factoryFinderFactoryClass.getMethod
("getInstance", null);
factoryFinderproviderFactoryGetFactoryFinderMethod = factoryFinderFactoryClass
.getMethod("getFactoryFinderProvider", null);
}
factoryFinderProviderClass = classForName(FACTORY_FINDER_PROVIDER_CLASS_NAME);
if (factoryFinderProviderClass != null)
{
factoryFinderProviderGetFactoryMethod = factoryFinderProviderClass.getMethod("getFactory",
new Class[]{String.class});
factoryFinderProviderSetFactoryMethod = factoryFinderProviderClass.getMethod("setFactory",
new Class[]{String.class, String.class});
factoryFinderProviderReleaseFactoriesMethod = factoryFinderProviderClass.getMethod
("releaseFactories", null);
}
injectionProviderFactoryClass = classForName(INJECTION_PROVIDER_FACTORY_CLASS_NAME);
if (injectionProviderFactoryClass != null)
{
injectionProviderFactoryGetInstanceMethod = injectionProviderFactoryClass.
getMethod("getInjectionProviderFactory", null);
injectionProviderFactoryGetInjectionProviderMethod = injectionProviderFactoryClass.
getMethod("getInjectionProvider", ExternalContext.class);
}
injectionProviderClass = classForName(INJECTION_PROVIDER_CLASS_NAME);
if (injectionProviderClass != null)
{
injectionProviderInjectObjectMethod = injectionProviderClass.
getMethod("inject", Object.class);
injectionProviderInjectClassMethod = injectionProviderClass.
getMethod("inject", Class.class);
injectionProviderPostConstructMethod = injectionProviderClass.
getMethod("postConstruct", Object.class, Object.class);
injectionProviderPreDestroyMethod = injectionProviderClass.
getMethod("preDestroy", Object.class, Object.class);
}
// get managed object and getObject and getContextData methods for CDI 1.2 support.
// getObject() is used to the created object instance
// getContextData(Class) is used to get the creational context
managedObjectClass = classForName(MANAGED_OBJECT_CLASS_NAME);
if (managedObjectClass != null)
{
managedObjectGetObjectMethod = managedObjectClass.getMethod("getObject", null);
managedObjectGetContextDataMethod = managedObjectClass.getMethod("getContextData", Class.class);
}
}
catch (Exception e)
{
// no op
}
FACTORY_FINDER_PROVIDER_FACTORY_CLASS = factoryFinderFactoryClass;
FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD = factoryFinderproviderFactoryGetMethod;
FACTORY_FINDER_PROVIDER_FACTORY_GET_FACTORY_FINDER_METHOD = factoryFinderproviderFactoryGetFactoryFinderMethod;
FACTORY_FINDER_PROVIDER_CLASS = factoryFinderProviderClass;
FACTORY_FINDER_PROVIDER_GET_FACTORY_METHOD = factoryFinderProviderGetFactoryMethod;
FACTORY_FINDER_PROVIDER_SET_FACTORY_METHOD = factoryFinderProviderSetFactoryMethod;
FACTORY_FINDER_PROVIDER_RELEASE_FACTORIES_METHOD = factoryFinderProviderReleaseFactoriesMethod;
INJECTION_PROVIDER_FACTORY_CLASS = injectionProviderFactoryClass;
INJECTION_PROVIDER_FACTORY_GET_INSTANCE_METHOD = injectionProviderFactoryGetInstanceMethod;
INJECTION_PROVIDER_FACTORY_GET_INJECTION_PROVIDER_METHOD = injectionProviderFactoryGetInjectionProviderMethod;
INJECTION_PROVIDER_CLASS = injectionProviderClass;
INJECTION_PROVIDER_INJECT_OBJECT_METHOD = injectionProviderInjectObjectMethod;
INJECTION_PROVIDER_INJECT_CLASS_METHOD = injectionProviderInjectClassMethod;
INJECTION_PROVIDER_POST_CONSTRUCT_METHOD = injectionProviderPostConstructMethod;
INJECTION_PROVIDER_PRE_DESTROY_METHOD = injectionProviderPreDestroyMethod;
MANAGED_OBJECT_CLASS = managedObjectClass;
MANAGED_OBJECT_GET_OBJECT_METHOD = managedObjectGetObjectMethod;
MANAGED_OBJECT_GET_CONTEXT_DATA_METHOD = managedObjectGetContextDataMethod;
}
public static Object getInstance()
{
if (FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD != null)
{
try
{
return FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD.invoke(FACTORY_FINDER_PROVIDER_FACTORY_CLASS, null);
}
catch (Exception e)
{
//No op
Logger log = Logger.getLogger(_FactoryFinderProviderFactory.class.getName());
if (log.isLoggable(Level.WARNING))
{
log.log(Level.WARNING, "Cannot retrieve current FactoryFinder instance from " +
"FactoryFinderProviderFactory." +<|fim▁hole|> return null;
}
// ~ Methods Copied from _ClassUtils
// ------------------------------------------------------------------------------------
/**
* Tries a Class.loadClass with the context class loader of the current thread first and automatically falls back
* to
* the ClassUtils class loader (i.e. the loader of the myfaces.jar lib) if necessary.
*
* @param type fully qualified name of a non-primitive non-array class
* @return the corresponding Class
* @throws NullPointerException if type is null
* @throws ClassNotFoundException
*/
public static Class<?> classForName(String type) throws ClassNotFoundException
{
if (type == null)
{
throw new NullPointerException("type");
}
try
{
// Try WebApp ClassLoader first
return Class.forName(type, false, // do not initialize for faster startup
getContextClassLoader());
}
catch (ClassNotFoundException ignore)
{
// fallback: Try ClassLoader for ClassUtils (i.e. the myfaces.jar lib)
return Class.forName(type, false, // do not initialize for faster startup
_FactoryFinderProviderFactory.class.getClassLoader());
}
}
/**
* Gets the ClassLoader associated with the current thread. Returns the class loader associated with the specified
* default object if no context loader is associated with the current thread.
*
* @return ClassLoader
*/
protected static ClassLoader getContextClassLoader()
{
if (System.getSecurityManager() != null)
{
try
{
Object cl = AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public Object run() throws PrivilegedActionException
{
return Thread.currentThread().getContextClassLoader();
}
});
return (ClassLoader) cl;
}
catch (PrivilegedActionException pae)
{
throw new FacesException(pae);
}
}
else
{
return Thread.currentThread().getContextClassLoader();
}
}
}<|fim▁end|> | " Default strategy using thread context class loader will be used.", e);
}
}
} |
<|file_name|>capture.pb.validate.go<|end_file_name|><|fim▁begin|>// Code generated by protoc-gen-validate
// source: envoy/data/tap/v2alpha/capture.proto
// DO NOT EDIT!!!
package v2
import (
"bytes"
"errors"
"fmt"
"net"
"net/mail"
"net/url"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/gogo/protobuf/types"
)
// ensure the imports are used
var (
_ = bytes.MinRead
_ = errors.New("")
_ = fmt.Print
_ = utf8.UTFMax
_ = (*regexp.Regexp)(nil)
_ = (*strings.Reader)(nil)
_ = net.IPv4len
_ = time.Duration(0)
_ = (*url.URL)(nil)
_ = (*mail.Address)(nil)
_ = types.DynamicAny{}
)
// Validate checks the field values on Connection with the rules defined in the
// proto definition for this message. If any rules are violated, an error is returned.
func (m *Connection) Validate() error {
if m == nil {
return nil
}
// no validation rules for Id
if v, ok := interface{}(m.GetLocalAddress()).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return ConnectionValidationError{
Field: "LocalAddress",
Reason: "embedded message failed validation",
Cause: err,
}
}
}
if v, ok := interface{}(m.GetRemoteAddress()).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return ConnectionValidationError{
Field: "RemoteAddress",
Reason: "embedded message failed validation",
Cause: err,
}
}
}
return nil
}
// ConnectionValidationError is the validation error returned by
// Connection.Validate if the designated constraints aren't met.
type ConnectionValidationError struct {
Field string
Reason string
Cause error
Key bool
}
// Error satisfies the builtin error interface
func (e ConnectionValidationError) Error() string {
cause := ""
if e.Cause != nil {
cause = fmt.Sprintf(" | caused by: %v", e.Cause)
}
key := ""
if e.Key {
key = "key for "
}
return fmt.Sprintf(
"invalid %sConnection.%s: %s%s",
key,
e.Field,
e.Reason,
cause)
}
var _ error = ConnectionValidationError{}
// Validate checks the field values on Event with the rules defined in the
// proto definition for this message. If any rules are violated, an error is returned.
func (m *Event) Validate() error {
if m == nil {
return nil
}
if v, ok := interface{}(m.GetTimestamp()).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return EventValidationError{
Field: "Timestamp",
Reason: "embedded message failed validation",
Cause: err,
}
}
}
switch m.EventSelector.(type) {
case *Event_Read_:
if v, ok := interface{}(m.GetRead()).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return EventValidationError{
Field: "Read",
Reason: "embedded message failed validation",
Cause: err,
}
}
}
case *Event_Write_:
if v, ok := interface{}(m.GetWrite()).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return EventValidationError{
Field: "Write",
Reason: "embedded message failed validation",
Cause: err,
}
}
}
}
return nil
}
// EventValidationError is the validation error returned by Event.Validate if
// the designated constraints aren't met.
type EventValidationError struct {
Field string
Reason string
Cause error
Key bool
}
// Error satisfies the builtin error interface
func (e EventValidationError) Error() string {
cause := ""
if e.Cause != nil {
cause = fmt.Sprintf(" | caused by: %v", e.Cause)
}
key := ""
if e.Key {
key = "key for "
}
return fmt.Sprintf(
"invalid %sEvent.%s: %s%s",
key,
e.Field,
e.Reason,
cause)
}
var _ error = EventValidationError{}
// Validate checks the field values on Trace with the rules defined in the
// proto definition for this message. If any rules are violated, an error is returned.
func (m *Trace) Validate() error {
if m == nil {
return nil
}
if v, ok := interface{}(m.GetConnection()).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return TraceValidationError{
Field: "Connection",
Reason: "embedded message failed validation",
Cause: err,
}
}
}
for idx, item := range m.GetEvents() {
_, _ = idx, item
if v, ok := interface{}(item).(interface{ Validate() error }); ok {
if err := v.Validate(); err != nil {
return TraceValidationError{
Field: fmt.Sprintf("Events[%v]", idx),
Reason: "embedded message failed validation",
Cause: err,
}
}
}
}
return nil
}
// TraceValidationError is the validation error returned by Trace.Validate if
// the designated constraints aren't met.
type TraceValidationError struct {
Field string
Reason string
Cause error
Key bool
}
// Error satisfies the builtin error interface
func (e TraceValidationError) Error() string {
cause := ""
if e.Cause != nil {
cause = fmt.Sprintf(" | caused by: %v", e.Cause)
}
key := ""
if e.Key {
key = "key for "
}
return fmt.Sprintf(
"invalid %sTrace.%s: %s%s",
key,
e.Field,
e.Reason,
cause)
}
var _ error = TraceValidationError{}
// Validate checks the field values on Event_Read with the rules defined in the
// proto definition for this message. If any rules are violated, an error is returned.
func (m *Event_Read) Validate() error {
if m == nil {
return nil
}
<|fim▁hole|> // no validation rules for Data
return nil
}
// Event_ReadValidationError is the validation error returned by
// Event_Read.Validate if the designated constraints aren't met.
type Event_ReadValidationError struct {
Field string
Reason string
Cause error
Key bool
}
// Error satisfies the builtin error interface
func (e Event_ReadValidationError) Error() string {
cause := ""
if e.Cause != nil {
cause = fmt.Sprintf(" | caused by: %v", e.Cause)
}
key := ""
if e.Key {
key = "key for "
}
return fmt.Sprintf(
"invalid %sEvent_Read.%s: %s%s",
key,
e.Field,
e.Reason,
cause)
}
var _ error = Event_ReadValidationError{}
// Validate checks the field values on Event_Write with the rules defined in
// the proto definition for this message. If any rules are violated, an error
// is returned.
func (m *Event_Write) Validate() error {
if m == nil {
return nil
}
// no validation rules for Data
// no validation rules for EndStream
return nil
}
// Event_WriteValidationError is the validation error returned by
// Event_Write.Validate if the designated constraints aren't met.
type Event_WriteValidationError struct {
Field string
Reason string
Cause error
Key bool
}
// Error satisfies the builtin error interface
func (e Event_WriteValidationError) Error() string {
cause := ""
if e.Cause != nil {
cause = fmt.Sprintf(" | caused by: %v", e.Cause)
}
key := ""
if e.Key {
key = "key for "
}
return fmt.Sprintf(
"invalid %sEvent_Write.%s: %s%s",
key,
e.Field,
e.Reason,
cause)
}
var _ error = Event_WriteValidationError{}<|fim▁end|> | |
<|file_name|>regex.py<|end_file_name|><|fim▁begin|>import re
from utilRegex import database
class regex:
def __init__(self, botCfg):
"""class initialization function
"""
#intitialize database variables
self.db = database()
#initialize regex variables
self.phrase = ''
self.url = ''
#initialize status variables
self.phraseReady = False
self.urlReady = False
#load database configuration settings
self.db.loadConfig(botCfg)
def buildPhrase(self):
"""compile phrase regex object
builds a regex object that includes
existing phrases from the phrase table
in the database.
returns:
success: True
failure: False
"""
#initialize function
self.phraseReady = False
#open database connection
try:
self.db.connect()
except:
print 'utilRegex/regex.buildPhrase: failed to connect to database.'
return False
#pull records from database
try:
self.db.cursor.execute('SELECT *' + \<|fim▁hole|> records = self.db.cursor.fetchall()
except:
print 'utilRegex/regex.buildPhrase: failed to retrieve records from database.'
self.db.cursor.close()
self.db.disconnect()
return False
#close database connection
self.db.cursor.close()
self.db.disconnect()
#build pattern string
if len(records) > 0: #only build the string if records are present
pattern = ''.join(['%s|' % (re.escape(record[1])) for record in records])
pattern = pattern[:-1]
else: #otherwise a placeholder (literally xD)
pattern = re.escape('a placeholder')
pattern = r'(^|\s|[a-z]-)(%s)+([a-z]{1,4})?(\'[a-z]{1,4})?(\s|\.|,|\?|\!|$)' % (pattern)
#compile the regex object
self.phrase = re.compile(pattern, re.IGNORECASE)
#exit the function
self.phraseReady = True
return True<|fim▁end|> | ' FROM phraseprint()' + \
' f(id bigint, phrase text, username text)') |
<|file_name|>sdc_firewall.py<|end_file_name|><|fim▁begin|>#
# Authors: Robert Abram <[email protected]>
#
# Copyright (C) 2015-2017 EntPack
# see file 'LICENSE' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import argparse
import gettext
import logging
import multiprocessing
import operator
import os
import signal
import sys
import time
from multiprocessing import Manager
from silentdune_client import modules
from silentdune_client.utils.log import setup_logging
from silentdune_client.utils.misc import node_info_dump
from silentdune_client.utils.configuration import ClientConfiguration
from silentdune_client.utils.daemon import Daemon
_logger = logging.getLogger('sd-client')
def run():
class SDCDaemon(Daemon):
# Node configuration information
_args = None
_config = None
stopProcessing = False
reload = False
t_start = time.time()
t_mod_check = 0
def __init__(self, *args, **kwargs):
self._args = kwargs.pop('args', None)
super(SDCDaemon, self).__init__(*args, **kwargs)
def startup_modules(self):
# Get the path where this file is located.
app_path = os.path.split(os.path.realpath(__file__))[0]
# Get our package path and package name
base_path, package_name = os.path.split(app_path)
# Get loadable module list
mods = modules.__load_modules__(base_path=base_path)
active_mods = [] # List of modules marked as active.
running_mods = [] # List of modules that are really running.
# Set the configuration in each module.
for mod in mods:
mod.set_config(self._config) # Set the configuration information in the module.
# If the module is enabled, add it to the active_mods list.
if mod.module_enabled():
active_mods.append(mod)
else:
_logger.debug('Service: module {0} is disabled.'.format(mod.get_name()))
pmanager = Manager()
mqueue = pmanager.Queue()
# Keep the created child processes.
cprocs = dict() # Dictionary of module process handlers.
cqueues = dict() # Dictionary of module Queue objects.
mlist = list() # List of module names.
# Sort modules by the priority attribute so we can start them in the proper order.
sorted_mods = sorted(active_mods, key=operator.attrgetter('priority'))
for mod in sorted_mods:
_logger.debug('Service: starting module {0}: ({1})'.format(mod.get_name(), mod.priority))
if mod.service_startup() is False:
_logger.critical('Service: module ({0}) failed during startup.'.format(mod.get_name))
# sys.exit(1)
continue
name = mod.get_name()
running_mods.append(mod)
mlist.append(name)
cprocs[name] = None # Add a place holder for the module process.
# Setup thread for modules wanting a processing thread.
if mod.wants_processing_thread:
# _logger.debug('Initializing thread for {0}.'.format(name))
cqueues[name] = multiprocessing.Queue()
cprocs[name] = multiprocessing.Process(
target=mod.process_handler, args=(cqueues[name], mqueue, mlist))
cprocs[name].start()
# Give the firewall manager time to setup the initial rules.
if name == 'SilentDuneClientFirewallModule':
time.sleep(2)
return running_mods, pmanager, mqueue, cprocs, cqueues, mlist
def check_module_state(self, mods, mqueue, cprocs, cqueues, mlist, force=False):
"""
Check each module that has a thread and make sure it is still alive.
:param mods:
:return: False if all threads are running fine, True if failed module.
"""
# We only want to do a check once a minute.
time_t = int((time.time() - self.t_start))
if (time_t > self.t_mod_check and time_t % 60.0 == 0.0) or force:
self.t_mod_check = int((time.time() - self.t_start))
# Check to see that module process threads are still running.
_logger.debug('Service: checking module threads.')
for mod in mods:
name = mod.get_name()
_logger.debug('{0}: checking module thread...'.format(name))
if name in cprocs and cprocs[name]:
if cprocs[name].is_alive():
mod.restart_count = 0
else:
# See if we should attempt to restart this module
if mod.restart_count < 10:
_logger.critical('service: {0} module has unexpectedly stopped.'.format(name))
mod.restart_count += 1
_logger.info('service: attempting to restart module {0} (rc:{1})'.format(
name, mod.restart_count))
if mod.wants_processing_thread:
# _logger.debug('Initializing thread for {0}.'.format(name))
cqueues[name] = multiprocessing.Queue()
cprocs[name] = multiprocessing.Process(
target=mod.process_handler, args=(cqueues[name], mqueue, mlist))
cprocs[name].start()
else:
if mod.restart_count == 10:
_logger.warning(
'service: module restart limit exceeded for {0}, giving up.'.format(
name, mod.restart_count))
mod.restart_count += 1
if mod.restart_count % 60 == 0:
_logger.warning('service: module {0} is dead.'.format(name))
return mods, mqueue, cprocs, cqueues
def terminate_modules(self, mods, cprocs, cqueues):<|fim▁hole|> """
Shutdown modules.
"""
for mod in mods:
name = mod.get_name()
if cprocs[name] and cprocs[name].is_alive():
_logger.debug('Service: signalling {0} module to stop processing.'.format(name))
cqueues[name].put(modules.QueueTask(modules.TASK_STOP_PROCESSING))
cqueues[name].close()
cqueues[name].join_thread()
cprocs[name].join()
def run(self):
_logger.debug('Service: setting signal handlers.')
# Set SIGTERM signal Handler
signal.signal(signal.SIGTERM, signal_term_handler)
signal.signal(signal.SIGHUP, signal_hup_handler)
_logger.info('Starting Silent Dune firewall.')
# This loop allows for restarting and reloading the configuration after a SIGHUP signal has been received.
while True:
# Reset loop controllers
self.stopProcessing = False
self.reload = False
# Read the local configuration file.
self._config = ClientConfiguration(self._args.config).read_config()
mods, pmanager, mqueue, cprocs, cqueues, mlist = self.startup_modules()
# RUn main loop until we get an external signal.
_logger.debug('Service: starting main processing loop.')
while not self.stopProcessing:
mods, mqueue, cprocs, cqueues = self.check_module_state(mods, mqueue, cprocs, cqueues, mlist)
# Check manage queue for any QueueTask object.
try:
task = mqueue.get_nowait()
_logger.debug('Service: forwarding task ({0}) from {1} to {2}'.format(
task.get_task_id(), task.get_sender(), task.get_dest_name()))
if task:
# Find the destination module and send task to it.
if not task.get_dest_name() or not cqueues[task.get_dest_name()]:
_logger.error('Service: task from {0} has unknown destination.'.format(
task.get_sender()))
cqueues[task.get_dest_name()].put(task)
except:
pass
# Sleep.
time.sleep(0.25)
# Stop all module processing threads
_logger.debug('Service: terminating active modules...')
self.terminate_modules(mods, cprocs, cqueues)
# If we are not reloading, just shutdown.
if not self.reload:
break
_logger.debug('Service: reloading firewall.')
_logger.info('Firewall shutdown complete.')
# exit process
sys.exit(0)
def signal_term_handler(signal, frame):
if not _daemon.stopProcessing:
_logger.debug('Service: received SIGTERM signal.')
_daemon.stopProcessing = True
def signal_hup_handler(signal, frame):
if not _daemon.reload:
_logger.debug('Service: received SIGHUP signal.')
_daemon.reload = True
_daemon.stopProcessing = True
setup_logging(_logger, '--debug' in sys.argv)
os.environ['TMPDIR'] = '/var/run/silentdune'
if not os.path.isdir(os.environ['TMPDIR']):
os.makedirs(os.environ['TMPDIR'])
# Setup i18n - Good for 2.x and 3.x python.
kwargs = {}
if sys.version_info[0] < 3:
kwargs['unicode'] = True
gettext.install('sdc_service', **kwargs)
# Setup program arguments.
parser = argparse.ArgumentParser(prog='sdc-firewall')
parser.add_argument('-c', '--config', help=_('Use config file'), default=None, type=str) # noqa
parser.add_argument('--debug', help=_('Enable debug output'), default=False, action='store_true') # noqa
parser.add_argument('--nodaemon', help=_('Do not daemonize process'), default=False, action='store_true') # noqa
parser.add_argument('action', choices=('start', 'stop', 'restart'), default='')
args = parser.parse_args()
if os.getuid() != 0:
print('sdc-firewall: error: must be run as root')
sys.exit(4)
# --nodaemon only valid with start action
if args.nodaemon and args.action != 'start':
print('sdc-firewall: error: --nodaemon option not valid with stop or restart action')
sys.exit(1)
# Read the local configuration file.
config = ClientConfiguration(args.config).read_config()
# Dump debug information
if args.debug:
node_info_dump(args)
if not config:
_logger.error('Invalid configuration file information, aborting.')
sys.exit(1)
# Do not fork the daemon process, run in foreground. For systemd service or debugging.
if args.nodaemon:
_daemon = SDCDaemon(args=args)
_daemon.run()
else:
# Setup daemon object
_daemon = SDCDaemon(
os.path.split(config.get('settings', 'pidfile'))[0],
'0o700',
os.path.split(config.get('settings', 'pidfile'))[1],
'root',
'root',
'/dev/null',
'/dev/null',
'/dev/null',
args=args
)
if args.action == 'start':
_logger.debug('Starting daemon.')
_daemon.start()
elif args.action == 'stop':
_logger.debug('Stopping daemon.')
_daemon.stop()
elif args.action == 'restart':
_logger.debug('Restarting daemon.')
_daemon.restart()
return 0
# --- Main Program Call ---
if __name__ == '__main__':
sys.exit(run())<|fim▁end|> | |
<|file_name|>ptr_in_fnptr.rs<|end_file_name|><|fim▁begin|>#[cxx::bridge]
mod ffi {
unsafe extern "C++" {
fn f(callback: fn(p: *const u8));<|fim▁hole|> }
}
fn main() {}<|fim▁end|> | |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>use ffmpeg::frame;
use openal::{Error, Listener};
use openal::source::{self, Stream};
use game::State;
use settings;
pub struct Sound<'a> {
settings: settings::Audio,
<|fim▁hole|> listener: Listener<'a>,
}
impl<'a> Sound<'a> {
pub fn new(settings: &settings::Audio) -> Result<Self, Error> {
Ok(Sound {
settings: settings.clone(),
music: None,
timestamp: -1,
listener: try!(Listener::default(&Default::default())),
})
}
pub fn play<'b>(&'b mut self, frame: &frame::Audio) {
if let None = self.music {
self.music = Some(self.listener.source().unwrap().stream());
}
if self.timestamp >= frame.timestamp().unwrap() {
return;
}
self.timestamp = frame.timestamp().unwrap();
if let Some(source) = self.music.as_mut() {
source.push(frame.channels(), frame.plane::<i16>(0), frame.rate()).unwrap();
if source.state() != source::State::Playing {
source.play();
}
}
}
pub fn render(&mut self, state: &State) {
}
}<|fim▁end|> | music: Option<Stream<'a>>,
timestamp: i64,
|
<|file_name|>extract_test_data.py<|end_file_name|><|fim▁begin|>import csv
import loremipsum
import random
import re
from encoded.loadxl import *
class Anonymizer(object):
"""Change email addresses and names consistently
"""
# From Colander. Not exhaustive, will not match .museum etc.
email_re = re.compile(r'(?i)[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}')
random_words = loremipsum._generator.words
def __init__(self):
self.mapped_emails = {}
self.mapped_names = {}
self.generated_emails = set()
self.generated_names = set()
def replace_emails(self, dictrows):
for row in dictrows:
for k, v in list(row.items()):
if v is None:
continue
new_value, num_subs = self.email_re.subn(
self._replace_emails, v)
row[k] = new_value
yield row
def replace_non_pi_names(self, dictrows):
for row in dictrows:
if row.get('job_title') != 'PI':
if 'first_name' in row:
row['first_name'] = random.choice(self.random_words).capitalize()
if 'last_name' in row:
row['last_name'] = self._random_name()
yield row
def _random_email(self):
for _ in range(1000):
generated = "%s.%s@%s.%s" % \
tuple(random.choice(self.random_words) for n in range(4))
if generated not in self.generated_emails:
self.generated_emails.add(generated)
return generated
raise AssertionError("Unable to find random email")
def _replace_emails(self, matchobj):
found = matchobj.group(0)
new, original = self.mapped_emails.get(found.lower(), (None, None))
if new is not None:
if found != original:
raise ValueError(
"Case mismatch for %s, %s" % (found, original))
return new
new = self._random_email()
self.mapped_emails[found.lower()] = (new, found)
return new
def _random_name(self):
for _ in range(1000):
if random.choice(range(4)):
generated = random.choice(self.random_words).capitalize()
else:
generated = "%s-%s" % \
tuple(random.choice(self.random_words).capitalize()
for n in range(2))
if generated not in self.generated_names:
self.generated_names.add(generated)
return generated
raise AssertionError("Unable to find random name")
def set_existing_key_value(**kw):
def component(dictrows):
for row in dictrows:
for k, v in kw.items():
if k in row:
row[k] = v
yield row
return component
def drop_rows_with_all_key_value(**kw):
def component(dictrows):
for row in dictrows:
if not all(row[k] == v if k in row else False for k, v in kw.items()):
yield row
return component
def extract_pipeline():
return [
skip_rows_with_all_falsey_value('test'),
skip_rows_with_all_key_value(test='skip'),
skip_rows_with_all_falsey_value('test'),
skip_rows_missing_all_keys('uuid'),
drop_rows_with_all_key_value(_skip=True),
]
def anon_pipeline():
anonymizer = Anonymizer()
return extract_pipeline() + [
set_existing_key_value(
fax='000-000-0000',
phone1='000-000-0000',
phone2='000-000-0000',
skype='skype',<|fim▁hole|> ),
anonymizer.replace_emails,
anonymizer.replace_non_pi_names,
]
def run(pipeline, inpath, outpath):
for item_type in ORDER:
source = read_single_sheet(inpath, item_type)
fieldnames = [k for k in source.fieldnames if ':ignore' not in k]
with open(os.path.join(outpath, item_type + '.tsv'), 'wb') as out:
writer = csv.DictWriter(out, fieldnames, dialect='excel-tab', extrasaction='ignore')
writer.writeheader()
writer.writerows(combine(source, pipeline))
def main():
import argparse
parser = argparse.ArgumentParser(description='Extract test data set.')
parser.add_argument('--anonymize', '-a', action="store_true",
help="anonymize the data.")
parser.add_argument('inpath',
help="input zip file of excel sheets.")
parser.add_argument('outpath',
help="directory to write filtered tsv files to.")
args = parser.parse_args()
pipeline = anon_pipeline() if args.anonymize else extract_pipeline()
import pdb
import sys
import traceback
try:
run(pipeline, args.inpath, args.outpath)
except:
type, value, tb = sys.exc_info()
traceback.print_exc()
pdb.post_mortem(tb)
if __name__ == '__main__':
main()<|fim▁end|> | google='google', |
<|file_name|>Gruntfile.js<|end_file_name|><|fim▁begin|>module.exports = function (grunt) {
var idVideo = 0;
var examples = require('./node_modules/grunt-json-mapreduce/examples');
var _ = require('underscore');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
cfg: {
paths: {
build: 'dist',
bower: 'bower_components',
npm: 'node_modules'
},
files: {
js: {
vendor: [
'<%= cfg.paths.npm %>/underscore/underscore.js',
'<%= cfg.paths.bower %>/angular/angular.js',
'<%= cfg.paths.bower %>/angular-mocks/angular-mocks.js',
'<%= cfg.paths.bower %>/angular-route/angular-route.js',
'<%= cfg.paths.bower %>/angular-slugify/angular-slugify.js',
'<%= cfg.paths.bower %>/angular-youtube-mb/src/angular-youtube-embed.js',
// '<%= cfg.paths.bower %>/angular-youtube-embed/dist/angular-youtube-embed.js',
// '<%= cfg.paths.bower %>/angular-youtube/angular-youtube-player-api.js',
'<%= cfg.paths.bower %>/jquery/dist/jquery.js',
'<%= cfg.paths.bower %>/bootstrap/dist/js/bootstrap.js'
],
mixins: [
'app/js/mixins/**/*.js'
],
app: [
'app/js/app.js', 'app/js/**/*.js', '!app/js/mock/*'
]
},
css: {
vendor: [
'<%= cfg.paths.bower %>/bootstrap/dist/css/bootstrap.css',
'<%= cfg.paths.bower %>/bootstrap/dist/css/bootstrap-theme.css'
],
app: [
'app/assets/css/**/*.css'
]
}
}
},
bump: {
options: {
files: ['package.json', 'bower.json'],
pushTo: 'origin',
commitFiles: ['-a']
}
},
clean: {<|fim▁hole|> build: ['<%= cfg.paths.build %>']
},
copy: {
static: {
files: [{
'<%= cfg.paths.build %>/index.html': 'app/index.html',
'<%= cfg.paths.build %>/favicon.png': 'app/assets/favicon.png'
}, {
expand: true,
cwd: 'app/templates/',
src: ["*.*", "**/*.*"],
dest: '<%= cfg.paths.build %>/templates'
}, {
expand: true,
cwd: 'app/assets/font/',
src: ["*.*", "**/*.*"],
dest: '<%= cfg.paths.build %>/font'
}
]
}
},
cssmin: {
vendor: {
files: {
'<%= cfg.paths.build %>/css/vendor.css': '<%= cfg.files.css.vendor %>'
}
},
app: {
files: {
'<%= cfg.paths.build %>/css/app.css': '<%= cfg.files.css.app %>'
}
}
},
uglify: {
options: {
mangle: false
},
vendor: {
files: {
'<%= cfg.paths.build %>/js/vendor.js': '<%= cfg.files.js.vendor %>'
}
},
mixins: {
files: {
'<%= cfg.paths.build %>/js/mixins.js': '<%= cfg.files.js.mixins %>'
}
},
app: {
files: {
'<%= cfg.paths.build %>/js/app.js': '<%= cfg.files.js.app %>'
}
}
},
json_mapreduce: {
events: {
src: ['data/events/**/*.json'],
dest: '<%= cfg.paths.build %>/data/events.json',
options: {
map: examples.map.pass,
reduce: examples.reduce.concat
}
},
videos: {
src: ['data/videos/**/*.json'],
dest: '<%= cfg.paths.build %>/data/videos.json',
options: {
map: function (currentValue, index, array) {
return currentValue.map(function (element) {
element.id = ++idVideo;
return element;
});
},
reduce: examples.reduce.concat
}
},
speakers: {
src: ['data/speakers/**/*.json'],
dest: '<%= cfg.paths.build %>/data/speakers.json',
options: {
map: examples.map.pass,
reduce: examples.reduce.concat
}
},
tags: {
src: ['data/videos/**/*.json'],
dest: '<%= cfg.paths.build %>/data/tags.json',
options: {
map: function (currentValue, index, array) {
var tagLists = currentValue.map(function (element) {
return element.tags;
});
return _.union.apply(this, tagLists);
},
reduce: function(previousValue, currentValue, index, array) {
if (typeof previousValue === "undefined") {
return currentValue;
} else {
return _.union(previousValue, currentValue);
}
}
}
}
},
browserify: {
app: {
src: ['./app/js/mock/index.js'],
dest: '<%= cfg.paths.build %>/js/mock.js'
}
},
'http-server': {
dist: {
root: 'dist',
host: '0.0.0.0',
port: '9000'
}
},
jsonlint: {
data: {
src: ['data/**/*.json']
}
},
jshint: {
options: {
jshintrc: true
},
app: {
src: ['app/js/**/*.js']
}
}
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('test', [
'jshint',
'jsonlint'
]);
grunt.registerTask('build', [
'clean',
'copy',
'cssmin',
'uglify'
]);
grunt.registerTask('mock', [
'json_mapreduce',
'browserify'
]);
grunt.registerTask('run', [
'http-server'
]);
grunt.registerTask('default', [
'test',
'build',
'mock',
]);
};<|fim▁end|> | |
<|file_name|>ppsspp_zh-cn.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="zh_CN">
<context>
<name>Controls</name>
<message>
<source>Controls</source>
<comment>Controls window title</comment>
<translation type="obsolete">控制器</translation>
</message>
</context>
<context>
<name>CtrlDisAsmView</name>
<message>
<location filename="../Debugger/ctrldisasmview.cpp" line="91"/>
<source>Copy &address</source>
<translation>(&A)复制地址</translation>
</message>
<message>
<location filename="../Debugger/ctrldisasmview.cpp" line="95"/>
<source>Copy instruction (&hex)</source>
<translation>(&H)复制指令(十六进制型)</translation>
</message>
<message>
<location filename="../Debugger/ctrldisasmview.cpp" line="99"/>
<source>Copy instruction (&disasm)</source>
<translation>(&D)复制指令(汇编型)</translation>
</message>
<message>
<location filename="../Debugger/ctrldisasmview.cpp" line="105"/>
<source>&Run to here</source>
<translation>(&R)执行到此处</translation>
</message>
<message>
<location filename="../Debugger/ctrldisasmview.cpp" line="109"/>
<source>&Set Next Statement</source>
<translation>(&S)设置下一语句</translation>
</message>
<message>
<location filename="../Debugger/ctrldisasmview.cpp" line="113"/>
<source>&Toggle breakpoint</source>
<translation>(&T)锁定断点</translation>
</message>
<message>
<location filename="../Debugger/ctrldisasmview.cpp" line="117"/>
<source>&Follow branch</source>
<translation>(&F)跟随分支</translation>
</message>
<message>
<location filename="../Debugger/ctrldisasmview.cpp" line="127"/>
<source>Go to in &Memory View</source>
<translation>(&M)转到内存视图</translation>
</message>
<message>
<location filename="../Debugger/ctrldisasmview.cpp" line="137"/>
<source>&Rename function...</source>
<translation>(&R)重命名函数...</translation>
</message>
<message>
<location filename="../Debugger/ctrldisasmview.cpp" line="208"/>
<source>New function name</source>
<translation>新函数名称</translation>
</message>
<message>
<location filename="../Debugger/ctrldisasmview.cpp" line="209"/>
<source>New function name:</source>
<translation>新函数名称:</translation>
</message>
<message>
<location filename="../Debugger/ctrldisasmview.cpp" line="220"/>
<source>Warning</source>
<translation>警告</translation>
</message>
<message>
<location filename="../Debugger/ctrldisasmview.cpp" line="220"/>
<source>No symbol selected</source>
<translation>没有选择象征</translation>
</message>
</context>
<context>
<name>CtrlMemView</name>
<message>
<location filename="../Debugger/ctrlmemview.cpp" line="205"/>
<source>Go to in &disasm</source>
<translation>(&D)转到汇编视图</translation>
</message>
<message>
<location filename="../Debugger/ctrlmemview.cpp" line="211"/>
<source>&Copy value</source>
<translation>(&C)复制值</translation>
</message>
<message>
<location filename="../Debugger/ctrlmemview.cpp" line="215"/>
<source>C&hange value</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/ctrlmemview.cpp" line="219"/>
<source>Dump...</source>
<translation>转储...</translation>
</message>
<message>
<location filename="../Debugger/ctrlmemview.cpp" line="242"/>
<source>Set new value</source>
<translation type="unfinished">设置新值</translation>
</message>
<message>
<location filename="../Debugger/ctrlmemview.cpp" line="243"/>
<source>Set new value:</source>
<translation type="unfinished">设置新值:</translation>
</message>
</context>
<context>
<name>CtrlRegisterList</name>
<message>
<location filename="../Debugger/ctrlregisterlist.cpp" line="260"/>
<source>Go to in &memory view</source>
<translation>(&M)转到内存视图</translation>
</message>
<message>
<location filename="../Debugger/ctrlregisterlist.cpp" line="264"/>
<source>Go to in &disasm</source>
<translation>(&D)转到汇编视图</translation>
</message>
<message>
<location filename="../Debugger/ctrlregisterlist.cpp" line="270"/>
<source>&Copy value</source>
<translation>(&C)复制值</translation>
</message>
<message>
<location filename="../Debugger/ctrlregisterlist.cpp" line="274"/>
<source>C&hange...</source>
<translation>(&H)更改...</translation>
</message>
<message>
<location filename="../Debugger/ctrlregisterlist.cpp" line="327"/>
<source>Set new value</source>
<translation>设置新值</translation>
</message>
<message>
<location filename="../Debugger/ctrlregisterlist.cpp" line="328"/>
<source>Set new value:</source>
<translation>设置新值:</translation>
</message>
</context>
<context>
<name>Debugger_Disasm</name>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="17"/>
<source>Disassembler</source>
<comment>Window title</comment>
<translation>反汇编器</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="30"/>
<source>Ctr:</source>
<translation>计数器:</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="43"/>
<source>&Go to</source>
<translation>(&G)转到</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="78"/>
<source>&PC</source>
<translation>(&P)PC寄存器</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="91"/>
<source>&LR</source>
<translation>(&L)连接寄存器</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="128"/>
<source>Show VFPU</source>
<translation>显示VFPU</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="147"/>
<source>Regs</source>
<translation>寄存器</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="198"/>
<source>Funcs</source>
<translation>函数</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="223"/>
<source>&Go</source>
<translation>(&G)转到</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="236"/>
<source>Stop</source>
<translation>停止</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="249"/>
<source>Step &Into</source>
<translation>(&I)单步跟进</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="265"/>
<source>Step &Over</source>
<translation>(&O)单步步过</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="278"/>
<source>S&kip</source>
<translation>(&K)跳过</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="291"/>
<source>Next &HLE</source>
<translation>(&H)下一HLE</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="320"/>
<source>Breakpoints</source>
<translation>断点</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="339"/>
<source>Address</source>
<translation>地址</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="362"/>
<source>Clear All</source>
<translation>清空所有</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="372"/>
<source>Callstack</source>
<translation>调用栈</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="382"/>
<source>Display Lists</source>
<translation>显示列表</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="408"/>
<location filename="../Debugger/debugger_disasm.ui" line="455"/>
<source>Id</source>
<translation>Id</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="413"/>
<location filename="../Debugger/debugger_disasm.ui" line="465"/>
<source>Status</source>
<translation>状态</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="418"/>
<source>Start Address</source>
<translation>起始地址</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="423"/>
<source>Current Address</source>
<translation>当前地址</translation>
</message>
<message>
<source>Run</source>
<translation type="obsolete">执行</translation>
</message>
<message>
<source>Step</source>
<translation type="obsolete">单步执行</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="433"/>
<source>Threads</source>
<translation>线程</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="460"/>
<source>Name</source>
<translation>名称</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="470"/>
<source>Current PC</source>
<translation>当前PC寄存器</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.ui" line="475"/>
<source>Entry point</source>
<translation>入口点</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.cpp" line="367"/>
<source>Remove breakpoint</source>
<translation>移除断点</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.cpp" line="443"/>
<source>Go to entry point</source>
<translation>转到入口点</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.cpp" line="447"/>
<source>Change status</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.cpp" line="449"/>
<source>Running</source>
<translation>执行中</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.cpp" line="453"/>
<source>Wait</source>
<translation>等待</translation>
</message>
<message>
<location filename="../Debugger/debugger_disasm.cpp" line="457"/>
<source>Suspend</source>
<translation>挂起</translation>
</message>
<message>
<source>Show code</source>
<translation type="obsolete">显示代码</translation>
</message>
</context>
<context>
<name>Debugger_DisplayList</name>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="14"/>
<source>Dialog</source>
<translation type="unfinished">对话框</translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="28"/>
<source>DisplayList</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="50"/>
<source>Id</source>
<translation type="unfinished">Id</translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="55"/>
<source>Status</source>
<translation type="unfinished">状态</translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="60"/>
<source>Start Address</source>
<translation type="unfinished">起始地址</translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="65"/>
<source>Current Address</source>
<translation type="unfinished">当前地址</translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="75"/>
<source>Run</source>
<translation type="unfinished">执行</translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="82"/>
<source>Stop</source>
<translation type="unfinished">停止</translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="89"/>
<source>Next DL</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="116"/>
<source>Commands</source>
<translation type="unfinished"></translation><|fim▁hole|> <translation type="unfinished">单步执行</translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="163"/>
<source>Next Draw</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="170"/>
<source>Goto PC</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="193"/>
<source>Textures</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="203"/>
<location filename="../Debugger/debugger_displaylist.ui" line="294"/>
<source>Address</source>
<translation type="unfinished">地址</translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="208"/>
<location filename="../Debugger/debugger_displaylist.ui" line="421"/>
<source>Width</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="213"/>
<location filename="../Debugger/debugger_displaylist.ui" line="426"/>
<source>Height</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="218"/>
<location filename="../Debugger/debugger_displaylist.ui" line="431"/>
<source>Format</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="227"/>
<source>Vertex Buffer</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="242"/>
<source>Coord Type</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="247"/>
<source>Number Morph</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="252"/>
<source>Number Weights</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="257"/>
<source>Has Weight</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="262"/>
<source>Has Position</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="267"/>
<source>Has Normal</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="272"/>
<source>Has Color</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="277"/>
<source>Has UV</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="299"/>
<source>Values</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="309"/>
<location filename="../Debugger/debugger_displaylist.ui" line="374"/>
<source>Next 20</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="332"/>
<source>Index Buffer</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="353"/>
<source>Idx</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="363"/>
<source>Value</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="399"/>
<source>Framebuffer</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="416"/>
<source>VAddress</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="478"/>
<source>Display : </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="486"/>
<source>Color</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="491"/>
<source>Depth</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="512"/>
<source>Zoom-</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="519"/>
<source>Zoom+</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.cpp" line="1773"/>
<source>Run to here</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_displaylist.cpp" line="1797"/>
<source>Run to draw using this texture</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Debugger_Memory</name>
<message>
<location filename="../Debugger/debugger_memory.ui" line="14"/>
<source>Dialog</source>
<translation>对话框</translation>
</message>
<message>
<location filename="../Debugger/debugger_memory.ui" line="22"/>
<source>Goto:</source>
<translation>转到:</translation>
</message>
<message>
<location filename="../Debugger/debugger_memory.ui" line="35"/>
<source>Mode</source>
<translation>模式</translation>
</message>
<message>
<location filename="../Debugger/debugger_memory.ui" line="41"/>
<source>Normal</source>
<translation>普通模式</translation>
</message>
<message>
<location filename="../Debugger/debugger_memory.ui" line="48"/>
<source>Symbols</source>
<translation>特征符模式</translation>
</message>
<message>
<location filename="../Debugger/debugger_memory.cpp" line="14"/>
<source>Memory Viewer - %1</source>
<translation>内存查看器 - %1</translation>
</message>
</context>
<context>
<name>Debugger_MemoryTex</name>
<message>
<location filename="../Debugger/debugger_memorytex.ui" line="14"/>
<source>Dialog</source>
<translation type="unfinished">对话框</translation>
</message>
<message>
<location filename="../Debugger/debugger_memorytex.ui" line="29"/>
<source>TexAddr</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_memorytex.ui" line="36"/>
<source>TexBufWidth0</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_memorytex.ui" line="43"/>
<source>TexFormat</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_memorytex.ui" line="50"/>
<source>TexSize</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_memorytex.ui" line="57"/>
<source>ClutFormat</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_memorytex.ui" line="64"/>
<source>ClutAddr</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_memorytex.ui" line="71"/>
<source>ClutAddrUpper</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_memorytex.ui" line="78"/>
<source>LoadClut</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_memorytex.ui" line="109"/>
<source>TexMode</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../Debugger/debugger_memorytex.ui" line="123"/>
<source>Read</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Debugger_VFPU</name>
<message>
<location filename="../Debugger/debugger_vfpu.ui" line="14"/>
<source>VFPU</source>
<translation>VFPU</translation>
</message>
<message>
<location filename="../Debugger/debugger_vfpu.ui" line="23"/>
<source>Float</source>
<translation>浮点型</translation>
</message>
<message>
<location filename="../Debugger/debugger_vfpu.ui" line="28"/>
<source>HalfFloat</source>
<translation>半浮点型</translation>
</message>
<message>
<location filename="../Debugger/debugger_vfpu.ui" line="33"/>
<source>Hex</source>
<translation>十六进制型</translation>
</message>
<message>
<location filename="../Debugger/debugger_vfpu.ui" line="38"/>
<source>Bytes</source>
<translation>字节型</translation>
</message>
<message>
<location filename="../Debugger/debugger_vfpu.ui" line="43"/>
<source>Shorts</source>
<translation>短整型</translation>
</message>
<message>
<location filename="../Debugger/debugger_vfpu.ui" line="48"/>
<source>Ints</source>
<translation>整型</translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<source>PPSSPP</source>
<translation type="obsolete">PPSSPP</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="460"/>
<source>&File</source>
<translation>(&F)文件</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="466"/>
<source>Quickload State</source>
<translation>快速负载态</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="468"/>
<source>Quicksave State</source>
<translation>快速保存态</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="478"/>
<source>&Emulation</source>
<translation>(&E)模拟</translation>
</message>
<message>
<source>Debu&g</source>
<translation type="obsolete">(&G)调试</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="513"/>
<source>&Options</source>
<translation>(&O)选项</translation>
</message>
<message>
<source>Default</source>
<translation type="obsolete">默认</translation>
</message>
<message>
<source>Lo&g Levels</source>
<translation type="obsolete">(&G)日志级别</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="579"/>
<source>&Language</source>
<translation>(&L)语言选择</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="525"/>
<source>&Video</source>
<translation>(&V)视频</translation>
</message>
<message>
<source>&Anisotropic filtering</source>
<translation type="obsolete">(&A)各向异性过滤</translation>
</message>
<message>
<source>&Zoom</source>
<translation type="obsolete">(&Z)缩放</translation>
</message>
<message>
<source>Co&ntrols</source>
<translation type="obsolete">(&N)控制</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="515"/>
<source>&Core</source>
<translation>(&C)核心</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="522"/>
<source>&Ignore Illegal reads/writes</source>
<translation>忽略非法读取/写入</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="620"/>
<source>&Help</source>
<translation>(&H)帮助</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="461"/>
<source>&Open...</source>
<translation>(&O)打开...</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="463"/>
<source>&Close</source>
<translation>(&C)关闭</translation>
</message>
<message>
<source>-</source>
<translation type="obsolete">-</translation>
</message>
<message>
<source>Quickload state</source>
<translation type="obsolete">快速读档</translation>
</message>
<message>
<source>F4</source>
<translation type="obsolete">F4</translation>
</message>
<message>
<source>Quicksave state</source>
<translation type="obsolete">快速存档</translation>
</message>
<message>
<source>F2</source>
<translation type="obsolete">F2</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="470"/>
<source>&Load State File...</source>
<translation>(&L)读取存档...</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="472"/>
<source>&Save State File...</source>
<translation>(&S)保存存档...</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="475"/>
<source>E&xit</source>
<translation>(&X)退出</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="479"/>
<source>&Run</source>
<translation>(&R)运行</translation>
</message>
<message>
<source>F7</source>
<translation type="obsolete">F7</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="481"/>
<source>&Pause</source>
<translation>(&P)暂停</translation>
</message>
<message>
<source>F8</source>
<translation type="obsolete">F8</translation>
</message>
<message>
<source>R&eset</source>
<translation type="obsolete">(&E)重置</translation>
</message>
<message>
<source>&Interpreter</source>
<translation type="obsolete">(&I)解释器</translation>
</message>
<message>
<source>&Slightly Faster Interpreter</source>
<translation type="obsolete">(&S)较快的解释器</translation>
</message>
<message>
<source>&Dynarec</source>
<translation type="obsolete">(&D)动态重编译</translation>
</message>
<message>
<source>Load &Map File...</source>
<translation type="obsolete">(&M)读取Map文件...</translation>
</message>
<message>
<source>&Save Map File...</source>
<translation type="obsolete">(&S)保存Map文件...</translation>
</message>
<message>
<source>&Reset Symbol Table</source>
<translation type="obsolete">(&R)重置符号表</translation>
</message>
<message>
<source>&Disassembly</source>
<translation type="obsolete">(&D)汇编视图</translation>
</message>
<message>
<source>Ctrl+D</source>
<translation type="obsolete">Ctrl+D</translation>
</message>
<message>
<source>&Log Console</source>
<translation type="obsolete">(&L)查看控制台日志</translation>
</message>
<message>
<source>Ctrl+L</source>
<translation type="obsolete">Ctrl+L</translation>
</message>
<message>
<source>Memory &View...</source>
<translation type="obsolete">(&V)内存视图...</translation>
</message>
<message>
<source>Ctrl+M</source>
<translation type="obsolete">Ctrl+M</translation>
</message>
<message>
<source>&Keyboard</source>
<translation type="obsolete">(&K)键盘</translation>
</message>
<message>
<source>&Toggle fullscreen</source>
<translation type="obsolete">(&T)全屏</translation>
</message>
<message>
<source>Show &debug statistics</source>
<translation type="obsolete">(&D)显示调试信息</translation>
</message>
<message>
<source>I&gnore illegal reads/writes</source>
<translation type="obsolete">(&G)忽略非法读写</translation>
</message>
<message>
<source>&Gamepad</source>
<translation type="obsolete">(&G)手柄</translation>
</message>
<message>
<source>Run on loa&d</source>
<translation type="obsolete">(&D)载入时运行</translation>
</message>
<message>
<source>Show &FPS counter</source>
<translation type="obsolete">(&F)显示帧率计数器</translation>
</message>
<message>
<source>S&tretch to display</source>
<translation type="obsolete">(&T)拉伸显示</translation>
</message>
<message>
<source>&Sound emulation</source>
<translation type="obsolete">(&S)模拟声音</translation>
</message>
<message>
<source>F11</source>
<translation type="obsolete">F11</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="532"/>
<source>&Buffered Rendering</source>
<translation>(&B)渲染缓冲</translation>
</message>
<message>
<source>F5</source>
<translation type="obsolete">F5</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="547"/>
<source>&Hardware Transform</source>
<translation>(&H)硬件加速</translation>
</message>
<message>
<source>F6</source>
<translation type="obsolete">F6</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="534"/>
<source>&Linear Filtering</source>
<translation>(&L)线性过滤</translation>
</message>
<message>
<source>&Wireframe (experimental)</source>
<translation type="obsolete">(&W)使用线框 (实验性选项)</translation>
</message>
<message>
<source>&Display Raw Framebuffer</source>
<translation type="obsolete">(&D)显示 Raw 原始缓冲</translation>
</message>
<message>
<source>Screen &1x</source>
<translation type="obsolete">&1倍窗口</translation>
</message>
<message>
<source>Ctrl+1</source>
<translation type="obsolete">Ctrl+1</translation>
</message>
<message>
<source>Screen &2x</source>
<translation type="obsolete">&2倍窗口</translation>
</message>
<message>
<source>Ctrl+2</source>
<translation type="obsolete">Ctrl+2</translation>
</message>
<message>
<source>Screen &3x</source>
<translation type="obsolete">&3倍窗口</translation>
</message>
<message>
<source>Ctrl+3</source>
<translation type="obsolete">Ctrl+3</translation>
</message>
<message>
<source>Screen &4x</source>
<translation type="obsolete">&4倍窗口</translation>
</message>
<message>
<source>Ctrl+4</source>
<translation type="obsolete">Ctrl+4</translation>
</message>
<message>
<source>&Fast Memory (dynarec, unstable)</source>
<translation type="obsolete">(&F)高速闪存 (动态重编译,不稳定)</translation>
</message>
<message>
<source>&Go to http://www.ppsspp.org/</source>
<translation type="obsolete">(&G)转到 http://www.ppsspp.org/</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="622"/>
<source>&About PPSSPP...</source>
<translation>(&A)关于 PPSSPP...</translation>
</message>
<message>
<source>&Use VBO</source>
<translation type="obsolete">(&U)使用 VBO</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="483"/>
<source>Re&set</source>
<translation>(&R)复位</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="486"/>
<source>Run on &load</source>
<translation>加载时执行</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="490"/>
<source>De&bug</source>
<translation>调试</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="491"/>
<source>Load Map File...</source>
<translation>载入地图文件</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="493"/>
<source>Save Map File...</source>
<translation>保存地图文件</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="495"/>
<source>Reset Symbol Table</source>
<translation>重置符号表</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="498"/>
<source>Dump next frame to log</source>
<translation>将下一帧转储至日志</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="501"/>
<source>Disassembly</source>
<translation>汇编视图</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="503"/>
<source>Display List...</source>
<translation>显示列表...</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="505"/>
<source>Log Console</source>
<translation>查看控制台日志</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="507"/>
<source>Memory View</source>
<translation>内存视图</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="509"/>
<source>Memory View Texture</source>
<translation>内存纹理视图</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="516"/>
<source>&CPU Dynarec</source>
<translation>(&D)动态重编译</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="518"/>
<source>&Vertex Decoder Dynarec</source>
<translation>顶点解码器动态重编译</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="520"/>
<source>Fast &Memory (unstable)</source>
<translation>(&F)高速闪存 (动态重编译,不稳定)</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="527"/>
<source>&Anisotropic Filtering</source>
<translation>(&A)各向异性过滤</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="538"/>
<source>&Screen Size</source>
<translation>屏幕尺寸</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="544"/>
<source>&Stretch to Display</source>
<translation>(&T)拉伸显示</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="549"/>
<source>&Vertex Cache</source>
<translation>(&V)顶点缓存</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="551"/>
<source>&Frameskip</source>
<translation>(&F)跳帧</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="553"/>
<source>&Audio</source>
<translation>(&S)声响</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="556"/>
<source>&Fullscreen</source>
<translation>(&F)全屏</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="558"/>
<source>&Show debug statistics</source>
<translation>(&D)显示调试信息</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="560"/>
<source>&Show FPS</source>
<translation>(&F)显示帧率计数器</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="564"/>
<source>Lo&g levels</source>
<translation>(&G)日志级别</translation>
</message>
<message>
<source>Debug</source>
<translation type="obsolete">调试</translation>
</message>
<message>
<source>Warning</source>
<translation type="obsolete">警告</translation>
</message>
<message>
<source>Error</source>
<translation type="obsolete">错误</translation>
</message>
<message>
<source>Info</source>
<translation type="obsolete">信息</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="621"/>
<source>&Go to official website</source>
<translation>(&G)进入官方网站</translation>
</message>
<message>
<source>D&ump next frame to log</source>
<translation type="obsolete">(&U)将下一帧转储至日志</translation>
</message>
<message>
<source>Memory View Texture...</source>
<translation type="obsolete">内存纹理视图...</translation>
</message>
<message>
<source>Off</source>
<translation type="obsolete">关闭</translation>
</message>
</context>
</TS><|fim▁end|> | </message>
<message>
<location filename="../Debugger/debugger_displaylist.ui" line="156"/>
<source>Step</source> |
<|file_name|>selectors.test.ts<|end_file_name|><|fim▁begin|>import { extractPartsFromPath } from './selectors';
describe('router/selectors', () => {
describe('extractPartsFromPath', () => {
it('return pathName, query and parse store data from window.location', () => {
const store = { useHash: false } as any;<|fim▁hole|> const results = extractPartsFromPath(store);
expect(results).toEqual({
pathName: '/page1',
query: 'queryParam=queryValue&a[]=1&a[]=2',
storeData: {
counter: { value: 1 },
counter2: { value: 2 },
},
});
});
it('passes url through serializers', () => {
const serializers = new Map([
[
'counter',
{
toUrlValue: (value) => value,
fromUrlValue: (counter) => {
counter.value *= 2;
return counter;
},
},
],
]);
const store = { useHash: false, serializers } as any;
const results = extractPartsFromPath(store);
expect(results).toEqual({
pathName: '/page1',
query: 'queryParam=queryValue&a[]=1&a[]=2',
storeData: {
counter: { value: 2 },
counter2: { value: 2 },
},
});
});
it('parses window.hash if store.useHash is true', () => {
const store = { useHash: true } as any;
window.location.hash = '#page1';
const results = extractPartsFromPath(store);
expect(results).toEqual({
pathName: '/page1',
query: '',
storeData: {},
});
});
it('returns an empty object if the store is badly formed', () => {
const store = { useHash: true } as any;
window.location.hash = '#?storeData={';
expect(extractPartsFromPath(store)).toEqual({
pathName: '/',
query: '',
storeData: {},
});
});
it('returns an empty object if the no store is found', () => {
const store = { useHash: true } as any;
window.location.hash = '#?a=1';
expect(extractPartsFromPath(store)).toEqual({
pathName: '/',
query: 'a=1',
storeData: {},
});
});
it('pathName defaults to / when useHash is true', () => {
history.pushState(null, null, 'http://example.com');
const store = { useHash: true } as any;
const results = extractPartsFromPath(store);
expect(results).toEqual({
pathName: '/',
query: '',
storeData: {},
});
});
});
});<|fim▁end|> | |
<|file_name|>issue-3683.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Foo {
fn a(&self) -> int;
fn b(&self) -> int {
self.a() + 2
}
}
impl Foo for int {
fn a(&self) -> int {<|fim▁hole|> 3
}
}
pub fn main() {
assert_eq!(3.b(), 5);
}<|fim▁end|> | |
<|file_name|>bot.py<|end_file_name|><|fim▁begin|>#-*- coding: utf- -*-
import os
import sys
import random
import time
import json
import wikiquote
import tuitear
from threading import Thread
CONGIG_JSON = 'bots.json'
# Variable local, para modificar el intervalo real cambiar la configuración
INTERVALO = 1<|fim▁hole|>
stop = False
def start_bot(bot):
""" Hilo que inicia el bot pasado como argumento (diccionario) """
citas = []
for pagina in bot['paginas']:
print 'Cargando', pagina
quotes = wikiquote.get_quotes(pagina.encode('utf8'))
quotes = [(q, pagina) for q in quotes]
citas += quotes
tiempo = 0
while not stop:
if tiempo >= bot['intervalo']:
quote, pagina = random.choice(citas)
tweet = bot['format'].encode('utf8') % dict(pagina = \
pagina.encode('utf8'), frase = quote.encode('utf8'))
if len(tweet) > 138:
#print 'tweet largo'
continue
print "%s: %s" % (bot['name'], tweet.decode('utf8'))
tuitear.tuitear(tweet, bot['consumer_key'], bot['consumer_secret'],
bot['access_token'], bot['access_token_secret'])
tiempo = 0
tiempo += INTERVALO
time.sleep(INTERVALO)
print 'Thread para', bot['name'], 'detenido'
def main():
path = os.path.dirname(__file__)
if len(sys.argv) == 2:
filename = sys.argv[1]
else:
filename = os.path.join(path, CONGIG_JSON)
print 'Cargando bots en', filename
j = json.load(file(filename))
for bot in j['bots']:
if bot.get('disabled'):
continue
thread = Thread(target = start_bot, args=[bot])
thread.daemon = True
thread.start()
print 'Thread para', bot['name'], 'iniciado'
while True:
# Para que no terminen los hilos
pass
if __name__ == '__main__':
main()<|fim▁end|> | |
<|file_name|>passability.py<|end_file_name|><|fim▁begin|># Passability types.
#
# @author Oktay Acikalin <[email protected]>
# @copyright Oktay Acikalin
# @license MIT (LICENSE.txt)
# from json import load
from collections import OrderedDict
# from os.path import splitext, dirname, join
from os.path import dirname, join<|fim▁hole|>
# locals().update(load(open('%s.json' % splitext(__file__)[0], 'rb'), object_pairs_hook=OrderedDict))
# filename = join(dirname(__file__), filename)
filename = join(dirname(__file__), 'passability.png')
# Replace all tiles in map and just use the definitions below.
sprites = OrderedDict((
('wall', {'none': [[[0, 0, 16, 16], [0, 0], [0, 0], 60]]}),
('platform', {'none': [[[48, 0, 16, 16], [48, 0], [0, 0], 60]]}),
('climb_platform', {'none': [[[16, 0, 16, 16], [16, 0], [0, 0], 60]]}),
('climb', {'none': [[[32, 0, 16, 16], [32, 0], [0, 0], 60]]}),
))
tile_size = [16, 16]<|fim▁end|> | |
<|file_name|>config.rs<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | pub const MEMORY_REGIONS_MAX: usize = 8; |
<|file_name|>LogbackServiceLogEventAppenderTest.java<|end_file_name|><|fim▁begin|>/*
* Copyright to the original author or 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<|fim▁hole|> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.rioproject.test.log;
import org.junit.runner.RunWith;
import org.rioproject.test.RioTestRunner;
/**
* Tests ServiceEventLog notifications using logback
*
* @author Dennis Reedy
*/
@RunWith(RioTestRunner.class)
public class LogbackServiceLogEventAppenderTest extends BaseServiceEventLogTest {
}<|fim▁end|> | * distributed under the License is distributed on an "AS IS" BASIS, |
<|file_name|>0005_parentrelation_signature.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [<|fim▁hole|> migrations.AddField(
model_name='parentrelation',
name='signature',
field=models.CharField(max_length=255, null=True, verbose_name='sig', blank=True),
preserve_default=True,
),
]<|fim▁end|> | ('users', '0004_auto_20150428_2142'),
]
operations = [ |
<|file_name|>Location.java<|end_file_name|><|fim▁begin|>package grid;
import java.util.Comparator;
import world.World;
/*
* AP(r) Computer Science GridWorld Case Study:
* Copyright(c) 2002-2006 College Entrance Examination Board
* (http://www.collegeboard.com).
*
* This code 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.
*
* This code 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.
*
* @author Alyce Brady
* @author Chris Nevison
* @author APCS Development Committee
* @author Cay Horstmann
*/
/**
* A <code>Location</code> object represents the row and column of a location
* in a two-dimensional grid. <br />
* The API of this class is testable on the AP CS A and AB exams.
*/
public class Location implements Comparable
{
private int row; // row location in grid
private int col; // column location in grid
/**
* The turn angle for turning 90 degrees to the left.
*/
public static final int LEFT = -90;
/**
* The turn angle for turning 90 degrees to the right.
*/
public static final int RIGHT = 90;
/**
* The turn angle for turning 45 degrees to the left.
*/
public static final int HALF_LEFT = -45;
/**
* The turn angle for turning 45 degrees to the right.
*/
public static final int HALF_RIGHT = 45;
/**
* The turn angle for turning a full circle.
*/
public static final int FULL_CIRCLE = 360;
/**
* The turn angle for turning a half circle.
*/
public static final int HALF_CIRCLE = 180;
/**
* The turn angle for making no turn.
*/
public static final int AHEAD = 0;
/**
* The compass direction for north.
*/
public static final int NORTH = 0;
/**
* The compass direction for northeast.
*/
public static final int NORTHEAST = 45;
/**
* The compass direction for east.
*/
public static final int EAST = 90;
/**
* The compass direction for southeast.
*/
public static final int SOUTHEAST = 135;
/**
* The compass direction for south.
*/
public static final int SOUTH = 180;
/**
* The compass direction for southwest.
*/
public static final int SOUTHWEST = 225;
/**
* The compass direction for west.
*/
public static final int WEST = 270;
/**
* The compass direction for northwest.
*/
public static final int NORTHWEST = 315;
/**
* Constructs a location with given row and column coordinates.
* @param r the row
* @param c the column
*/
public Location(int r, int c)
{
row = r;
col = c;
}
/**
* Gets the row coordinate.
* @return the row of this location
*/
public int getRow()
{
return row;
}
/**
* Gets the column coordinate.
* @return the column of this location
*/
public int getCol()
{
return col;
}
/**
* Gets the adjacent location in any one of the eight compass directions.
* @param direction the direction in which to find a neighbor location
* @return the adjacent location in the direction that is closest to
* <tt>direction</tt>
*/
public Location getAdjacentLocation(int direction)
{
// reduce mod 360 and round to closest multiple of 45
int adjustedDirection = (direction + HALF_RIGHT / 2) % FULL_CIRCLE;
if (adjustedDirection < 0)
adjustedDirection += FULL_CIRCLE;
adjustedDirection = (adjustedDirection / HALF_RIGHT) * HALF_RIGHT;
int dc = 0;
int dr = 0;
if (adjustedDirection == EAST)
dc = 1;
else if (adjustedDirection == SOUTHEAST)
{
dc = 1;<|fim▁hole|> dr = 1;
else if (adjustedDirection == SOUTHWEST)
{
dc = -1;
dr = 1;
}
else if (adjustedDirection == WEST)
dc = -1;
else if (adjustedDirection == NORTHWEST)
{
dc = -1;
dr = -1;
}
else if (adjustedDirection == NORTH)
dr = -1;
else if (adjustedDirection == NORTHEAST)
{
dc = 1;
dr = -1;
}
return new Location(getRow() + dr, getCol() + dc);
}
/**
* Returns the direction from this location toward another location. The
* direction is rounded to the nearest compass direction.
* @param target a location that is different from this location
* @return the closest compass direction from this location toward
* <code>target</code>
*/
public int getDirectionToward(Location target)
{
int dx = target.getCol() - getCol();
int dy = target.getRow() - getRow();
// y axis points opposite to mathematical orientation
int angle = (int) Math.toDegrees(Math.atan2(-dy, dx));
// mathematical angle is counterclockwise from x-axis,
// compass angle is clockwise from y-axis
int compassAngle = RIGHT - angle;
// prepare for truncating division by 45 degrees
compassAngle += HALF_RIGHT / 2;
// wrap negative angles
if (compassAngle < 0)
compassAngle += FULL_CIRCLE;
// round to nearest multiple of 45
return (compassAngle / HALF_RIGHT) * HALF_RIGHT;
}
/**
* Indicates whether some other <code>Location</code> object is "equal to"
* this one.
* @param other the other location to test
* @return <code>true</code> if <code>other</code> is a
* <code>Location</code> with the same row and column as this location;
* <code>false</code> otherwise
*/
public boolean equals(Object other)
{
if (!(other instanceof Location))
return false;
Location otherLoc = (Location) other;
return getRow() == otherLoc.getRow() && getCol() == otherLoc.getCol();
}
/**
* Generates a hash code.
* @return a hash code for this location
*/
public int hashCode()
{
return getRow() * 3737 + getCol();
}
/**
* Compares this location to <code>other</code> for ordering. Returns a
* negative integer, zero, or a positive integer as this location is less
* than, equal to, or greater than <code>other</code>. Locations are
* ordered in row-major order. <br />
* (Precondition: <code>other</code> is a <code>Location</code> object.)
* @param other the other location to test
* @return a negative integer if this location is less than
* <code>other</code>, zero if the two locations are equal, or a positive
* integer if this location is greater than <code>other</code>
*/
public int compareTo(Object other)
{
Location otherLoc = (Location) other;
if (getRow() < otherLoc.getRow())
return -1;
if (getRow() > otherLoc.getRow())
return 1;
if (getCol() < otherLoc.getCol())
return -1;
if (getCol() > otherLoc.getCol())
return 1;
return 0;
}
/**
* (Added for RatBots) Calculates the distance to another location.
* The distance is reported as the sum of the x and y distances
* and therefore doesn't consider diagonal movement.
* @param other the location that the distance is calculated to
* @return the distance
*/
public int distanceTo(Location other)
{
int dx = Math.abs(row - other.getRow());
int dy = Math.abs(col - other.getCol());
return dx+dy;
}
public boolean isValidLocation()
{
if(this.getRow() < 0 || this.getRow() >= World.DEFAULT_ROWS)
return false;
if(this.getCol() < 0 || this.getCol() >= World.DEFAULT_COLS)
return false;
return true;
}
/**
* Creates a string that describes this location.
* @return a string with the row and column of this location, in the format
* (row, col)
*/
public String toString()
{
return "(r:" + getRow() + ", c:" + getCol() + ")";
}
}<|fim▁end|> | dr = 1;
}
else if (adjustedDirection == SOUTH) |
<|file_name|>numpy-examples.py<|end_file_name|><|fim▁begin|>import numpy as np
# Inner (or dot) product
a = np.array([1,2])
b = np.array([3,4])
np.inner(a, b)
a.dot(b)
# Outer product
a = np.array([1,2])
b = np.array([3,4])
np.outer(a, b)
# Inverse
m = np.array([[1,2], [3,4]])
np.linalg.inv(m)
# Inner (or dot) product
m = np.array([[1,2], [3,4]])
minv = np.linalg.inv(m)
m.dot(minv)
# Diagonal
m = np.array([[1,2], [3,4]])
np.diag(m)
m = np.array([1,2])
np.diag(m)
# Determinant
m = np.array([[1,2], [3,4]])
np.linalg.det(m)
# Trace - sum of elements of the diagonal
m = np.array([[1,2], [3,4]])
np.diag(m)
np.diag(m).sum()
np.trace(m)
# Transpose
m = np.array([ [1,2], [3,4] ])
m.T
# Gaussian distribution
m = np.random.randn(2,3)
m
<|fim▁hole|>
# Eigen vectors and values
# For symmetric matrix (m == m.T) and hermitian matrix (m = m.H) we use eigh.
m = np.array([
[ 0.89761228, 0.00538701, -0.03229084],
[ 0.00538701, 1.04860676, -0.25001666],
[-0.03229084, -0.25001666, 0.81116126]])
# The first tuple contains three Eigen values.
# The second tuple contains Eigen vectors stored in columns.
np.linalg.eigh(m)
# Solving linear systems
# The admissions fee at a small far is $1.50 for children an $4.00 for adults.
# On a certain day 2,200 people enter the fair and $5050 is collected.
# How many children and how many adults attended.
#
# Let X1 = number of children
# Let X2 = number of adults
# X1 + X2 = 2200
# 1.5X1 + 4X2 = 5050
a = np.array([ [1,1], [1.5,4] ])
b = np.array( [ 2200, 5050] )
np.linalg.solve(a, b)<|fim▁end|> | # Covariance
X = np.random.randn(100,3)
np.cov(X.T) |
<|file_name|>sistema.js<|end_file_name|><|fim▁begin|>/**
*<|fim▁hole|>});
/*
* Función que permite bloquear la pantalla mientras esta procesando
*/
$(function () {
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
});
/*
* Función que bloquea la tecla F5 y Enter de la pagina y detectar tecla arriba y abajo
*/
$(function () {
$(document).keydown(function (e) {
if ($('#formulario\\:menu').length) {
var code = (e.keyCode ? e.keyCode : e.which);
//if(code == 116 || code == 13) {
if (code == 13) {
e.preventDefault();
}
if (code == 40) {
teclaAbajo();
e.preventDefault();
}
if (code == 38) {
teclaArriba();
e.preventDefault();
}
}
});
});
/*
*Función Desabilitar el clik derecho
*/
//$(function() {
// $(document).ready(function(){
// $(document).bind("contextmenu",function(e){
// return false;
// });
// });
//});
/*
* Funcion que calcula y asigna el ancho y el alto del navegador
*/
function dimiensionesNavegador() {
var na = $(window).height();
document.getElementById('formulario:alto').value = na;
var ancho = $(window).width();
document.getElementById('formulario:ancho').value = ancho;
}
/*
* Funcion que calcula y asigna el ancho y el alto disponible sin la barra de menu
*/
function dimensionesDisponibles() {
var na = $(window).height();
var me = $('#formulario\\:menu').height();
var alto = na - me - 45;
alto = parseInt(alto);
document.getElementById('formulario:ith_alto').value = alto;
document.getElementById('formulario:alto').value = na;
var ancho = $(window).width();
document.getElementById('formulario:ancho').value = ancho;
}
/*
* Para poner los calendarios, las horas en español
*/
PrimeFaces.locales['es'] = {
closeText: 'Cerrar',
prevText: 'Anterior',
nextText: 'Siguiente',
monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab'],
dayNamesMin: ['D', 'L', 'M', 'M', 'J', 'V', 'S'],
weekHeader: 'Semana',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: '',
timeOnlyTitle: 'Sólo hora',
timeText: 'Tiempo',
hourText: 'Hora',
minuteText: 'Minuto',
secondText: 'Segundo',
currentText: 'Hora actual',
ampm: false,
month: 'Mes',
week: 'Semana',
day: 'Día',
allDayText: 'Todo el día'
};
function abrirPopUp(dir) {
var w = window.open(dir, "sistemadj", "width=" + screen.availWidth + ", height=" + screen.availHeight + ", screenX=0,screenY=0, top=0, left=0, status=0 , resizable=yes, scrollbars=yes");
w.focus();
}
function abrirNuevoPopUp(dir) {
var w = window.open(dir, "", "width=" + screen.availWidth + ", height=" + screen.availHeight + ", screenX=0,screenY=0, top=0, left=0, status=0 , resizable=yes, scrollbars=yes");
w.focus();
}<|fim▁end|> | * @author xedushx
*/
$(document).bind("touchmove", function (event) {
event.preventDefault(); |
<|file_name|>water-triple-ind.py<|end_file_name|><|fim▁begin|>from gen import *
##########
# shared #
##########
flow_var[0] = """
(declare-fun tau () Real)
(declare-fun x1 () Real)
(declare-fun x2 () Real)
(declare-fun x3 () Real)
"""
flow_dec[0] = """
(define-ode flow_1 ((= d/dt[x1] (/ (- 5 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (^ x1 0.5))) 2))
(= d/dt[x2] (/ (+ 3 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x1 0.5) (^ x2 0.5)))) 4))
(= d/dt[x3] (/ (+ 4 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x2 0.5) (^ x3 0.5)))) 3))
(= d/dt[tau] 1)))
(define-ode flow_2 ((= d/dt[x1] (/ (- 5 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (^ x1 0.5))) 2))
(= d/dt[x2] (/ (+ 3 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x1 0.5) (^ x2 0.5)))) 4))
(= d/dt[x3] (/ (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x2 0.5) (^ x3 0.5))) 3))
(= d/dt[tau] 1)))
(define-ode flow_3 ((= d/dt[x1] (/ (- 5 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (^ x1 0.5))) 2))
(= d/dt[x2] (/ (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x1 0.5) (^ x2 0.5))) 4))
(= d/dt[x3] (/ (+ 4 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x2 0.5) (^ x3 0.5)))) 3))
(= d/dt[tau] 1)))
(define-ode flow_4 ((= d/dt[x1] (/ (- 5 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (^ x1 0.5))) 2))
(= d/dt[x2] (/ (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x1 0.5) (^ x2 0.5))) 4))
(= d/dt[x3] (/ (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x2 0.5) (^ x3 0.5))) 3))
(= d/dt[tau] 1)))
(define-ode flow_5 ((= d/dt[x1] (/ (* (* -0.5 (^ (* 2 9.80665) 0.5)) (^ x1 0.5)) 2))
(= d/dt[x2] (/ (+ 3 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x1 0.5) (^ x2 0.5)))) 4))
(= d/dt[x3] (/ (+ 4 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x2 0.5) (^ x3 0.5)))) 3))
(= d/dt[tau] 1)))
(define-ode flow_6 ((= d/dt[x1] (/ (* (* -0.5 (^ (* 2 9.80665) 0.5)) (^ x1 0.5)) 2))
(= d/dt[x2] (/ (+ 3 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x1 0.5) (^ x2 0.5)))) 4))
(= d/dt[x3] (/ (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x2 0.5) (^ x3 0.5))) 3))
(= d/dt[tau] 1)))
(define-ode flow_7 ((= d/dt[x1] (/ (* (* -0.5 (^ (* 2 9.80665) 0.5)) (^ x1 0.5)) 2))
(= d/dt[x2] (/ (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x1 0.5) (^ x2 0.5))) 4))
(= d/dt[x3] (/ (+ 4 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x2 0.5) (^ x3 0.5)))) 3))
(= d/dt[tau] 1)))
(define-ode flow_8 ((= d/dt[x1] (/ (* (* -0.5 (^ (* 2 9.80665) 0.5)) (^ x1 0.5)) 2))
(= d/dt[x2] (/ (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x1 0.5) (^ x2 0.5))) 4))
(= d/dt[x3] (/ (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x2 0.5) (^ x3 0.5))) 3))
(= d/dt[tau] 1)))
"""
state_dec[0] = """
(declare-fun time_{0} () Real)
(declare-fun tau_{0}_0 () Real)
(declare-fun tau_{0}_t () Real)
(declare-fun mode1_{0} () Bool)
(declare-fun x1_{0}_0 () Real)
(declare-fun x1_{0}_t () Real)
(declare-fun mode2_{0} () Bool)
(declare-fun x2_{0}_0 () Real)
(declare-fun x2_{0}_t () Real)
(declare-fun mode3_{0} () Bool)
(declare-fun x3_{0}_0 () Real)
(declare-fun x3_{0}_t () Real)
"""
state_val[0] = """
(assert (<= 0 time_{0})) (assert (<= time_{0} 1))
(assert (<= 0 tau_{0}_0)) (assert (<= tau_{0}_0 1))
(assert (<= 0 tau_{0}_t)) (assert (<= tau_{0}_t 1))
(assert (<= 0 x1_{0}_0)) (assert (<= x1_{0}_0 10))
(assert (<= 0 x1_{0}_t)) (assert (<= x1_{0}_t 10))
(assert (<= 0 x2_{0}_0)) (assert (<= x2_{0}_0 10))
(assert (<= 0 x2_{0}_t)) (assert (<= x2_{0}_t 10))
(assert (<= 0 x3_{0}_0)) (assert (<= x3_{0}_0 10))
(assert (<= 0 x3_{0}_t)) (assert (<= x3_{0}_t 10))
"""
cont_cond[0] = ["""
(assert (and (>= tau_{0}_0 0) (<= tau_{0}_0 1)
(>= tau_{0}_t 0) (<= tau_{0}_t 1)
(forall_t 1 [0 time_{0}] (>= tau_{0}_t 0))
(forall_t 2 [0 time_{0}] (<= tau_{0}_t 1))))
(assert (or (and (= mode1_{0} true) (= mode2_{0} true) (= mode3_{0} true)
(= [x1_{0}_t x2_{0}_t x3_{0}_t tau_{0}_t]
(integral 0. time_{0} [x1_{0}_0 x2_{0}_0 x3_{0}_0 tau_{0}_0] flow_1)))
(and (= mode1_{0} true) (= mode2_{0} true) (= mode3_{0} false)
(= [x1_{0}_t x2_{0}_t x3_{0}_t tau_{0}_t]
(integral 0. time_{0} [x1_{0}_0 x2_{0}_0 x3_{0}_0 tau_{0}_0] flow_2)))
(and (= mode1_{0} true) (= mode2_{0} false) (= mode3_{0} true)
(= [x1_{0}_t x2_{0}_t x3_{0}_t tau_{0}_t]
(integral 0. time_{0} [x1_{0}_0 x2_{0}_0 x3_{0}_0 tau_{0}_0] flow_3)))
(and (= mode1_{0} true) (= mode2_{0} false) (= mode3_{0} false)
(= [x1_{0}_t x2_{0}_t x3_{0}_t tau_{0}_t]
(integral 0. time_{0} [x1_{0}_0 x2_{0}_0 x3_{0}_0 tau_{0}_0] flow_4)))
(and (= mode1_{0} false) (= mode2_{0} true) (= mode3_{0} true)
(= [x1_{0}_t x2_{0}_t x3_{0}_t tau_{0}_t]
(integral 0. time_{0} [x1_{0}_0 x2_{0}_0 x3_{0}_0 tau_{0}_0] flow_5)))
(and (= mode1_{0} false) (= mode2_{0} true) (= mode3_{0} false)
(= [x1_{0}_t x2_{0}_t x3_{0}_t tau_{0}_t]
(integral 0. time_{0} [x1_{0}_0 x2_{0}_0 x3_{0}_0 tau_{0}_0] flow_6)))
(and (= mode1_{0} false) (= mode2_{0} false) (= mode3_{0} true)
(= [x1_{0}_t x2_{0}_t x3_{0}_t tau_{0}_t]
(integral 0. time_{0} [x1_{0}_0 x2_{0}_0 x3_{0}_0 tau_{0}_0] flow_7)))
(and (= mode1_{0} false) (= mode2_{0} false) (= mode3_{0} false)
(= [x1_{0}_t x2_{0}_t x3_{0}_t tau_{0}_t]
(integral 0. time_{0} [x1_{0}_0 x2_{0}_0 x3_{0}_0 tau_{0}_0] flow_8)))))"""]
jump_cond[0] = ["""
(assert (and (= tau_{0}_t 1) (= tau_{1}_0 0)))
(assert (and (= x1_{1}_0 x1_{0}_t)))
(assert (or (and (< x1_{0}_t 5) (= mode1_{1} true))
(and (>= x1_{0}_t 5) (= mode1_{1} false))))
(assert (and (= x2_{1}_0 x2_{0}_t)))
(assert (or (and (< x2_{0}_t 5) (= mode2_{1} true))
(and (>= x2_{0}_t 5) (= mode2_{1} false))))
(assert (and (= x3_{1}_0 x3_{0}_t)))
(assert (or (and (< x3_{0}_t 5) (= mode3_{1} true))
(and (>= x3_{0}_t 5) (= mode3_{1} false))))"""]
#############
# Init/Goal #
#############
init_cond = """
(assert (< 0.99 tau_{0}_0))
(assert
(and (> x1_{0}_0 (- 5 4)) (< x1_{0}_0 (+ 5 4))
(> x2_{0}_0 (- 5 4)) (< x2_{0}_0 (+ 5 4))
(> x3_{0}_0 (- 5 4)) (< x3_{0}_0 (+ 5 4))))
"""
goal_cond = """
(assert (< 0.99 tau_{0}_t))
(assert (not
(and (> x1_{0}_t (- 5 4)) (< x1_{0}_t (+ 5 4))
(> x2_{0}_t (- 5 4)) (< x2_{0}_t (+ 5 4))
(> x3_{0}_t (- 5 4)) (< x3_{0}_t (+ 5 4)))))<|fim▁hole|>"""
import sys
try:
bound = int(sys.argv[1])
except:
print("Usage:", sys.argv[0], "<Bound>")
else:
generate(bound, 1, [0], 0, init_cond, goal_cond)<|fim▁end|> | |
<|file_name|>test_shutil.py<|end_file_name|><|fim▁begin|># Copyright (C) 2003 Python Software Foundation
import unittest
import shutil
import tempfile
import sys
import stat
import os
import os.path
from os.path import splitdrive
from distutils.spawn import find_executable, spawn
from shutil import (_make_tarball, _make_zipfile, make_archive,
register_archive_format, unregister_archive_format,
get_archive_formats)
import tarfile
import warnings
from test import test_support
from test.test_support import TESTFN, check_warnings, captured_stdout
TESTFN2 = TESTFN + "2"
try:
import grp
import pwd
UID_GID_SUPPORT = True
except ImportError:
UID_GID_SUPPORT = False
try:
import zlib
except ImportError:
zlib = None
try:
import zipfile
ZIP_SUPPORT = True
except ImportError:
ZIP_SUPPORT = find_executable('zip')
class TestShutil(unittest.TestCase):
def setUp(self):
super(TestShutil, self).setUp()
self.tempdirs = []
def tearDown(self):
super(TestShutil, self).tearDown()
while self.tempdirs:
d = self.tempdirs.pop()
shutil.rmtree(d, os.name in ('nt', 'cygwin'))
def write_file(self, path, content='xxx'):
"""Writes a file in the given path.
path can be a string or a sequence.
"""
if isinstance(path, (list, tuple)):
path = os.path.join(*path)
f = open(path, 'w')
try:
f.write(content)
finally:
f.close()
def mkdtemp(self):
"""Create a temporary directory that will be cleaned up.
Returns the path of the directory.
"""
d = tempfile.mkdtemp()
self.tempdirs.append(d)
return d
def test_rmtree_errors(self):
# filename is guaranteed not to exist
filename = tempfile.mktemp()
self.assertRaises(OSError, shutil.rmtree, filename)
# See bug #1071513 for why we don't run this on cygwin
# and bug #1076467 for why we don't run this as root.
if (hasattr(os, 'chmod') and sys.platform[:6] != 'cygwin'
and not (hasattr(os, 'geteuid') and os.geteuid() == 0)):
def test_on_error(self):
self.errorState = 0
os.mkdir(TESTFN)
self.childpath = os.path.join(TESTFN, 'a')
f = open(self.childpath, 'w')
f.close()
old_dir_mode = os.stat(TESTFN).st_mode
old_child_mode = os.stat(self.childpath).st_mode
# Make unwritable.
os.chmod(self.childpath, stat.S_IREAD)
os.chmod(TESTFN, stat.S_IREAD)
shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror)
# Test whether onerror has actually been called.
self.assertEqual(self.errorState, 2,
"Expected call to onerror function did not happen.")
# Make writable again.
os.chmod(TESTFN, old_dir_mode)
os.chmod(self.childpath, old_child_mode)
# Clean up.
shutil.rmtree(TESTFN)
def check_args_to_onerror(self, func, arg, exc):
# test_rmtree_errors deliberately runs rmtree
# on a directory that is chmod 400, which will fail.
# This function is run when shutil.rmtree fails.
# 99.9% of the time it initially fails to remove
# a file in the directory, so the first time through
# func is os.remove.
# However, some Linux machines running ZFS on
# FUSE experienced a failure earlier in the process
# at os.listdir. The first failure may legally
# be either.
if self.errorState == 0:
if func is os.remove:
self.assertEqual(arg, self.childpath)
else:
self.assertIs(func, os.listdir,
"func must be either os.remove or os.listdir")
self.assertEqual(arg, TESTFN)
self.assertTrue(issubclass(exc[0], OSError))
self.errorState = 1
else:
self.assertEqual(func, os.rmdir)
self.assertEqual(arg, TESTFN)
self.assertTrue(issubclass(exc[0], OSError))
self.errorState = 2
def test_rmtree_dont_delete_file(self):
# When called on a file instead of a directory, don't delete it.
handle, path = tempfile.mkstemp()
os.fdopen(handle).close()
self.assertRaises(OSError, shutil.rmtree, path)
os.remove(path)
def test_copytree_simple(self):
def write_data(path, data):
f = open(path, "w")
f.write(data)
f.close()
def read_data(path):
f = open(path)
data = f.read()
f.close()
return data
src_dir = tempfile.mkdtemp()
dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
write_data(os.path.join(src_dir, 'test.txt'), '123')
os.mkdir(os.path.join(src_dir, 'test_dir'))
write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
try:
shutil.copytree(src_dir, dst_dir)
self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
'test.txt')))
actual = read_data(os.path.join(dst_dir, 'test.txt'))
self.assertEqual(actual, '123')
actual = read_data(os.path.join(dst_dir, 'test_dir', 'test.txt'))
self.assertEqual(actual, '456')
finally:
for path in (
os.path.join(src_dir, 'test.txt'),
os.path.join(dst_dir, 'test.txt'),
os.path.join(src_dir, 'test_dir', 'test.txt'),
os.path.join(dst_dir, 'test_dir', 'test.txt'),
):
if os.path.exists(path):
os.remove(path)
for path in (src_dir,
os.path.dirname(dst_dir)
):
if os.path.exists(path):
shutil.rmtree(path)
def test_copytree_with_exclude(self):
def write_data(path, data):
f = open(path, "w")
f.write(data)
f.close()
def read_data(path):
f = open(path)
data = f.read()
f.close()
return data
# creating data
join = os.path.join
exists = os.path.exists
src_dir = tempfile.mkdtemp()
try:
dst_dir = join(tempfile.mkdtemp(), 'destination')
write_data(join(src_dir, 'test.txt'), '123')
write_data(join(src_dir, 'test.tmp'), '123')
os.mkdir(join(src_dir, 'test_dir'))
write_data(join(src_dir, 'test_dir', 'test.txt'), '456')
os.mkdir(join(src_dir, 'test_dir2'))
write_data(join(src_dir, 'test_dir2', 'test.txt'), '456')
os.mkdir(join(src_dir, 'test_dir2', 'subdir'))
os.mkdir(join(src_dir, 'test_dir2', 'subdir2'))
write_data(join(src_dir, 'test_dir2', 'subdir', 'test.txt'), '456')
write_data(join(src_dir, 'test_dir2', 'subdir2', 'test.py'), '456')
# testing glob-like patterns
try:
patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
shutil.copytree(src_dir, dst_dir, ignore=patterns)
# checking the result: some elements should not be copied
self.assertTrue(exists(join(dst_dir, 'test.txt')))
self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
self.assertTrue(not exists(join(dst_dir, 'test_dir2')))
finally:
if os.path.exists(dst_dir):
shutil.rmtree(dst_dir)
try:
patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
shutil.copytree(src_dir, dst_dir, ignore=patterns)
# checking the result: some elements should not be copied
self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2')))
self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
finally:
if os.path.exists(dst_dir):
shutil.rmtree(dst_dir)
# testing callable-style
try:
def _filter(src, names):
res = []
for name in names:
path = os.path.join(src, name)
if (os.path.isdir(path) and
path.split()[-1] == 'subdir'):
res.append(name)
elif os.path.splitext(path)[-1] in ('.py'):
res.append(name)
return res
shutil.copytree(src_dir, dst_dir, ignore=_filter)
# checking the result: some elements should not be copied
self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2',
'test.py')))
self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
finally:
if os.path.exists(dst_dir):
shutil.rmtree(dst_dir)
<|fim▁hole|>
if hasattr(os, "symlink"):
def test_dont_copy_file_onto_link_to_itself(self):
# bug 851123.
os.mkdir(TESTFN)
src = os.path.join(TESTFN, 'cheese')
dst = os.path.join(TESTFN, 'shop')
try:
f = open(src, 'w')
f.write('cheddar')
f.close()
os.link(src, dst)
self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
with open(src, 'r') as f:
self.assertEqual(f.read(), 'cheddar')
os.remove(dst)
# Using `src` here would mean we end up with a symlink pointing
# to TESTFN/TESTFN/cheese, while it should point at
# TESTFN/cheese.
os.symlink('cheese', dst)
self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
with open(src, 'r') as f:
self.assertEqual(f.read(), 'cheddar')
os.remove(dst)
finally:
try:
shutil.rmtree(TESTFN)
except OSError:
pass
def test_rmtree_on_symlink(self):
# bug 1669.
os.mkdir(TESTFN)
try:
src = os.path.join(TESTFN, 'cheese')
dst = os.path.join(TESTFN, 'shop')
os.mkdir(src)
os.symlink(src, dst)
self.assertRaises(OSError, shutil.rmtree, dst)
finally:
shutil.rmtree(TESTFN, ignore_errors=True)
if hasattr(os, "mkfifo"):
# Issue #3002: copyfile and copytree block indefinitely on named pipes
def test_copyfile_named_pipe(self):
os.mkfifo(TESTFN)
try:
self.assertRaises(shutil.SpecialFileError,
shutil.copyfile, TESTFN, TESTFN2)
self.assertRaises(shutil.SpecialFileError,
shutil.copyfile, __file__, TESTFN)
finally:
os.remove(TESTFN)
def test_copytree_named_pipe(self):
os.mkdir(TESTFN)
try:
subdir = os.path.join(TESTFN, "subdir")
os.mkdir(subdir)
pipe = os.path.join(subdir, "mypipe")
os.mkfifo(pipe)
try:
shutil.copytree(TESTFN, TESTFN2)
except shutil.Error as e:
errors = e.args[0]
self.assertEqual(len(errors), 1)
src, dst, error_msg = errors[0]
self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
else:
self.fail("shutil.Error should have been raised")
finally:
shutil.rmtree(TESTFN, ignore_errors=True)
shutil.rmtree(TESTFN2, ignore_errors=True)
@unittest.skipUnless(zlib, "requires zlib")
def test_make_tarball(self):
# creating something to tar
tmpdir = self.mkdtemp()
self.write_file([tmpdir, 'file1'], 'xxx')
self.write_file([tmpdir, 'file2'], 'xxx')
os.mkdir(os.path.join(tmpdir, 'sub'))
self.write_file([tmpdir, 'sub', 'file3'], 'xxx')
tmpdir2 = self.mkdtemp()
unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
"source and target should be on same drive")
base_name = os.path.join(tmpdir2, 'archive')
# working with relative paths to avoid tar warnings
old_dir = os.getcwd()
os.chdir(tmpdir)
try:
_make_tarball(splitdrive(base_name)[1], '.')
finally:
os.chdir(old_dir)
# check if the compressed tarball was created
tarball = base_name + '.tar.gz'
self.assertTrue(os.path.exists(tarball))
# trying an uncompressed one
base_name = os.path.join(tmpdir2, 'archive')
old_dir = os.getcwd()
os.chdir(tmpdir)
try:
_make_tarball(splitdrive(base_name)[1], '.', compress=None)
finally:
os.chdir(old_dir)
tarball = base_name + '.tar'
self.assertTrue(os.path.exists(tarball))
def _tarinfo(self, path):
tar = tarfile.open(path)
try:
names = tar.getnames()
names.sort()
return tuple(names)
finally:
tar.close()
def _create_files(self):
# creating something to tar
tmpdir = self.mkdtemp()
dist = os.path.join(tmpdir, 'dist')
os.mkdir(dist)
self.write_file([dist, 'file1'], 'xxx')
self.write_file([dist, 'file2'], 'xxx')
os.mkdir(os.path.join(dist, 'sub'))
self.write_file([dist, 'sub', 'file3'], 'xxx')
os.mkdir(os.path.join(dist, 'sub2'))
tmpdir2 = self.mkdtemp()
base_name = os.path.join(tmpdir2, 'archive')
return tmpdir, tmpdir2, base_name
@unittest.skipUnless(zlib, "Requires zlib")
@unittest.skipUnless(find_executable('tar') and find_executable('gzip'),
'Need the tar command to run')
def test_tarfile_vs_tar(self):
tmpdir, tmpdir2, base_name = self._create_files()
old_dir = os.getcwd()
os.chdir(tmpdir)
try:
_make_tarball(base_name, 'dist')
finally:
os.chdir(old_dir)
# check if the compressed tarball was created
tarball = base_name + '.tar.gz'
self.assertTrue(os.path.exists(tarball))
# now create another tarball using `tar`
tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
gzip_cmd = ['gzip', '-f9', 'archive2.tar']
old_dir = os.getcwd()
os.chdir(tmpdir)
try:
with captured_stdout() as s:
spawn(tar_cmd)
spawn(gzip_cmd)
finally:
os.chdir(old_dir)
self.assertTrue(os.path.exists(tarball2))
# let's compare both tarballs
self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
# trying an uncompressed one
base_name = os.path.join(tmpdir2, 'archive')
old_dir = os.getcwd()
os.chdir(tmpdir)
try:
_make_tarball(base_name, 'dist', compress=None)
finally:
os.chdir(old_dir)
tarball = base_name + '.tar'
self.assertTrue(os.path.exists(tarball))
# now for a dry_run
base_name = os.path.join(tmpdir2, 'archive')
old_dir = os.getcwd()
os.chdir(tmpdir)
try:
_make_tarball(base_name, 'dist', compress=None, dry_run=True)
finally:
os.chdir(old_dir)
tarball = base_name + '.tar'
self.assertTrue(os.path.exists(tarball))
@unittest.skipUnless(zlib, "Requires zlib")
@unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
def test_make_zipfile(self):
# creating something to tar
tmpdir = self.mkdtemp()
self.write_file([tmpdir, 'file1'], 'xxx')
self.write_file([tmpdir, 'file2'], 'xxx')
tmpdir2 = self.mkdtemp()
base_name = os.path.join(tmpdir2, 'archive')
_make_zipfile(base_name, tmpdir)
# check if the compressed tarball was created
tarball = base_name + '.zip'
self.assertTrue(os.path.exists(tarball))
def test_make_archive(self):
tmpdir = self.mkdtemp()
base_name = os.path.join(tmpdir, 'archive')
self.assertRaises(ValueError, make_archive, base_name, 'xxx')
@unittest.skipUnless(zlib, "Requires zlib")
def test_make_archive_owner_group(self):
# testing make_archive with owner and group, with various combinations
# this works even if there's not gid/uid support
if UID_GID_SUPPORT:
group = grp.getgrgid(0)[0]
owner = pwd.getpwuid(0)[0]
else:
group = owner = 'root'
base_dir, root_dir, base_name = self._create_files()
base_name = os.path.join(self.mkdtemp() , 'archive')
res = make_archive(base_name, 'zip', root_dir, base_dir, owner=owner,
group=group)
self.assertTrue(os.path.exists(res))
res = make_archive(base_name, 'zip', root_dir, base_dir)
self.assertTrue(os.path.exists(res))
res = make_archive(base_name, 'tar', root_dir, base_dir,
owner=owner, group=group)
self.assertTrue(os.path.exists(res))
res = make_archive(base_name, 'tar', root_dir, base_dir,
owner='kjhkjhkjg', group='oihohoh')
self.assertTrue(os.path.exists(res))
@unittest.skipUnless(zlib, "Requires zlib")
@unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
def test_tarfile_root_owner(self):
tmpdir, tmpdir2, base_name = self._create_files()
old_dir = os.getcwd()
os.chdir(tmpdir)
group = grp.getgrgid(0)[0]
owner = pwd.getpwuid(0)[0]
try:
archive_name = _make_tarball(base_name, 'dist', compress=None,
owner=owner, group=group)
finally:
os.chdir(old_dir)
# check if the compressed tarball was created
self.assertTrue(os.path.exists(archive_name))
# now checks the rights
archive = tarfile.open(archive_name)
try:
for member in archive.getmembers():
self.assertEqual(member.uid, 0)
self.assertEqual(member.gid, 0)
finally:
archive.close()
def test_make_archive_cwd(self):
current_dir = os.getcwd()
def _breaks(*args, **kw):
raise RuntimeError()
register_archive_format('xxx', _breaks, [], 'xxx file')
try:
try:
make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
except Exception:
pass
self.assertEqual(os.getcwd(), current_dir)
finally:
unregister_archive_format('xxx')
def test_register_archive_format(self):
self.assertRaises(TypeError, register_archive_format, 'xxx', 1)
self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
1)
self.assertRaises(TypeError, register_archive_format, 'xxx', lambda: x,
[(1, 2), (1, 2, 3)])
register_archive_format('xxx', lambda: x, [(1, 2)], 'xxx file')
formats = [name for name, params in get_archive_formats()]
self.assertIn('xxx', formats)
unregister_archive_format('xxx')
formats = [name for name, params in get_archive_formats()]
self.assertNotIn('xxx', formats)
class TestMove(unittest.TestCase):
def setUp(self):
filename = "foo"
self.src_dir = tempfile.mkdtemp()
self.dst_dir = tempfile.mkdtemp()
self.src_file = os.path.join(self.src_dir, filename)
self.dst_file = os.path.join(self.dst_dir, filename)
# Try to create a dir in the current directory, hoping that it is
# not located on the same filesystem as the system tmp dir.
try:
self.dir_other_fs = tempfile.mkdtemp(
dir=os.path.dirname(__file__))
self.file_other_fs = os.path.join(self.dir_other_fs,
filename)
except OSError:
self.dir_other_fs = None
with open(self.src_file, "wb") as f:
f.write("spam")
def tearDown(self):
for d in (self.src_dir, self.dst_dir, self.dir_other_fs):
try:
if d:
shutil.rmtree(d)
except:
pass
def _check_move_file(self, src, dst, real_dst):
with open(src, "rb") as f:
contents = f.read()
shutil.move(src, dst)
with open(real_dst, "rb") as f:
self.assertEqual(contents, f.read())
self.assertFalse(os.path.exists(src))
def _check_move_dir(self, src, dst, real_dst):
contents = sorted(os.listdir(src))
shutil.move(src, dst)
self.assertEqual(contents, sorted(os.listdir(real_dst)))
self.assertFalse(os.path.exists(src))
def test_move_file(self):
# Move a file to another location on the same filesystem.
self._check_move_file(self.src_file, self.dst_file, self.dst_file)
def test_move_file_to_dir(self):
# Move a file inside an existing dir on the same filesystem.
self._check_move_file(self.src_file, self.dst_dir, self.dst_file)
def test_move_file_other_fs(self):
# Move a file to an existing dir on another filesystem.
if not self.dir_other_fs:
# skip
return
self._check_move_file(self.src_file, self.file_other_fs,
self.file_other_fs)
def test_move_file_to_dir_other_fs(self):
# Move a file to another location on another filesystem.
if not self.dir_other_fs:
# skip
return
self._check_move_file(self.src_file, self.dir_other_fs,
self.file_other_fs)
def test_move_dir(self):
# Move a dir to another location on the same filesystem.
dst_dir = tempfile.mktemp()
try:
self._check_move_dir(self.src_dir, dst_dir, dst_dir)
finally:
try:
shutil.rmtree(dst_dir)
except:
pass
def test_move_dir_other_fs(self):
# Move a dir to another location on another filesystem.
if not self.dir_other_fs:
# skip
return
dst_dir = tempfile.mktemp(dir=self.dir_other_fs)
try:
self._check_move_dir(self.src_dir, dst_dir, dst_dir)
finally:
try:
shutil.rmtree(dst_dir)
except:
pass
def test_move_dir_to_dir(self):
# Move a dir inside an existing dir on the same filesystem.
self._check_move_dir(self.src_dir, self.dst_dir,
os.path.join(self.dst_dir, os.path.basename(self.src_dir)))
def test_move_dir_to_dir_other_fs(self):
# Move a dir inside an existing dir on another filesystem.
if not self.dir_other_fs:
# skip
return
self._check_move_dir(self.src_dir, self.dir_other_fs,
os.path.join(self.dir_other_fs, os.path.basename(self.src_dir)))
def test_existing_file_inside_dest_dir(self):
# A file with the same name inside the destination dir already exists.
with open(self.dst_file, "wb"):
pass
self.assertRaises(shutil.Error, shutil.move, self.src_file, self.dst_dir)
def test_dont_move_dir_in_itself(self):
# Moving a dir inside itself raises an Error.
dst = os.path.join(self.src_dir, "bar")
self.assertRaises(shutil.Error, shutil.move, self.src_dir, dst)
def test_destinsrc_false_negative(self):
os.mkdir(TESTFN)
try:
for src, dst in [('srcdir', 'srcdir/dest')]:
src = os.path.join(TESTFN, src)
dst = os.path.join(TESTFN, dst)
self.assertTrue(shutil._destinsrc(src, dst),
msg='_destinsrc() wrongly concluded that '
'dst (%s) is not in src (%s)' % (dst, src))
finally:
shutil.rmtree(TESTFN, ignore_errors=True)
def test_destinsrc_false_positive(self):
os.mkdir(TESTFN)
try:
for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
src = os.path.join(TESTFN, src)
dst = os.path.join(TESTFN, dst)
self.assertFalse(shutil._destinsrc(src, dst),
msg='_destinsrc() wrongly concluded that '
'dst (%s) is in src (%s)' % (dst, src))
finally:
shutil.rmtree(TESTFN, ignore_errors=True)
class TestCopyFile(unittest.TestCase):
_delete = False
class Faux(object):
_entered = False
_exited_with = None
_raised = False
def __init__(self, raise_in_exit=False, suppress_at_exit=True):
self._raise_in_exit = raise_in_exit
self._suppress_at_exit = suppress_at_exit
def read(self, *args):
return ''
def __enter__(self):
self._entered = True
def __exit__(self, exc_type, exc_val, exc_tb):
self._exited_with = exc_type, exc_val, exc_tb
if self._raise_in_exit:
self._raised = True
raise IOError("Cannot close")
return self._suppress_at_exit
def tearDown(self):
if self._delete:
del shutil.open
def _set_shutil_open(self, func):
shutil.open = func
self._delete = True
def test_w_source_open_fails(self):
def _open(filename, mode='r'):
if filename == 'srcfile':
raise IOError('Cannot open "srcfile"')
assert 0 # shouldn't reach here.
self._set_shutil_open(_open)
self.assertRaises(IOError, shutil.copyfile, 'srcfile', 'destfile')
def test_w_dest_open_fails(self):
srcfile = self.Faux()
def _open(filename, mode='r'):
if filename == 'srcfile':
return srcfile
if filename == 'destfile':
raise IOError('Cannot open "destfile"')
assert 0 # shouldn't reach here.
self._set_shutil_open(_open)
shutil.copyfile('srcfile', 'destfile')
self.assertTrue(srcfile._entered)
self.assertTrue(srcfile._exited_with[0] is IOError)
self.assertEqual(srcfile._exited_with[1].args,
('Cannot open "destfile"',))
def test_w_dest_close_fails(self):
srcfile = self.Faux()
destfile = self.Faux(True)
def _open(filename, mode='r'):
if filename == 'srcfile':
return srcfile
if filename == 'destfile':
return destfile
assert 0 # shouldn't reach here.
self._set_shutil_open(_open)
shutil.copyfile('srcfile', 'destfile')
self.assertTrue(srcfile._entered)
self.assertTrue(destfile._entered)
self.assertTrue(destfile._raised)
self.assertTrue(srcfile._exited_with[0] is IOError)
self.assertEqual(srcfile._exited_with[1].args,
('Cannot close',))
def test_w_source_close_fails(self):
srcfile = self.Faux(True)
destfile = self.Faux()
def _open(filename, mode='r'):
if filename == 'srcfile':
return srcfile
if filename == 'destfile':
return destfile
assert 0 # shouldn't reach here.
self._set_shutil_open(_open)
self.assertRaises(IOError,
shutil.copyfile, 'srcfile', 'destfile')
self.assertTrue(srcfile._entered)
self.assertTrue(destfile._entered)
self.assertFalse(destfile._raised)
self.assertTrue(srcfile._exited_with[0] is None)
self.assertTrue(srcfile._raised)
def test_move_dir_caseinsensitive(self):
# Renames a folder to the same name
# but a different case.
self.src_dir = tempfile.mkdtemp()
dst_dir = os.path.join(
os.path.dirname(self.src_dir),
os.path.basename(self.src_dir).upper())
self.assertNotEqual(self.src_dir, dst_dir)
try:
shutil.move(self.src_dir, dst_dir)
self.assertTrue(os.path.isdir(dst_dir))
finally:
if os.path.exists(dst_dir):
os.rmdir(dst_dir)
def test_main():
test_support.run_unittest(TestShutil, TestMove, TestCopyFile)
if __name__ == '__main__':
test_main()<|fim▁end|> | finally:
shutil.rmtree(src_dir)
shutil.rmtree(os.path.dirname(dst_dir))
|
<|file_name|>system_tests_policy_oversize_basic.py<|end_file_name|><|fim▁begin|>#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# 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 unittest
from system_test import TestCase, Qdrouterd, main_module, TIMEOUT, Logger, TestTimeout
from proton import Message
from proton.handlers import MessagingHandler
from proton.reactor import Container
# How many worker threads?
W_THREADS = 2
# Define oversize denial condition
OVERSIZE_CONDITION_NAME = "amqp:connection:forced"
OVERSIZE_CONDITION_DESC = "Message size exceeded"
#
# DISPATCH-975 Detect that an oversize message is blocked.
# These tests check basic blocking where the the sender is blocked by
# the ingress routers. It does not check compound blocking where
# oversize is allowed or denied by an ingress edge router but also
# denied by the uplink interior router.
class OversizeMessageTransferTest(MessagingHandler):
"""
This test connects a sender and a receiver. Then it tries to send _count_
number of messages of the given size through the router or router network.
With expect_block=True the ingress router should detect the sender's oversize
message and close the sender connection. The receiver may receive
aborted message indications but that is not guaranteed. If any aborted
messages are received then the count must be at most one.
The test is a success when the sender receives a connection error with
oversize indication and the receiver has not received too many aborts.
With expect_block=False sender messages should be received normally.
The test is a success when n_accepted == count.
"""
def __init__(self, sender_host, receiver_host, test_address,
message_size=100000, count=10, expect_block=True, print_to_console=False):
super(OversizeMessageTransferTest, self).__init__()
self.sender_host = sender_host
self.receiver_host = receiver_host
self.test_address = test_address
self.msg_size = message_size
self.count = count
self.expect_block = expect_block
self.sender_conn = None
self.receiver_conn = None
self.error = None
self.sender = None
self.receiver = None
self.proxy = None
self.n_sent = 0
self.n_rcvd = 0
self.n_accepted = 0
self.n_rejected = 0
self.n_aborted = 0
self.n_connection_error = 0
self.shut_down = False
self.logger = Logger(title=("OversizeMessageTransferTest - %s" % (self.test_address)), print_to_console=print_to_console)
self.log_unhandled = False
def timeout(self):
self.error = "Timeout Expired: n_sent=%d n_rcvd=%d n_rejected=%d n_aborted=%d" % \
(self.n_sent, self.n_rcvd, self.n_rejected, self.n_aborted)
self.logger.log("self.timeout " + self.error)
self._shut_down_test()
def on_start(self, event):
self.logger.log("on_start")
self.timer = event.reactor.schedule(TIMEOUT, TestTimeout(self))
self.logger.log("on_start: opening receiver connection to %s" % (self.receiver_host.addresses[0]))
self.receiver_conn = event.container.connect(self.receiver_host.addresses[0])
self.logger.log("on_start: opening sender connection to %s" % (self.sender_host.addresses[0]))
self.sender_conn = event.container.connect(self.sender_host.addresses[0])
self.logger.log("on_start: Creating receiver")
self.receiver = event.container.create_receiver(self.receiver_conn, self.test_address)
self.logger.log("on_start: Creating sender")
self.sender = event.container.create_sender(self.sender_conn, self.test_address)
self.logger.log("on_start: done")
def send(self):
while self.sender.credit > 0 and self.n_sent < self.count:
# construct message in indentifiable chunks
body_msg = ""
padchar = "abcdefghijklmnopqrstuvwxyz@#$%"[self.n_sent % 30]
while len(body_msg) < self.msg_size:
chunk = "[%s:%d:%d" % (self.test_address, self.n_sent, len(body_msg))
padlen = 50 - len(chunk)
chunk += padchar * padlen
body_msg += chunk
if len(body_msg) > self.msg_size:
body_msg = body_msg[:self.msg_size]
self.logger.log("send. address:%s message:%d of %s length=%d" %
(self.test_address, self.n_sent, self.count, self.msg_size))
m = Message(body=body_msg)
self.sender.send(m)
self.n_sent += 1
def on_sendable(self, event):
if event.sender == self.sender:
self.logger.log("on_sendable")
self.send()
def on_message(self, event):
if self.expect_block:
# All messages should violate maxMessageSize.
# Receiving any is an error.
self.error = "Received a message. Expected to receive no messages."
self.logger.log(self.error)
self._shut_down_test()
else:
self.n_rcvd += 1
self.accept(event.delivery)
self._check_done()
def on_connection_remote_close(self, event):
if self.shut_down:
return
if event.connection == self.sender_conn:
if event.connection.remote_condition is not None:
if event.connection.remote_condition.name == OVERSIZE_CONDITION_NAME and \
event.connection.remote_condition.description == OVERSIZE_CONDITION_DESC:
self.logger.log("on_connection_remote_close: sender closed with correct condition")
self.n_connection_error += 1
self.sender_conn.close()
self.sender_conn = None
else:
# sender closed but for wrong reason
self.error = "sender close error: Expected name: %s, description: %s, but received name: %s, description: %s" % (
OVERSIZE_CONDITION_NAME, OVERSIZE_CONDITION_DESC,
event.connection.remote_condition.name, event.connection.remote_condition.description)
self.logger.log(self.error)
else:
self.error = "sender close error: Expected a remote_condition but there was none."
self.logger.log(self.error)
else:
# connection error but not for sender
self.error = "unexpected connection close error: wrong connection closed."
self.logger.log(self.error)
self._check_done()
def _shut_down_test(self):
self.shut_down = True
if self.timer:
self.timer.cancel()
self.timer = None
if self.sender:
self.sender.close()
self.sender = None
if self.receiver:
self.receiver.close()
self.receiver = None
if self.sender_conn:
self.sender_conn.close()
self.sender_conn = None
if self.receiver_conn:
self.receiver_conn.close()
self.receiver_conn = None
def _check_done(self):
current = ("check_done: sent=%d rcvd=%d rejected=%d aborted=%d connection_error:%d" %
(self.n_sent, self.n_rcvd, self.n_rejected, self.n_aborted, self.n_connection_error))
self.logger.log(current)
if self.error is not None:
self.logger.log("TEST FAIL")
self._shut_down_test()
else:
done = (self.n_connection_error == 1) \
if self.expect_block else \
(self.n_sent == self.count and self.n_rcvd == self.count)
if done:
self.logger.log("TEST DONE!!!")
# self.log_unhandled = True # verbose debugging
self._shut_down_test()
def on_rejected(self, event):
self.n_rejected += 1
if self.expect_block:
self.logger.log("on_rejected: entry")
self._check_done()
else:
self.error = "Unexpected on_reject"
self.logger.log(self.error)
self._check_done()
def on_aborted(self, event):
self.logger.log("on_aborted")
self.n_aborted += 1
self._check_done()
def on_error(self, event):
self.error = "Container error"
self.logger.log(self.error)
self._shut_down_test()
def on_unhandled(self, method, *args):
if self.log_unhandled:
self.logger.log("on_unhandled: method: %s, args: %s" % (method, args))
def run(self):
try:
Container(self).run()
except Exception as e:
self.error = "Container run exception: %s" % (e)
self.logger.log(self.error)
self.logger.dump()
# For the next test case define max sizes for each router.
# These are the configured maxMessageSize values
EA1_MAX_SIZE = 50000
INTA_MAX_SIZE = 100000
INTB_MAX_SIZE = 150000
EB1_MAX_SIZE = 200000
# DISPATCH-1645 S32 max size is chosen to expose signed 32-bit
# wraparound bug. Sizes with bit 31 set look negative when used as
# C 'int' and prevent any message from passing policy checks.
S32_MAX_SIZE = 2**31
# Interior routers enforce max size directly.
# Edge routers are also checked by the attached interior router.
# Block tests that use edge routers that send messages to the network must
# account for the fact that the attached interior router will apply
# another max size. These tests do not check against EB1 max for the
# sender if the receiver is on EA1, INTA, or INTB since INTB's max
# would kick an and cause a false positive.
# Tests that check for allowing near-max sizes use the minimum of
# the edge router's max and the attached interior router's max.
# The bytes-over and bytes-under max that should trigger allow or deny.
# Messages with content this much over should be blocked while
# messages with content this much under should be allowed.
# * client overhead is typically 16 bytes or so
# * interrouter overhead is much larger with annotations
OVER_UNDER = 200
class MaxMessageSizeBlockOversize(TestCase):
"""<|fim▁hole|> verify that maxMessageSize blocks oversize messages
"""
@classmethod
def setUpClass(cls):
"""Start the router"""
super(MaxMessageSizeBlockOversize, cls).setUpClass()
def router(name, mode, max_size, extra):
config = [
('router', {'mode': mode,
'id': name,
'allowUnsettledMulticast': 'yes',
'workerThreads': W_THREADS}),
('listener', {'role': 'normal',
'port': cls.tester.get_port()}),
('address', {'prefix': 'multicast', 'distribution': 'multicast'}),
('policy', {'maxConnections': 100, 'enableVhostPolicy': 'true', 'maxMessageSize': max_size, 'defaultVhost': '$default'}),
('vhost', {'hostname': '$default',
'allowUnknownUser': 'true',
'groups': {
'$default': {
'users': '*',
'maxConnections': 100,
'remoteHosts': '*',
'sources': '*',
'targets': '*',
'allowAnonymousSender': 'true',
'allowWaypointLinks': 'true',
'allowDynamicSource': 'true'
}
}
})
]
if extra:
config.extend(extra)
config = Qdrouterd.Config(config)
cls.routers.append(cls.tester.qdrouterd(name, config, wait=True))
return cls.routers[-1]
# configuration:
# two edge routers connected via 2 interior routers with max sizes
#
# +-------+ +---------+ +---------+ +-------+
# | EA1 |<==>| INT.A |<==>| INT.B |<==>| EB1 |
# | 50,000| | 100,000 | | 150,000 | |200,000|
# +-------+ +---------+ +---------+ +-------+
#
# Note:
# * Messages whose senders connect to INT.A or INT.B are subject to max message size
# defined for the ingress router only.
# * Message whose senders connect to EA1 or EA2 are subject to max message size
# defined for the ingress router. If the message is forwarded through the
# connected interior router then the message is subject to another max message size
# defined by the interior router.
cls.routers = []
interrouter_port = cls.tester.get_port()
cls.INTA_edge_port = cls.tester.get_port()
cls.INTB_edge_port = cls.tester.get_port()
router('INT.A', 'interior', INTA_MAX_SIZE,
[('listener', {'role': 'inter-router',
'port': interrouter_port}),
('listener', {'role': 'edge', 'port': cls.INTA_edge_port})])
cls.INT_A = cls.routers[0]
cls.INT_A.listener = cls.INT_A.addresses[0]
router('INT.B', 'interior', INTB_MAX_SIZE,
[('connector', {'name': 'connectorToA',
'role': 'inter-router',
'port': interrouter_port}),
('listener', {'role': 'edge',
'port': cls.INTB_edge_port})])
cls.INT_B = cls.routers[1]
cls.INT_B.listener = cls.INT_B.addresses[0]
router('EA1', 'edge', EA1_MAX_SIZE,
[('listener', {'name': 'rc', 'role': 'route-container',
'port': cls.tester.get_port()}),
('connector', {'name': 'uplink', 'role': 'edge',
'port': cls.INTA_edge_port})])
cls.EA1 = cls.routers[2]
cls.EA1.listener = cls.EA1.addresses[0]
router('EB1', 'edge', EB1_MAX_SIZE,
[('connector', {'name': 'uplink',
'role': 'edge',
'port': cls.INTB_edge_port,
'maxFrameSize': 1024}),
('listener', {'name': 'rc', 'role': 'route-container',
'port': cls.tester.get_port()})])
cls.EB1 = cls.routers[3]
cls.EB1.listener = cls.EB1.addresses[0]
router('S32', 'standalone', S32_MAX_SIZE, [])
cls.S32 = cls.routers[4]
cls.S32.listener = cls.S32.addresses[0]
cls.INT_A.wait_router_connected('INT.B')
cls.INT_B.wait_router_connected('INT.A')
cls.EA1.wait_connectors()
cls.EB1.wait_connectors()
def test_40_block_oversize_INTA_INTA(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_A,
MaxMessageSizeBlockOversize.INT_A,
"e40",
message_size=INTA_MAX_SIZE + OVER_UNDER,
expect_block=True,
print_to_console=False)
test.run()
if test.error is not None:
test.logger.log("test_40 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_41_block_oversize_INTA_INTB(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_A,
MaxMessageSizeBlockOversize.INT_B,
"e41",
message_size=INTA_MAX_SIZE + OVER_UNDER,
expect_block=True)
test.run()
if test.error is not None:
test.logger.log("test_41 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_42_block_oversize_INTA_EA1(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_A,
MaxMessageSizeBlockOversize.EA1,
"e42",
message_size=INTA_MAX_SIZE + OVER_UNDER,
expect_block=True)
test.run()
if test.error is not None:
test.logger.log("test_42 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_43_block_oversize_INTA_EB1(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_A,
MaxMessageSizeBlockOversize.EB1,
"e43",
message_size=INTA_MAX_SIZE + OVER_UNDER,
expect_block=True)
test.run()
if test.error is not None:
test.logger.log("test_43 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_44_block_oversize_INTB_INTA(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_B,
MaxMessageSizeBlockOversize.INT_A,
"e44",
message_size=INTB_MAX_SIZE + OVER_UNDER,
expect_block=True)
test.run()
if test.error is not None:
test.logger.log("test_44 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_45_block_oversize_INTB_INTB(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_B,
MaxMessageSizeBlockOversize.INT_B,
"e45",
message_size=INTB_MAX_SIZE + OVER_UNDER,
expect_block=True)
test.run()
if test.error is not None:
test.logger.log("test_45 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_46_block_oversize_INTB_EA1(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_B,
MaxMessageSizeBlockOversize.EA1,
"e46",
message_size=INTB_MAX_SIZE + OVER_UNDER,
expect_block=True)
test.run()
if test.error is not None:
test.logger.log("test_46 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_47_block_oversize_INTB_EB1(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_B,
MaxMessageSizeBlockOversize.EB1,
"e47",
message_size=INTB_MAX_SIZE + OVER_UNDER,
expect_block=True)
test.run()
if test.error is not None:
test.logger.log("test_47 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_48_block_oversize_EA1_INTA(self):
if EA1_MAX_SIZE >= INTA_MAX_SIZE:
self.skipTest("EA1 sending to INT.A may be blocked by EA1 limit and also by INT.A limit. That condition is tested in compound test.")
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EA1,
MaxMessageSizeBlockOversize.INT_A,
"e48",
message_size=EA1_MAX_SIZE + OVER_UNDER,
expect_block=True)
test.run()
if test.error is not None:
test.logger.log("test_48 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_49_block_oversize_EA1_INTB(self):
if EA1_MAX_SIZE >= INTA_MAX_SIZE:
self.skipTest("EA1 sending to INT.B may be blocked by EA1 limit and also by INT.A limit. That condition is tested in compound test.")
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EA1,
MaxMessageSizeBlockOversize.INT_B,
"e49",
message_size=EA1_MAX_SIZE + OVER_UNDER,
expect_block=True)
test.run()
if test.error is not None:
test.logger.log("test_49 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_4a_block_oversize_EA1_EA1(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EA1,
MaxMessageSizeBlockOversize.EA1,
"e4a",
message_size=EA1_MAX_SIZE + OVER_UNDER,
expect_block=True)
test.run()
if test.error is not None:
test.logger.log("test_4a test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_4b_block_oversize_EA1_EB1(self):
if EA1_MAX_SIZE >= INTA_MAX_SIZE:
self.skipTest("EA1 sending to EB1 may be blocked by EA1 limit and also by INT.A limit. That condition is tested in compound test.")
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EA1,
MaxMessageSizeBlockOversize.EB1,
"e4b",
message_size=EA1_MAX_SIZE + OVER_UNDER,
expect_block=True)
test.run()
if test.error is not None:
test.logger.log("test_4b test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_4c_block_oversize_EB1_INTA(self):
if EB1_MAX_SIZE > INTB_MAX_SIZE:
self.skipTest("EB1 sending to INT.A may be blocked by EB1 limit and also by INT.B limit. That condition is tested in compound test.")
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EB1,
MaxMessageSizeBlockOversize.INT_A,
"e4c",
message_size=EB1_MAX_SIZE + OVER_UNDER,
expect_block=True)
test.run()
if test.error is not None:
test.logger.log("test_4c test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_4d_block_oversize_EB1_INTB(self):
if EB1_MAX_SIZE > INTB_MAX_SIZE:
self.skipTest("EB1 sending to INT.B may be blocked by EB1 limit and also by INT.B limit. That condition is tested in compound test.")
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EB1,
MaxMessageSizeBlockOversize.INT_B,
"e4d",
message_size=EB1_MAX_SIZE + OVER_UNDER,
expect_block=True)
test.run()
if test.error is not None:
test.logger.log("test_4d test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_4e_block_oversize_EB1_EA1(self):
if EB1_MAX_SIZE > INTB_MAX_SIZE:
self.skipTest("EB1 sending to EA1 may be blocked by EB1 limit and also by INT.B limit. That condition is tested in compound test.")
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EB1,
MaxMessageSizeBlockOversize.EA1,
"e4e",
message_size=EB1_MAX_SIZE + OVER_UNDER,
expect_block=True)
test.run()
if test.error is not None:
test.logger.log("test_4e test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_4f_block_oversize_EB1_EB1(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EB1,
MaxMessageSizeBlockOversize.EB1,
"e4f",
message_size=EB1_MAX_SIZE + OVER_UNDER,
expect_block=True)
test.run()
if test.error is not None:
test.logger.log("test_4f test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
#
# tests under maxMessageSize should not block
#
def test_50_allow_undersize_INTA_INTA(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_A,
MaxMessageSizeBlockOversize.INT_A,
"e50",
message_size=INTA_MAX_SIZE - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_50 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_51_allow_undersize_INTA_INTB(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_A,
MaxMessageSizeBlockOversize.INT_B,
"e51",
message_size=INTA_MAX_SIZE - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_51 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_52_allow_undersize_INTA_EA1(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_A,
MaxMessageSizeBlockOversize.EA1,
"e52",
message_size=INTA_MAX_SIZE - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_52 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_53_allow_undersize_INTA_EB1(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_A,
MaxMessageSizeBlockOversize.EB1,
"e53",
message_size=INTA_MAX_SIZE - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_53 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_54_allow_undersize_INTB_INTA(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_B,
MaxMessageSizeBlockOversize.INT_A,
"e54",
message_size=INTB_MAX_SIZE - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_54 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_55_allow_undersize_INTB_INTB(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_B,
MaxMessageSizeBlockOversize.INT_B,
"e55",
message_size=INTB_MAX_SIZE - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_55 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_56_allow_undersize_INTB_EA1(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_B,
MaxMessageSizeBlockOversize.EA1,
"e56",
message_size=INTB_MAX_SIZE - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_56 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_57_allow_undersize_INTB_EB1(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.INT_B,
MaxMessageSizeBlockOversize.EB1,
"e57",
message_size=INTB_MAX_SIZE - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_57 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_58_allow_undersize_EA1_INTA(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EA1,
MaxMessageSizeBlockOversize.INT_A,
"e58",
message_size=min(EA1_MAX_SIZE, INTA_MAX_SIZE) - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_58 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_59_allow_undersize_EA1_INTB(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EA1,
MaxMessageSizeBlockOversize.INT_B,
"e59",
message_size=min(EA1_MAX_SIZE, INTA_MAX_SIZE) - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_59 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_5a_allow_undersize_EA1_EA1(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EA1,
MaxMessageSizeBlockOversize.EA1,
"e5a",
message_size=min(EA1_MAX_SIZE, INTA_MAX_SIZE) - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_5a test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_5b_allow_undersize_EA1_EB1(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EA1,
MaxMessageSizeBlockOversize.EB1,
"e5b",
message_size=min(EA1_MAX_SIZE, INTA_MAX_SIZE) - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_5b test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_5c_allow_undersize_EB1_INTA(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EB1,
MaxMessageSizeBlockOversize.INT_A,
"e5c",
message_size=min(EB1_MAX_SIZE, INTB_MAX_SIZE) - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_5c test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_5d_allow_undersize_EB1_INTB(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EB1,
MaxMessageSizeBlockOversize.INT_B,
"e5d",
message_size=min(EB1_MAX_SIZE, INTB_MAX_SIZE) - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_5d test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_5e_allow_undersize_EB1_EA1(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EB1,
MaxMessageSizeBlockOversize.EA1,
"e5e",
message_size=min(EB1_MAX_SIZE, INTB_MAX_SIZE) - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_5e test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_5f_allow_undersize_EB1_EB1(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.EB1,
MaxMessageSizeBlockOversize.EB1,
"e5f",
message_size=min(EB1_MAX_SIZE, INTB_MAX_SIZE) - OVER_UNDER,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_5f test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
def test_s32_allow_gt_signed_32bit_max(self):
test = OversizeMessageTransferTest(MaxMessageSizeBlockOversize.S32,
MaxMessageSizeBlockOversize.S32,
"s32",
message_size=200,
expect_block=False)
test.run()
if test.error is not None:
test.logger.log("test_s32 test error: %s" % (test.error))
test.logger.dump()
self.assertTrue(test.error is None)
if __name__ == '__main__':
unittest.main(main_module())<|fim▁end|> | |
<|file_name|>market-selection.component.ts<|end_file_name|><|fim▁begin|>import {Component, OnInit} from '@angular/core';<|fim▁hole|>import {MarketCardType} from '../market-card-type';
import {MarketService} from '../market.service';
import {Expansion} from '../expansion';
import { GameModeService } from '../game-mode.service';
import { GameMode } from '../game-mode';
@Component({
selector: 'app-market-selection',
templateUrl: './market-selection.component.html',
styleUrls: ['./market-selection.component.css']
})
export class MarketSelectionComponent implements OnInit {
constructor(private marketService: MarketService, private gameModeService: GameModeService) { }
cards: MarketCard[];
expeditionMode: boolean;
ngOnInit() {
this.marketService.marketCards$.subscribe((cards: MarketCard[]) => {
this.cards = cards;
});
this.cards = this.marketService.marketCards;
this.gameModeService.selectedGameMode$.subscribe((newGameMode: GameMode) => {
this.updateExpeditionMode(newGameMode);
});
this.updateExpeditionMode(this.gameModeService.selectedGameMode);
}
getCardCssClass(type: MarketCardType): string {
switch (type) {
case MarketCardType.Gem:
return 'gem-card';
case MarketCardType.Relic:
return 'relic-card';
case MarketCardType.Spell:
return 'spell-card';
}
}
getCardTypeLabel(type: MarketCardType): string {
switch (type) {
case MarketCardType.Gem:
return 'Gem';
case MarketCardType.Relic:
return 'Relic';
case MarketCardType.Spell:
return 'Spell';
}
}
private updateExpeditionMode(gameMode: GameMode): void {
this.expeditionMode = (gameMode !== GameMode.SingleGame);
}
}<|fim▁end|> | import {MarketCard} from '../market-card'; |
<|file_name|>UniformBuffer.cpp<|end_file_name|><|fim▁begin|>#include "UniformBuffer.hpp"
#include <iostream>
#include <cstring>
UniformBuffer::UniformBuffer(const void* data, unsigned int size, VkDevice device, VkPhysicalDevice physicalDevice, VkDescriptorPool descriptorPool, VkShaderStageFlags flags) : Buffer(device, physicalDevice, descriptorPool) {
this->device = device;
this->physicalDevice = physicalDevice;
this->descriptorPool = descriptorPool;
createBuffer(size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &buffer, &bufferMemory);
// Copy data to mapped memory.
setData(data, size);
// Create descriptor set.
createDescriptorSetLayout(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, flags);
createDescriptorSet(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, buffer, size);
}
UniformBuffer::~UniformBuffer() {
vkDestroyBuffer(device, buffer, nullptr);
vkFreeMemory(device, bufferMemory, nullptr);
}
void UniformBuffer::setData(const void* data, unsigned int size) {
void* mappedMemory;
vkMapMemory(device, bufferMemory, 0, size, 0, &mappedMemory);<|fim▁hole|><|fim▁end|> | memcpy(mappedMemory, data, size);
vkUnmapMemory(device, bufferMemory);
} |
<|file_name|>test_init.py<|end_file_name|><|fim▁begin|>"""Test Agent DVR integration."""
from unittest.mock import AsyncMock, patch
from agent import AgentError
from homeassistant.components.agent_dvr.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from . import CONF_DATA, create_entry
from tests.components.agent_dvr import init_integration
from tests.test_util.aiohttp import AiohttpClientMocker
async def _create_mocked_agent(available: bool = True):
mocked_agent = AsyncMock()
mocked_agent.is_available = available
return mocked_agent
def _patch_init_agent(mocked_agent):
return patch(
"homeassistant.components.agent_dvr.Agent",
return_value=mocked_agent,
)
async def test_setup_config_and_unload(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
):
"""Test setup and unload."""
entry = await init_integration(hass, aioclient_mock)
assert entry.state == ConfigEntryState.LOADED
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert entry.data == CONF_DATA
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.NOT_LOADED<|fim▁hole|> """Test that it throws ConfigEntryNotReady when exception occurs during setup."""
entry = create_entry(hass)
with patch(
"homeassistant.components.agent_dvr.Agent.update",
side_effect=AgentError,
):
await hass.config_entries.async_setup(entry.entry_id)
assert entry.state == ConfigEntryState.SETUP_RETRY
with _patch_init_agent(await _create_mocked_agent(available=False)):
await hass.config_entries.async_reload(entry.entry_id)
assert entry.state == ConfigEntryState.SETUP_RETRY<|fim▁end|> | assert not hass.data.get(DOMAIN)
async def test_async_setup_entry_not_ready(hass: HomeAssistant): |
<|file_name|>service.rs<|end_file_name|><|fim▁begin|>// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify<|fim▁hole|>// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Tests for the snapshot service.
use std::sync::Arc;
use client::{BlockChainClient, Client};
use ids::BlockId;
use snapshot::service::{Service, ServiceParams};
use snapshot::{self, ManifestData, SnapshotService};
use spec::Spec;
use tests::helpers::generate_dummy_client_with_spec_and_data;
use devtools::RandomTempPath;
use io::IoChannel;
use util::kvdb::{Database, DatabaseConfig};
struct NoopDBRestore;
impl snapshot::DatabaseRestore for NoopDBRestore {
fn restore_db(&self, _new_db: &str) -> Result<(), ::error::Error> {
Ok(())
}
}
#[test]
fn restored_is_equivalent() {
const NUM_BLOCKS: u32 = 400;
const TX_PER: usize = 5;
let gas_prices = vec![1.into(), 2.into(), 3.into(), 999.into()];
let client = generate_dummy_client_with_spec_and_data(Spec::new_null, NUM_BLOCKS, TX_PER, &gas_prices);
let path = RandomTempPath::create_dir();
let mut path = path.as_path().clone();
let mut client_db = path.clone();
client_db.push("client_db");
path.push("snapshot");
let db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
let client_db = Database::open(&db_config, client_db.to_str().unwrap()).unwrap();
let spec = Spec::new_null();
let client2 = Client::new(
Default::default(),
&spec,
Arc::new(client_db),
Arc::new(::miner::Miner::with_spec(&spec)),
IoChannel::disconnected(),
).unwrap();
let service_params = ServiceParams {
engine: spec.engine.clone(),
genesis_block: spec.genesis_block(),
db_config: db_config,
pruning: ::util::journaldb::Algorithm::Archive,
channel: IoChannel::disconnected(),
snapshot_root: path,
db_restore: client2.clone(),
};
let service = Service::new(service_params).unwrap();
service.take_snapshot(&client, NUM_BLOCKS as u64).unwrap();
let manifest = service.manifest().unwrap();
service.init_restore(manifest.clone(), true).unwrap();
assert!(service.init_restore(manifest.clone(), true).is_ok());
for hash in manifest.state_hashes {
let chunk = service.chunk(hash).unwrap();
service.feed_state_chunk(hash, &chunk);
}
for hash in manifest.block_hashes {
let chunk = service.chunk(hash).unwrap();
service.feed_block_chunk(hash, &chunk);
}
assert_eq!(service.status(), ::snapshot::RestorationStatus::Inactive);
for x in 0..NUM_BLOCKS {
let block1 = client.block(BlockId::Number(x as u64)).unwrap();
let block2 = client2.block(BlockId::Number(x as u64)).unwrap();
assert_eq!(block1, block2);
}
}
#[test]
fn guards_delete_folders() {
let spec = Spec::new_null();
let path = RandomTempPath::create_dir();
let mut path = path.as_path().clone();
let service_params = ServiceParams {
engine: spec.engine.clone(),
genesis_block: spec.genesis_block(),
db_config: DatabaseConfig::with_columns(::db::NUM_COLUMNS),
pruning: ::util::journaldb::Algorithm::Archive,
channel: IoChannel::disconnected(),
snapshot_root: path.clone(),
db_restore: Arc::new(NoopDBRestore),
};
let service = Service::new(service_params).unwrap();
path.push("restoration");
let manifest = ManifestData {
version: 2,
state_hashes: vec![],
block_hashes: vec![],
block_number: 0,
block_hash: Default::default(),
state_root: Default::default(),
};
service.init_restore(manifest.clone(), true).unwrap();
assert!(path.exists());
service.abort_restore();
assert!(!path.exists());
service.init_restore(manifest.clone(), true).unwrap();
assert!(path.exists());
drop(service);
assert!(!path.exists());
}<|fim▁end|> | // 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.
|
<|file_name|>extract_patches.py<|end_file_name|><|fim▁begin|>import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import os
from math import sqrt
from os.path import expanduser
def extract_patches(path, filename, out_path, patch_size, stride, visualize):
img = mpimg.imread(path+filename)
nRows, nCols, nColor = img.shape
psx, psy = patch_size
patches = []
for r in xrange(psy/2+1, nRows - psy/2 - 1, stride):
for c in xrange(psx/2+1, nCols - psx/2 - 1, stride):
patches.append(img[r-psy/2 : r + psy/2, c-psx/2 : c+psx/2, :]) <|fim▁hole|> for pos in xrange(len(patches)):
plt.imsave(out_path + name + "_" + str(pos) + ext, patches[pos])
if not visualize:
return
for pos in xrange(len(patches)):
if pos + 1 < grid_size ** 2:
plt.subplot(grid_size, grid_size, pos+1)
plt.imshow(patches[pos])
plt.axis('off')
if __name__ == "__main__":
home = expanduser("~")
nyu_path = home+'/IGNORE_NYU/jpgs/'
#extract_patches(, [16,16], 100, True)
for root, dirs, files in os.walk(nyu_path, topdown=False):
for filename in files:
extract_patches(nyu_path, filename, nyu_path+"/patches/", [64,64], 100, False)<|fim▁end|> | grid_size = int(sqrt(len(patches)))
name, ext = os.path.splitext(filename) |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>pub mod apps;
pub mod scope;
mod user;
<|fim▁hole|><|fim▁end|> | pub use self::user::{SignedInUser, SignedInUserWithEmail}; |
<|file_name|>caret_jump.py<|end_file_name|><|fim▁begin|>import sublime
import sublime_plugin
OPTIONS_LAST_REGEX = "jump_caret_last_regex"
class CaretJumpCommand(sublime_plugin.TextCommand):
def run(self, edit, jump=True, jump_to=None, repeat_previous_jump=False):<|fim▁hole|> for sel in view.sel():
next_sel = view.find(user_input, sel.end(), sublime.IGNORECASE)
if next_sel.begin() != -1:
new_sels.append(next_sel)
return new_sels
def jump_last_regex():
last_reg = self.view.settings().get(OPTIONS_LAST_REGEX)
if last_reg:
select_next_regex(last_reg)
def select_next_regex(user_input):
view.erase_regions("caret_jump_preview")
if not user_input:
# jump_last_regex()
return
self.view.settings().set(OPTIONS_LAST_REGEX, user_input)
new_sels = get_next_sels(user_input)
if jump and new_sels:
view.sel().clear()
view.sel().add_all(new_sels)
def input_changed(user_input):
new_sels = get_next_sels(user_input)
view.add_regions("caret_jump_preview",
new_sels,
"source, text",
"dot",
sublime.DRAW_OUTLINED)
def input_canceled():
view.erase_regions("caret_jump_preview")
selection = view.substr(view.sel()[0]) if view.sel() else ""
if jump_to:
select_next_regex(jump_to)
elif repeat_previous_jump:
jump_last_regex()
else:
default = selection if selection \
else self.view.settings().get(OPTIONS_LAST_REGEX, "")
view.window().show_input_panel("Seach for",
default,
select_next_regex,
input_changed,
input_canceled)<|fim▁end|> | view = self.view
def get_next_sels(user_input):
new_sels = [] |
<|file_name|>sandboxSignalMapper.py<|end_file_name|><|fim▁begin|>from PyQt4 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.mapper = QtCore.QSignalMapper(self)
self.toolbar = self.addToolBar('Foo')
self.toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly)
for text in 'One Two Three'.split():
action = QtGui.QAction(text, self)
self.mapper.setMapping(action, text)<|fim▁hole|> action.triggered.connect(self.mapper.map)
self.toolbar.addAction(action)
self.mapper.mapped['QString'].connect(self.handleButton)
self.edit = QtGui.QLineEdit(self)
self.setCentralWidget(self.edit)
def handleButton(self, identifier):
if identifier == 'One':
text = 'Do This'
elif identifier == 'Two':
text = 'Do That'
elif identifier == 'Three':
text = 'Do Other'
self.edit.setText(text)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.resize(300, 60)
window.show()
sys.exit(app.exec_())<|fim▁end|> | |
<|file_name|>color.cpp<|end_file_name|><|fim▁begin|>// SPDX-License-Identifier: GPL-2.0<|fim▁hole|>#include "color.h"
#include <QMap>
#include <array>
// Note that std::array<QColor, 2> is in every respect equivalent to QColor[2],
// but allows assignment, comparison, can be returned from functions, etc.
static QMap<color_index_t, std::array<QColor, 2>> profile_color = {
{ SAC_1, {{ FUNGREEN1, BLACK1_LOW_TRANS }} },
{ SAC_2, {{ APPLE1, BLACK1_LOW_TRANS }} },
{ SAC_3, {{ ATLANTIS1, BLACK1_LOW_TRANS }} },
{ SAC_4, {{ ATLANTIS2, BLACK1_LOW_TRANS }} },
{ SAC_5, {{ EARLSGREEN1, BLACK1_LOW_TRANS }} },
{ SAC_6, {{ HOKEYPOKEY1, BLACK1_LOW_TRANS }} },
{ SAC_7, {{ TUSCANY1, BLACK1_LOW_TRANS }} },
{ SAC_8, {{ CINNABAR1, BLACK1_LOW_TRANS }} },
{ SAC_9, {{ REDORANGE1, BLACK1_LOW_TRANS }} },
{ VELO_STABLE, {{ CAMARONE1, BLACK1_LOW_TRANS }} },
{ VELO_SLOW, {{ LIMENADE1, BLACK1_LOW_TRANS }} },
{ VELO_MODERATE, {{ RIOGRANDE1, BLACK1_LOW_TRANS }} },
{ VELO_FAST, {{ PIRATEGOLD1, BLACK1_LOW_TRANS }} },
{ VELO_CRAZY, {{ RED1, BLACK1_LOW_TRANS }} },
{ PO2, {{ APPLE1, BLACK1_LOW_TRANS }} },
{ PO2_ALERT, {{ RED1, BLACK1_LOW_TRANS }} },
{ PN2, {{ BLACK1_LOW_TRANS, BLACK1_LOW_TRANS }} },
{ PN2_ALERT, {{ RED1, BLACK1_LOW_TRANS }} },
{ PHE, {{ PEANUT, BLACK1_LOW_TRANS }} },
{ PHE_ALERT, {{ RED1, BLACK1_LOW_TRANS }} },
{ O2SETPOINT, {{ PIRATEGOLD1_MED_TRANS, BLACK1_LOW_TRANS }} },
{ CCRSENSOR1, {{ TUNDORA1_MED_TRANS, BLACK1_LOW_TRANS }} },
{ CCRSENSOR2, {{ ROYALBLUE2_LOW_TRANS, BLACK1_LOW_TRANS }} },
{ CCRSENSOR3, {{ PEANUT, BLACK1_LOW_TRANS }} },
{ SCR_OCPO2, {{ PIRATEGOLD1_MED_TRANS, BLACK1_LOW_TRANS }} },
{ PP_LINES, {{ BLACK1_HIGH_TRANS, BLACK1_LOW_TRANS }} },
{ TEXT_BACKGROUND, {{ CONCRETE1_LOWER_TRANS, WHITE1 }} },
{ ALERT_BG, {{ BROOM1_LOWER_TRANS, BLACK1_LOW_TRANS }} },
{ ALERT_FG, {{ BLACK1_LOW_TRANS, WHITE1 }} },
{ EVENTS, {{ REDORANGE1, BLACK1_LOW_TRANS }} },
{ SAMPLE_DEEP, {{ QColor(Qt::red).darker(), BLACK1 }} },
{ SAMPLE_SHALLOW, {{ QColor(Qt::red).lighter(), BLACK1_LOW_TRANS }} },
{ SMOOTHED, {{ REDORANGE1_HIGH_TRANS, BLACK1_LOW_TRANS }} },
{ MINUTE, {{ MEDIUMREDVIOLET1_HIGHER_TRANS, BLACK1_LOW_TRANS }} },
{ TIME_GRID, {{ WHITE1, BLACK1_HIGH_TRANS }} },
{ TIME_TEXT, {{ FORESTGREEN1, BLACK1 }} },
{ DEPTH_GRID, {{ WHITE1, BLACK1_HIGH_TRANS }} },
{ MEAN_DEPTH, {{ REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS }} },
{ HR_PLOT, {{ REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS }} },
{ HR_TEXT, {{ REDORANGE1_MED_TRANS, BLACK1_LOW_TRANS }} },
{ HR_AXIS, {{ MED_GRAY_HIGH_TRANS, MED_GRAY_HIGH_TRANS }} },
{ DEPTH_BOTTOM, {{ GOVERNORBAY1_MED_TRANS, BLACK1_HIGH_TRANS }} },
{ DEPTH_TOP, {{ MERCURY1_MED_TRANS, WHITE1_MED_TRANS }} },
{ TEMP_TEXT, {{ GOVERNORBAY2, BLACK1_LOW_TRANS }} },
{ TEMP_PLOT, {{ ROYALBLUE2_LOW_TRANS, BLACK1_LOW_TRANS }} },
{ SAC_DEFAULT, {{ WHITE1, BLACK1_LOW_TRANS }} },
{ BOUNDING_BOX, {{ WHITE1, BLACK1_LOW_TRANS }} },
{ PRESSURE_TEXT, {{ KILLARNEY1, BLACK1_LOW_TRANS }} },
{ BACKGROUND, {{ SPRINGWOOD1, WHITE1 }} },
{ BACKGROUND_TRANS, {{ SPRINGWOOD1_MED_TRANS, WHITE1_MED_TRANS }} },
{ CEILING_SHALLOW, {{ REDORANGE1_HIGH_TRANS, BLACK1_HIGH_TRANS }} },
{ CEILING_DEEP, {{ RED1_MED_TRANS, BLACK1_HIGH_TRANS }} },
{ CALC_CEILING_SHALLOW, {{ FUNGREEN1_HIGH_TRANS, BLACK1_HIGH_TRANS }} },
{ CALC_CEILING_DEEP, {{ APPLE1_HIGH_TRANS, BLACK1_HIGH_TRANS }} },
{ TISSUE_PERCENTAGE, {{ GOVERNORBAY2, BLACK1_LOW_TRANS }} },
{ DURATION_LINE, {{ BLACK1, BLACK1_LOW_TRANS }} }
};
QColor getColor(const color_index_t i, bool isGrayscale)
{
if (profile_color.count() > i && i >= 0)
return profile_color[i][isGrayscale ? 1 : 0];
return QColor(Qt::black);
}
QColor getSacColor(int sac, int avg_sac)
{
int sac_index = 0;
int delta = sac - avg_sac + 7000;
sac_index = delta / 2000;
if (sac_index < 0)
sac_index = 0;
if (sac_index > SAC_COLORS - 1)
sac_index = SAC_COLORS - 1;
return getColor((color_index_t)(SAC_COLORS_START_IDX + sac_index), false);
}
QColor getPressureColor(double density)
{
QColor color;
int h = ((int) (180.0 - 180.0 * density / 8.0));
while (h < 0)
h += 360;
color.setHsv(h , 255, 255);
return color;
}<|fim▁end|> | |
<|file_name|>api.js<|end_file_name|><|fim▁begin|>(function (root, factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory(require('jquery'), require('../common/utility'));
} else {
root.api = factory(root.jQuery, root.utility);
}
}(this, function ($, util) {
// API
var self = {};
// Object -> Promise[[Entity]]
self.searchEntity = function(query){
return get('/search/entity', { num: 10, q: query })
.then(format)
.catch(handleError);
// [Entity] -> [Entity]
function format(results){
// stringify id & rename keys (`primary_type` -> `primary_ext`; `description` -> `blurb`)
return results.map(function(result) {
var _result = Object.assign({}, result, {
primary_ext: result.primary_ext || result.primary_type,
blurb: result.blurb || result.description,
id: String(result.id)
});
delete _result.primary_type;
delete _result.description;
return _result;
});
}
// Error -> []
function handleError(err){
console.error('API request error: ', err);
return [];
}
};
// [EntityWithoutId] -> Promise[[Entity]]
self.createEntities = function(entities){
return post('/entities/bulk', formatReq(entities))
.then(formatResp);
// [Entity] -> [Entity]
function formatReq(entities){
return {
data: entities.map(function(entity){
return {
type: "entities",
attributes: entity
};
})
};
};
// [Entity] -> [Entity]
function formatResp(resp){
// copy, but stringify id
return resp.data.map(function(datum){
return Object.assign(
datum.attributes,
{ id: String(datum.attributes.id)}
);
});
}
};
// Integer, [Integer] -> Promise[[ListEntity]]
self.addEntitiesToList = function(listId, entityIds, reference){
return post('/lists/'+listId+'/entities/bulk', formatReq(entityIds))
.then(formatResp);
function formatReq(entityIds){
return {
data: entityIds.map(function(id){
return { type: 'entities', id: id };
}).concat({
type: 'references',
attributes: reference
})
};
};
function formatResp(resp){
return resp.data.map(function(datum){
return util.stringifyValues(datum.attributes);
});
}
};
// String, Integer -> Promise
// helpers
function get(url, queryParams){
return fetch(url + qs(queryParams), {
headers: headers(),
method: 'get',
credentials: 'include' // use auth tokens stored in session cookies
}).then(jsonify);
}
function post(url, payload){
return fetch(url, {
headers: headers(),
method: 'post',
credentials: 'include', // use auth tokens stored in session cookies
body: JSON.stringify(payload)
}).then(jsonify);
};
function patch(url, payload){
return fetch(url, {
headers: headers(),
method: 'PATCH',
credentials: 'include', // use auth tokens stored in session cookies
body: JSON.stringify(payload)
}).then(function(response) {
if (response.body) {
return jsonify(response);
} else {
return response;
}
});
};
function headers(){
return {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'Littlesis-Request-Type': 'API',
// TODO: retrieve this w/o JQuery
'X-CSRF-Token': $("meta[name='csrf-token']").attr("content") || ""
};
}
function qs(queryParams){
return '?' + $.param(queryParams);
}
// Response -> Promise[Error|JSON]<|fim▁hole|> function jsonify(response){
return response
.json()
.then(function(json){
return json.errors ?
Promise.reject(json.errors[0].title) :
Promise.resolve(json);
});
}
return self;
}));<|fim▁end|> | |
<|file_name|>test.py<|end_file_name|><|fim▁begin|>############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the commercial license agreement provided with the
# Software or, alternatively, in accordance with the terms contained in
# a written agreement between you and The Qt Company. For licensing terms
# and conditions see https://www.qt.io/terms-conditions. For further
# information use the contact form at https://www.qt.io/contact-us.
#
# GNU General Public License Usage
# Alternatively, this file may be used under the terms of the GNU
# General Public License version 3 as published by the Free Software
# Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
# included in the packaging of this file. Please review the following
# information to ensure the GNU General Public License requirements will
# be met: https://www.gnu.org/licenses/gpl-3.0.html.
#
############################################################################
<|fim▁hole|> startApplication("qtcreator" + SettingsPath)
if not startedWithoutPluginError():
return
checkedTargets, projectName = createNewQtQuickApplication(tempDir(), "SampleApp")
# run project for debug and release and verify results
runVerify(checkedTargets)
#close Qt Creator
invokeMenuItem("File", "Exit")<|fim▁end|> | source("../../shared/qtcreator.py")
# test New Qt Quick Application build and run for release and debug option
def main(): |
<|file_name|>spinner.rs<|end_file_name|><|fim▁begin|>// This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use Widget;
use ffi;
use glib;
use glib::Value;
use glib::object::Downcast;<|fim▁hole|>
glib_wrapper! {
pub struct Spinner(Object<ffi::GtkSpinner>): Widget;
match fn {
get_type => || ffi::gtk_spinner_get_type(),
}
}
impl Spinner {
pub fn new() -> Spinner {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_spinner_new()).downcast_unchecked()
}
}
}
pub trait SpinnerExt {
fn start(&self);
fn stop(&self);
fn get_property_active(&self) -> bool;
fn set_property_active(&self, active: bool);
}
impl<O: IsA<Spinner> + IsA<glib::object::Object>> SpinnerExt for O {
fn start(&self) {
unsafe {
ffi::gtk_spinner_start(self.to_glib_none().0);
}
}
fn stop(&self) {
unsafe {
ffi::gtk_spinner_stop(self.to_glib_none().0);
}
}
fn get_property_active(&self) -> bool {
let mut value = Value::from(&false);
unsafe {
gobject_ffi::g_object_get_property(self.to_glib_none().0, "active".to_glib_none().0, value.to_glib_none_mut().0);
}
value.get().unwrap()
}
fn set_property_active(&self, active: bool) {
unsafe {
gobject_ffi::g_object_set_property(self.to_glib_none().0, "active".to_glib_none().0, Value::from(&active).to_glib_none().0);
}
}
}<|fim▁end|> | use glib::object::IsA;
use glib::translate::*;
use gobject_ffi; |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// The code below is a stub. Just enough to satisfy the compiler.
// In order to pass the tests you can add-to or change any of this code.
#[allow(unused_variables)]<|fim▁hole|>pub fn convert(input: &str) -> Result<String, ()> {
unimplemented!();
}<|fim▁end|> | |
<|file_name|>ex_integer.go<|end_file_name|><|fim▁begin|>package atoms
import (
"fmt"
"hash/fnv"
"math/big"
"github.com/corywalker/expreduce/pkg/expreduceapi"
)
// Integer numbers represented by big.Int
type Integer struct {
Val *big.Int
cachedHash uint64
}
/*func (f *Integer) StringForm(params ToStringParams) string {
return fmt.Sprintf("%d", f.Val)
}*/
func (thisInt *Integer) StringForm(params expreduceapi.ToStringParams) string {
return fmt.Sprintf("%d", thisInt.Val)
}
func (thisInt *Integer) String() string {
return thisInt.StringForm(defaultStringParams())
}
func (thisInt *Integer) IsEqual(other expreduceapi.Ex) string {
otherConv, ok := other.(*Integer)
if !ok {
otherFlt, ok := other.(*Flt)
if ok {
thisIntAsFlt := big.NewFloat(0)
thisIntAsFlt.SetInt(thisInt.Val)
if thisIntAsFlt.Cmp(otherFlt.Val) == 0 {
return "EQUAL_TRUE"
}
}
return "EQUAL_UNK"
}<|fim▁hole|> return "EQUAL_FALSE"
}
return "EQUAL_TRUE"
}
func (thisInt *Integer) DeepCopy() expreduceapi.Ex {
tmp := big.NewInt(0)
tmp.Set(thisInt.Val)
return &Integer{Val: tmp, cachedHash: thisInt.cachedHash}
}
func (thisInt *Integer) Copy() expreduceapi.Ex {
return thisInt
}
func (thisInt *Integer) NeedsEval() bool {
return false
}
func NewInteger(i *big.Int) *Integer {
return &Integer{Val: i}
}
func NewInt(i int64) *Integer {
return NewInteger(big.NewInt(i))
}
func (thisInt *Integer) Hash() uint64 {
if thisInt.cachedHash > 0 {
return thisInt.cachedHash
}
h := fnv.New64a()
h.Write([]byte{242, 99, 84, 113, 102, 46, 118, 94})
bytes, _ := thisInt.Val.GobEncode()
h.Write(bytes)
thisInt.cachedHash = h.Sum64()
return h.Sum64()
}
func (thisInt *Integer) asBigFloat() *big.Float {
newfloat := big.NewFloat(0)
newfloat.SetInt(thisInt.Val)
return newfloat
}
func (thisInt *Integer) addI(i *Integer) {
thisInt.Val.Add(thisInt.Val, i.Val)
thisInt.cachedHash = 0
}
func (thisInt *Integer) mulI(i *Integer) {
thisInt.Val.Mul(thisInt.Val, i.Val)
thisInt.cachedHash = 0
}<|fim▁end|> | if thisInt.Val.Cmp(otherConv.Val) != 0 { |
<|file_name|>buddy.py<|end_file_name|><|fim▁begin|>__author__ = "Steffen Vogel"
__copyright__ = "Copyright 2015, Steffen Vogel"
__license__ = "GPLv3"
__maintainer__ = "Steffen Vogel"
__email__ = "[email protected]"
"""
This file is part of transWhat
transWhat 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
any later version.
transwhat 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 transWhat. If not, see <http://www.gnu.org/licenses/>.
"""
from Spectrum2 import protocol_pb2
import logging
import time
import utils
import base64
import deferred
from deferred import call
class Buddy():
def __init__(self, owner, number, nick, statusMsg, groups, image_hash):
self.nick = nick
self.owner = owner
self.number = number
self.groups = groups
self.image_hash = image_hash if image_hash is not None else ""
self.statusMsg = u""
self.lastseen = 0
self.presence = 0
def update(self, nick, groups, image_hash):
self.nick = nick
self.groups = groups
if image_hash is not None:
self.image_hash = image_hash
def __str__(self):
return "%s (nick=%s)" % (self.number, self.nick)
class BuddyList(dict):
def __init__(self, owner, backend, user, session):
self.owner = owner
self.backend = backend
self.session = session
self.user = user
self.logger = logging.getLogger(self.__class__.__name__)
self.synced = False
def _load(self, buddies):
for buddy in buddies:
number = buddy.buddyName
nick = buddy.alias
statusMsg = buddy.statusMessage.decode('utf-8')
groups = [g for g in buddy.group]
image_hash = buddy.iconHash
self[number] = Buddy(self.owner, number, nick, statusMsg,
groups, image_hash)
self.logger.debug("Update roster")
contacts = self.keys()
contacts.remove('bot')
if self.synced == False:
self.session.sendSync(contacts, delta = False, interactive = True)
self.synced = True
self.logger.debug("Roster add: %s", str(list(contacts)))
for number in contacts:
buddy = self[number]
self.backend.handleBuddyChanged(self.user, number, buddy.nick,
buddy.groups, protocol_pb2.STATUS_NONE,
iconHash = buddy.image_hash if buddy.image_hash is not None else "")
self.session.subscribePresence(number)
self.logger.debug("%s is requesting statuses of: %s", self.user, contacts)
self.session.requestStatuses(contacts, success = self.onStatus)
def onStatus(self, contacts):
self.logger.debug("%s received statuses of: %s", self.user, contacts)
for number, (status, time) in contacts.iteritems():
buddy = self[number]
if status is None:
buddy.statusMsg = ""
else:
buddy.statusMsg = utils.softToUni(status)
self.updateSpectrum(buddy)
def load(self, buddies):
if self.session.loggedIn:
self._load(buddies)
else:
self.session.loginQueue.append(lambda: self._load(buddies))
def update(self, number, nick, groups, image_hash):
if number in self:
buddy = self[number]
buddy.update(nick, groups, image_hash)
else:
buddy = Buddy(self.owner, number, nick, "", groups, image_hash)
self[number] = buddy
self.logger.debug("Roster add: %s", buddy)
self.session.sendSync([number], delta = True, interactive = True)
self.session.subscribePresence(number)
self.session.requestStatuses([number], success = self.onStatus)
if image_hash == "" or image_hash is None:
self.requestVCard(number)
self.updateSpectrum(buddy)
return buddy
def updateSpectrum(self, buddy):
if buddy.presence == 0:
status = protocol_pb2.STATUS_NONE
elif buddy.presence == 'unavailable':
status = protocol_pb2.STATUS_AWAY<|fim▁hole|>
statusmsg = buddy.statusMsg
if buddy.lastseen != 0:
timestamp = time.localtime(buddy.lastseen)
statusmsg += time.strftime("\n Last seen: %a, %d %b %Y %H:%M:%S", timestamp)
iconHash = buddy.image_hash if buddy.image_hash is not None else ""
self.logger.debug("Updating buddy %s (%s) in %s, image_hash = %s",
buddy.nick, buddy.number, buddy.groups, iconHash)
self.logger.debug("Status Message: %s", statusmsg)
self.backend.handleBuddyChanged(self.user, buddy.number, buddy.nick,
buddy.groups, status, statusMessage=statusmsg, iconHash=iconHash)
def remove(self, number):
try:
buddy = self[number]
del self[number]
self.backend.handleBuddyChanged(self.user, number, "", [],
protocol_pb2.STATUS_NONE)
self.backend.handleBuddyRemoved(self.user, number)
self.session.unsubscribePresence(number)
# TODO Sync remove
return buddy
except KeyError:
return None
def requestVCard(self, buddy, ID=None):
if buddy == self.user or buddy == self.user.split('@')[0]:
buddy = self.session.legacyName
# Get profile picture
self.logger.debug('Requesting profile picture of %s', buddy)
response = deferred.Deferred()
self.session.requestProfilePicture(buddy, onSuccess = response.run)
response = response.arg(0)
pictureData = response.pictureData()
# Send VCard
if ID != None:
call(self.logger.debug, 'Sending VCard (%s) with image id %s: %s',
ID, response.pictureId(), pictureData.then(base64.b64encode))
call(self.backend.handleVCard, self.user, ID, buddy, "", "",
pictureData)
# Send image hash
if not buddy == self.session.legacyName:
try:
obuddy = self[buddy]
nick = obuddy.nick
groups = obuddy.groups
except KeyError:
nick = ""
groups = []
image_hash = pictureData.then(utils.sha1hash)
call(self.logger.debug, 'Image hash is %s', image_hash)
call(self.update, buddy, nick, groups, image_hash)<|fim▁end|> | else:
status = protocol_pb2.STATUS_ONLINE |
<|file_name|>doc.go<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | // Package maths provides basic operations with floats and vectors
package maths |
<|file_name|>exercise11_4_2.py<|end_file_name|><|fim▁begin|>import math
Deleted = math.inf
def hash_delete(T, k, h):
m = T.length
i = 0
while True:
j = h(k, i, m)
if T[j] == k:
T[j] = Deleted
return<|fim▁hole|> i = i + 1
if T[j] is None or i == m:
break
def hash_insert_(T, k, h):
m = T.length
i = 0
while True:
j = h(k, i, m)
if T[j] is None or T[j] is Deleted:
T[j] = k
return j
else:
i = i + 1
if i == m:
break
raise RuntimeError('hash table overflow')<|fim▁end|> | |
<|file_name|>audio_low_latency_output_mac.cc<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/audio/mac/audio_low_latency_output_mac.h"
#include <CoreServices/CoreServices.h>
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/mac/mac_logging.h"
#include "media/audio/audio_util.h"
#include "media/audio/mac/audio_manager_mac.h"
#include "media/base/media_switches.h"
namespace media {
static std::ostream& operator<<(std::ostream& os,
const AudioStreamBasicDescription& format) {
os << "sample rate : " << format.mSampleRate << std::endl
<< "format ID : " << format.mFormatID << std::endl
<< "format flags : " << format.mFormatFlags << std::endl
<< "bytes per packet : " << format.mBytesPerPacket << std::endl
<< "frames per packet : " << format.mFramesPerPacket << std::endl
<< "bytes per frame : " << format.mBytesPerFrame << std::endl
<< "channels per frame: " << format.mChannelsPerFrame << std::endl
<< "bits per channel : " << format.mBitsPerChannel;
return os;
}
static AudioObjectPropertyAddress kDefaultOutputDeviceAddress = {
kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
// Overview of operation:
// 1) An object of AUAudioOutputStream is created by the AudioManager
// factory: audio_man->MakeAudioStream().
// 2) Next some thread will call Open(), at that point the underlying
// default output Audio Unit is created and configured.
// 3) Then some thread will call Start(source).
// Then the Audio Unit is started which creates its own thread which
// periodically will call the source for more data as buffers are being
// consumed.
// 4) At some point some thread will call Stop(), which we handle by directly
// stopping the default output Audio Unit.
// 6) The same thread that called stop will call Close() where we cleanup
// and notify the audio manager, which likely will destroy this object.
AUAudioOutputStream::AUAudioOutputStream(
AudioManagerMac* manager, const AudioParameters& params)
: manager_(manager),
source_(NULL),
output_unit_(0),<|fim▁hole|> volume_(1),
hardware_latency_frames_(0),
stopped_(false),
audio_bus_(AudioBus::Create(params)) {
// We must have a manager.
DCHECK(manager_);
// A frame is one sample across all channels. In interleaved audio the per
// frame fields identify the set of n |channels|. In uncompressed audio, a
// packet is always one frame.
format_.mSampleRate = params.sample_rate();
format_.mFormatID = kAudioFormatLinearPCM;
format_.mFormatFlags = kLinearPCMFormatFlagIsPacked |
kLinearPCMFormatFlagIsSignedInteger;
format_.mBitsPerChannel = params.bits_per_sample();
format_.mChannelsPerFrame = params.channels();
format_.mFramesPerPacket = 1;
format_.mBytesPerPacket = (format_.mBitsPerChannel * params.channels()) / 8;
format_.mBytesPerFrame = format_.mBytesPerPacket;
format_.mReserved = 0;
DVLOG(1) << "Desired ouput format: " << format_;
// Calculate the number of sample frames per callback.
number_of_frames_ = params.GetBytesPerBuffer() / format_.mBytesPerPacket;
DVLOG(1) << "Number of frames per callback: " << number_of_frames_;
const AudioParameters parameters =
manager_->GetDefaultOutputStreamParameters();
CHECK_EQ(number_of_frames_,
static_cast<size_t>(parameters.frames_per_buffer()));
}
AUAudioOutputStream::~AUAudioOutputStream() {
}
bool AUAudioOutputStream::Open() {
// Obtain the current input device selected by the user.
UInt32 size = sizeof(output_device_id_);
OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject,
&kDefaultOutputDeviceAddress,
0,
0,
&size,
&output_device_id_);
if (result != noErr || output_device_id_ == kAudioObjectUnknown) {
OSSTATUS_DLOG(WARNING, result)
<< "Could not get default audio output device.";
return false;
}
// Open and initialize the DefaultOutputUnit.
AudioComponent comp;
AudioComponentDescription desc;
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_DefaultOutput;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
comp = AudioComponentFindNext(0, &desc);
if (!comp)
return false;
result = AudioComponentInstanceNew(comp, &output_unit_);
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result) << "AudioComponentInstanceNew() failed.";
return false;
}
result = AudioUnitInitialize(output_unit_);
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result) << "AudioUnitInitialize() failed.";
return false;
}
hardware_latency_frames_ = GetHardwareLatency();
return Configure();
}
bool AUAudioOutputStream::Configure() {
// Set the render callback.
AURenderCallbackStruct input;
input.inputProc = InputProc;
input.inputProcRefCon = this;
OSStatus result = AudioUnitSetProperty(
output_unit_,
kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Global,
0,
&input,
sizeof(input));
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result)
<< "AudioUnitSetProperty(kAudioUnitProperty_SetRenderCallback) failed.";
return false;
}
// Set the stream format.
result = AudioUnitSetProperty(
output_unit_,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
0,
&format_,
sizeof(format_));
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result)
<< "AudioUnitSetProperty(kAudioUnitProperty_StreamFormat) failed.";
return false;
}
// Set the buffer frame size.
// WARNING: Setting this value changes the frame size for all audio units in
// the current process. It's imperative that the input and output frame sizes
// be the same as the frames_per_buffer() returned by
// GetDefaultOutputStreamParameters.
// See http://crbug.com/154352 for details.
UInt32 buffer_size = number_of_frames_;
result = AudioUnitSetProperty(
output_unit_,
kAudioDevicePropertyBufferFrameSize,
kAudioUnitScope_Output,
0,
&buffer_size,
sizeof(buffer_size));
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result)
<< "AudioUnitSetProperty(kAudioDevicePropertyBufferFrameSize) failed.";
return false;
}
return true;
}
void AUAudioOutputStream::Close() {
if (output_unit_)
AudioComponentInstanceDispose(output_unit_);
// Inform the audio manager that we have been closed. This can cause our
// destruction.
manager_->ReleaseOutputStream(this);
}
void AUAudioOutputStream::Start(AudioSourceCallback* callback) {
DCHECK(callback);
if (!output_unit_) {
DLOG(ERROR) << "Open() has not been called successfully";
return;
}
stopped_ = false;
{
base::AutoLock auto_lock(source_lock_);
source_ = callback;
}
AudioOutputUnitStart(output_unit_);
}
void AUAudioOutputStream::Stop() {
if (stopped_)
return;
AudioOutputUnitStop(output_unit_);
base::AutoLock auto_lock(source_lock_);
source_ = NULL;
stopped_ = true;
}
void AUAudioOutputStream::SetVolume(double volume) {
if (!output_unit_)
return;
volume_ = static_cast<float>(volume);
// TODO(crogers): set volume property
}
void AUAudioOutputStream::GetVolume(double* volume) {
if (!output_unit_)
return;
*volume = volume_;
}
// Pulls on our provider to get rendered audio stream.
// Note to future hackers of this function: Do not add locks here because this
// is running on a real-time thread (for low-latency).
OSStatus AUAudioOutputStream::Render(UInt32 number_of_frames,
AudioBufferList* io_data,
const AudioTimeStamp* output_time_stamp) {
// Update the playout latency.
double playout_latency_frames = GetPlayoutLatency(output_time_stamp);
AudioBuffer& buffer = io_data->mBuffers[0];
uint8* audio_data = reinterpret_cast<uint8*>(buffer.mData);
uint32 hardware_pending_bytes = static_cast<uint32>
((playout_latency_frames + 0.5) * format_.mBytesPerFrame);
// Unfortunately AUAudioInputStream and AUAudioOutputStream share the frame
// size set by kAudioDevicePropertyBufferFrameSize above on a per process
// basis. What this means is that the |number_of_frames| value may be larger
// or smaller than the value set during Configure(). In this case either
// audio input or audio output will be broken, so just output silence.
// TODO(crogers): Figure out what can trigger a change in |number_of_frames|.
// See http://crbug.com/154352 for details.
if (number_of_frames != static_cast<UInt32>(audio_bus_->frames())) {
memset(audio_data, 0, number_of_frames * format_.mBytesPerFrame);
return noErr;
}
int frames_filled = 0;
{
// Render() shouldn't be called except between AudioOutputUnitStart() and
// AudioOutputUnitStop() calls, but crash reports have shown otherwise:
// http://crbug.com/178765. We use |source_lock_| to prevent races and
// crashes in Render() when |source_| is cleared.
base::AutoLock auto_lock(source_lock_);
if (!source_) {
memset(audio_data, 0, number_of_frames * format_.mBytesPerFrame);
return noErr;
}
frames_filled = source_->OnMoreData(
audio_bus_.get(), AudioBuffersState(0, hardware_pending_bytes));
}
// Note: If this ever changes to output raw float the data must be clipped and
// sanitized since it may come from an untrusted source such as NaCl.
audio_bus_->ToInterleaved(
frames_filled, format_.mBitsPerChannel / 8, audio_data);
uint32 filled = frames_filled * format_.mBytesPerFrame;
// Perform in-place, software-volume adjustments.
media::AdjustVolume(audio_data,
filled,
audio_bus_->channels(),
format_.mBitsPerChannel / 8,
volume_);
return noErr;
}
// DefaultOutputUnit callback
OSStatus AUAudioOutputStream::InputProc(void* user_data,
AudioUnitRenderActionFlags*,
const AudioTimeStamp* output_time_stamp,
UInt32,
UInt32 number_of_frames,
AudioBufferList* io_data) {
AUAudioOutputStream* audio_output =
static_cast<AUAudioOutputStream*>(user_data);
if (!audio_output)
return -1;
return audio_output->Render(number_of_frames, io_data, output_time_stamp);
}
int AUAudioOutputStream::HardwareSampleRate() {
// Determine the default output device's sample-rate.
AudioDeviceID device_id = kAudioObjectUnknown;
UInt32 info_size = sizeof(device_id);
OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject,
&kDefaultOutputDeviceAddress,
0,
0,
&info_size,
&device_id);
if (result != noErr || device_id == kAudioObjectUnknown) {
OSSTATUS_DLOG(WARNING, result)
<< "Could not get default audio output device.";
return 0;
}
Float64 nominal_sample_rate;
info_size = sizeof(nominal_sample_rate);
AudioObjectPropertyAddress nominal_sample_rate_address = {
kAudioDevicePropertyNominalSampleRate,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
result = AudioObjectGetPropertyData(device_id,
&nominal_sample_rate_address,
0,
0,
&info_size,
&nominal_sample_rate);
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result)
<< "Could not get default sample rate for device: " << device_id;
return 0;
}
return static_cast<int>(nominal_sample_rate);
}
double AUAudioOutputStream::GetHardwareLatency() {
if (!output_unit_ || output_device_id_ == kAudioObjectUnknown) {
DLOG(WARNING) << "Audio unit object is NULL or device ID is unknown";
return 0.0;
}
// Get audio unit latency.
Float64 audio_unit_latency_sec = 0.0;
UInt32 size = sizeof(audio_unit_latency_sec);
OSStatus result = AudioUnitGetProperty(output_unit_,
kAudioUnitProperty_Latency,
kAudioUnitScope_Global,
0,
&audio_unit_latency_sec,
&size);
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result) << "Could not get audio unit latency";
return 0.0;
}
// Get output audio device latency.
AudioObjectPropertyAddress property_address = {
kAudioDevicePropertyLatency,
kAudioDevicePropertyScopeOutput,
kAudioObjectPropertyElementMaster
};
UInt32 device_latency_frames = 0;
size = sizeof(device_latency_frames);
result = AudioObjectGetPropertyData(output_device_id_,
&property_address,
0,
NULL,
&size,
&device_latency_frames);
if (result != noErr) {
OSSTATUS_DLOG(WARNING, result) << "Could not get audio unit latency";
return 0.0;
}
return static_cast<double>((audio_unit_latency_sec *
format_.mSampleRate) + device_latency_frames);
}
double AUAudioOutputStream::GetPlayoutLatency(
const AudioTimeStamp* output_time_stamp) {
// Ensure mHostTime is valid.
if ((output_time_stamp->mFlags & kAudioTimeStampHostTimeValid) == 0)
return 0;
// Get the delay between the moment getting the callback and the scheduled
// time stamp that tells when the data is going to be played out.
UInt64 output_time_ns = AudioConvertHostTimeToNanos(
output_time_stamp->mHostTime);
UInt64 now_ns = AudioConvertHostTimeToNanos(AudioGetCurrentHostTime());
// Prevent overflow leading to huge delay information; occurs regularly on
// the bots, probably less so in the wild.
if (now_ns > output_time_ns)
return 0;
double delay_frames = static_cast<double>
(1e-9 * (output_time_ns - now_ns) * format_.mSampleRate);
return (delay_frames + hardware_latency_frames_);
}
} // namespace media<|fim▁end|> | output_device_id_(kAudioObjectUnknown), |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible import constants as C
from ansible.errors import AnsibleParserError
from ansible.module_utils._text import to_text, to_native
from ansible.playbook.play import Play
from ansible.playbook.playbook_include import PlaybookInclude
from ansible.utils.display import Display
display = Display()
__all__ = ['Playbook']
class Playbook:
def __init__(self, loader):
# Entries in the datastructure of a playbook may
# be either a play or an include statement
self._entries = []
self._basedir = to_text(os.getcwd(), errors='surrogate_or_strict')
self._loader = loader
self._file_name = None
@staticmethod
def load(file_name, variable_manager=None, loader=None):
pb = Playbook(loader=loader)
pb._load_playbook_data(file_name=file_name, variable_manager=variable_manager)
return pb
def _load_playbook_data(self, file_name, variable_manager, vars=None):
if os.path.isabs(file_name):
self._basedir = os.path.dirname(file_name)
else:
self._basedir = os.path.normpath(os.path.join(self._basedir, os.path.dirname(file_name)))
# set the loaders basedir
cur_basedir = self._loader.get_basedir()
self._loader.set_basedir(self._basedir)
self._file_name = file_name
try:
ds = self._loader.load_from_file(os.path.basename(file_name))
except UnicodeDecodeError as e:
raise AnsibleParserError("Could not read playbook (%s) due to encoding issues: %s" % (file_name, to_native(e)))
# check for errors and restore the basedir in case this error is caught and handled
if not ds:
self._loader.set_basedir(cur_basedir)
raise AnsibleParserError("Empty playbook, nothing to do", obj=ds)
elif not isinstance(ds, list):
self._loader.set_basedir(cur_basedir)
raise AnsibleParserError("A playbook must be a list of plays, got a %s instead" % type(ds), obj=ds)
# Parse the playbook entries. For plays, we simply parse them
# using the Play() object, and includes are parsed using the
# PlaybookInclude() object
for entry in ds:<|fim▁hole|> self._loader.set_basedir(cur_basedir)
raise AnsibleParserError("playbook entries must be either a valid play or an include statement", obj=entry)
if any(action in entry for action in ('import_playbook', 'include')):
if 'include' in entry:
display.deprecated("'include' for playbook includes. You should use 'import_playbook' instead", version="2.12")
pb = PlaybookInclude.load(entry, basedir=self._basedir, variable_manager=variable_manager, loader=self._loader)
if pb is not None:
self._entries.extend(pb._entries)
else:
which = entry.get('import_playbook', entry.get('include', entry))
display.display("skipping playbook '%s' due to conditional test failure" % which, color=C.COLOR_SKIP)
else:
entry_obj = Play.load(entry, variable_manager=variable_manager, loader=self._loader, vars=vars)
self._entries.append(entry_obj)
# we're done, so restore the old basedir in the loader
self._loader.set_basedir(cur_basedir)
def get_loader(self):
return self._loader
def get_plays(self):
return self._entries[:]<|fim▁end|> | if not isinstance(entry, dict):
# restore the basedir in case this error is caught and handled |
<|file_name|>TransformBase64DecodeTest.java<|end_file_name|><|fim▁begin|>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* 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<|fim▁hole|>
import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.apache.xml.security.signature.XMLSignatureInput;
import org.apache.xml.security.test.dom.DSNamespaceContext;
import org.apache.xml.security.transforms.Transforms;
import org.apache.xml.security.transforms.implementations.TransformBase64Decode;
import org.apache.xml.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* Unit test for {@link org.apache.xml.security.transforms.implementations.TransformBase64Decode}
*
* @author Christian Geuer-Pollmann
*/
public class TransformBase64DecodeTest extends org.junit.Assert {
static org.slf4j.Logger log =
org.slf4j.LoggerFactory.getLogger(TransformBase64DecodeTest.class);
static {
org.apache.xml.security.Init.init();
}
@org.junit.Test
public void test1() throws Exception {
// base64 encoded
String s1 =
"VGhlIFVSSSBvZiB0aGUgdHJhbnNmb3JtIGlzIGh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1s\n"
+ "ZHNpZyNiYXNlNjQ=";
Document doc = TransformBase64DecodeTest.createDocument();
Transforms t = new Transforms(doc);
doc.appendChild(t.getElement());
t.addTransform(TransformBase64Decode.implementedTransformURI);
XMLSignatureInput in =
new XMLSignatureInput(new ByteArrayInputStream(s1.getBytes()));
XMLSignatureInput out = t.performTransforms(in);
String result = new String(out.getBytes());
assertTrue(
result.equals("The URI of the transform is http://www.w3.org/2000/09/xmldsig#base64")
);
}
@org.junit.Test
public void test2() throws Exception {
// base64 encoded twice
String s2 =
"VkdobElGVlNTU0J2WmlCMGFHVWdkSEpoYm5ObWIzSnRJR2x6SUdoMGRIQTZMeTkzZDNjdWR6TXVi\n"
+ "M0puTHpJd01EQXZNRGt2ZUcxcwpaSE5wWnlOaVlYTmxOalE9";
Document doc = TransformBase64DecodeTest.createDocument();
Transforms t = new Transforms(doc);
doc.appendChild(t.getElement());
t.addTransform(TransformBase64Decode.implementedTransformURI);
XMLSignatureInput in =
new XMLSignatureInput(new ByteArrayInputStream(s2.getBytes()));
XMLSignatureInput out = t.performTransforms(t.performTransforms(in));
String result = new String(out.getBytes());
assertTrue(
result.equals("The URI of the transform is http://www.w3.org/2000/09/xmldsig#base64")
);
}
@org.junit.Test
public void test3() throws Exception {
//J-
String input = ""
+ "<Object xmlns:signature='http://www.w3.org/2000/09/xmldsig#'>\n"
+ "<signature:Base64>\n"
+ "VGhlIFVSSSBvZiB0aGU gdHJhbn<RealText>Nmb 3JtIGlzIG<test/>h0dHA6</RealText>Ly93d3cudzMub3JnLzIwMDAvMDkveG1s\n"
+ "ZHNpZyNiYXNlNjQ=\n"
+ "</signature:Base64>\n"
+ "</Object>\n"
;
//J+
DocumentBuilder db = XMLUtils.createDocumentBuilder(false);
db.setErrorHandler(new org.apache.xml.security.utils.IgnoreAllErrorHandler());
Document doc = db.parse(new ByteArrayInputStream(input.getBytes()));
//XMLUtils.circumventBug2650(doc);
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
xpath.setNamespaceContext(new DSNamespaceContext());
String expression = "//ds:Base64";
Node base64Node =
(Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
XMLSignatureInput xmlinput = new XMLSignatureInput(base64Node);
Document doc2 = TransformBase64DecodeTest.createDocument();
Transforms t = new Transforms(doc2);
doc2.appendChild(t.getElement());
t.addTransform(Transforms.TRANSFORM_BASE64_DECODE);
XMLSignatureInput out = t.performTransforms(xmlinput);
String result = new String(out.getBytes());
assertTrue(
"\"" + result + "\"",
result.equals("The URI of the transform is http://www.w3.org/2000/09/xmldsig#base64")
);
}
private static Document createDocument() throws ParserConfigurationException {
DocumentBuilder db = XMLUtils.createDocumentBuilder(false);
Document doc = db.newDocument();
if (doc == null) {
throw new RuntimeException("Could not create a Document");
} else {
log.debug("I could create the Document");
}
return doc;
}
}<|fim▁end|> | * under the License.
*/
package org.apache.xml.security.test.dom.transforms.implementations; |
<|file_name|>requests.ts<|end_file_name|><|fim▁begin|>// https://developer.mozilla.org/ja/docs/Web/API/Navigator/doNotTrack
export function enable(): boolean {
const w: any = window
const dnt: string = w.navigator.doNotTrack || w.doNotTrack<|fim▁hole|> return false
}
return true
}
export function get(
url: string,
query: string[],
onerror: OnErrorEventHandler
): void {
if (enable() && query.length > 0) {
const img: HTMLImageElement = document.createElement('img')
img.onload = () => {
// nothing todo
}
img.onerror = onerror
img.src = `${url}?${query.join('&')}`
}
}
export function obj2query(data: { [key: string]: string }): string[] {
const query: string[] = []
Object.keys(data).forEach(key => {
if (data[key]) {
query.push(`${key}=${encodeURIComponent(data[key])}`)
}
})
return query
}<|fim▁end|> | if (dnt === '1' || dnt === 'yes') { |
<|file_name|>settings.py<|end_file_name|><|fim▁begin|><|fim▁hole|>
REDMINE_SERVER_URL = getattr(settings, 'REDMINE_SERVER_URL', 'https://localhost')<|fim▁end|> | from django.conf import settings |
<|file_name|>header.js<|end_file_name|><|fim▁begin|>import $ from 'jquery';
import { router } from 'src/router';
import './header.scss';
export default class Header {
static selectors = {
button: '.header__enter',
search: '.header__search'
};
constructor($root) {
this.elements = {
$root,
$window: $(window)
};
this.attachEvents();
}
attachEvents() {
this.elements.$root.on('click', Header.selectors.button, this.handleClick)
}
handleClick = () => {
const search = $(Header.selectors.search).val();
if (search) {
router.navigate(`/search?query=${search}`);
}
}<|fim▁hole|>}<|fim▁end|> | |
<|file_name|>schematic_type_map.py<|end_file_name|><|fim▁begin|>'''
Created on Mar 20, 2011
@author: frederikns
'''
from model.flyweight import Flyweight
from collections import namedtuple
from model.static.database import database
from model.dynamic.inventory.item import Item
class SchematicTypeMap(Flyweight):
def __init__(self,schematic_id):
#prevents reinitializing
if "_inited" in self.__dict__:
return
self._inited = None
#prevents reinitializing
self.schematic_id = schematic_id
cursor = database.get_cursor(
"select * from planetSchematicTypeMap where schematicID={};".format(self.schematic_id))
types = list()
<|fim▁hole|>
for row in cursor:
types.append(schematic_type(
item=Item(row["typeID"], row["quantity"]),
is_input=(row["isInput"])))
cursor.close()<|fim▁end|> | schematic_type = namedtuple("schematic_type", "item, is_input") |
<|file_name|>atom_installer.py<|end_file_name|><|fim▁begin|># Author: Ahmed Husam Elsers
# Email: [email protected]
# This is a Python3 script to install/upgrade Atom for Linux (Fedora, Ubuntu)
# Check The Host Linux Distro (Fedora/Ubuntu)
# Check if Atom installed or Not
# If Installed:
# check the latest version on Atom web page
# then compare it to installed
# if latest > installed:
# upgrade()
# if latest == installed:
# inform and exit
# If Not Installed:
# download()
# install()
import os
import platform
import re
import subprocess
import sys
import urllib.request
def check_linux_distro():
if platform.architecture()[0] == '64bit':
if 'fedora' in (platform.platform()).lower():
linux_distro = 'fedora'
if 'ubuntu' or 'debian' in (platform.platform()).lower():
linux_distro = 'ubuntu'
return linux_distro
else:
print("Sorry, Unsupported Linux Distro.")
sys.exit(1)
def atom_latest(atom_base_url, atom_latest_url, linux_distro):
try:
with urllib.request.urlopen(atom_latest_url) as atom_urlopened:
atom_url_read = str(atom_urlopened.read())
latest_version_num = re.search(
r"/atom/atom/releases/tag/v([\w.]+)", atom_url_read).group(1)
if linux_distro == 'fedora':
rpm_link = atom_base_url + \
re.search(r"/atom/atom/releases/download/v{0}/atom[.-]+[^\d][a-zA-Z\d_]+[.]{1}".format(
latest_version_num, 'rpm'), atom_url_read).group()
return rpm_link, latest_version_num
if linux_distro == 'ubuntu':
deb_link = atom_base_url + \
re.search(r"/atom/atom/releases/download/v{0}/atom[.-]+[^\d][a-zA-Z\d_]+[.]{1}".format(
latest_version_num, 'deb'), atom_url_read).group()
return deb_link, latest_version_num
except:
print("Atom website is not reachable!!")
print("Please Check Your Internet Connection.")
sys.exit(1)
def atom_installed(linux_distro):
try:
if linux_distro == 'fedora':
installed_status = subprocess.getstatusoutput('rpm -q atom')[0]
if installed_status == 0:
installed_version = re.search(
r"atom-([\d.]+)-\w+", subprocess.getoutput('rpm -q atom')).group(1)
if linux_distro == 'ubuntu':
installed_status = subprocess.getstatusoutput('dpkg -s atom')[0]
if installed_status == 0:
installed_version = re.search(
r"Version: ([\d.]+)", subprocess.getoutput('dpkg -s atom')).group(1)
return (True, installed_version)
except:
return (False, '')
def get_atom_install(linux_distro, atom_link):
if linux_distro == 'fedora':
subprocess.run(['wget', '-c', atom_link, '-O', os.path.join('/tmp/', os.path.basename(atom_link))])
subprocess.run(['sudo', 'dnf', '-y', 'install', os.path.join('/tmp/', os.path.basename(atom_link))])
print("Thank You for using my Script.")
if linux_distro == 'ubuntu':
subprocess.run(['wget', '-c', atom_link, '-O', os.path.join('/tmp/', os.path.basename(atom_link))])
subprocess.run(['sudo', 'dpkg', '-i', os.path.join('/tmp/', os.path.basename(atom_link))])
print("Thank You for using my Script.")
def main():
try:
atom_base_url = 'https://github.com'
atom_latest_url = 'https://github.com/atom/atom/releases/latest'
<|fim▁hole|> linux_distro = check_linux_distro()
atom_link_pkgver_latest = atom_latest(atom_base_url, atom_latest_url, linux_distro)
is_atom_installed = atom_installed(linux_distro)
if is_atom_installed[0]:
if atom_link_pkgver_latest[1] > is_atom_installed[1]:
get_atom_install(linux_distro, atom_link_pkgver_latest[0])
if atom_link_pkgver_latest[1] == is_atom_installed[1]:
print("You already have atom latest installed, Good for You.")
print("Thank You for using my Script.")
sys.exit(0)
else:
get_atom_install(linux_distro, atom_link_pkgver_latest[0])
except KeyboardInterrupt:
print("\nIt seems you entered Ctl-C, run the script again when you ready.")
print("Thank You anyway.")
if __name__ == '__main__':
main()<|fim▁end|> | |
<|file_name|>environ.py<|end_file_name|><|fim▁begin|>"""
Django-environ allows you to utilize 12factor inspired environment
variables to configure your Django application.
"""
import json
import logging
import os
import re
import sys
import warnings
from django.core.exceptions import ImproperlyConfigured
from six.moves import urllib_parse as urlparse
from six import string_types
logger = logging.getLogger(__file__)
__author__ = 'joke2k'
__version__ = (0, 4, 0)
# return int if possible
def _cast_int(v):
return int(v) if hasattr(v, 'isdigit') and v.isdigit() else v
class NoValue(object):
def __repr__(self):
return '<{0}>'.format(self.__class__.__name__)
class Env(object):
"""Provide scheme-based lookups of environment variables so that each
caller doesn't have to pass in `cast` and `default` parameters.
Usage:::
env = Env(MAIL_ENABLED=bool, SMTP_LOGIN=(str, 'DEFAULT'))
if env('MAIL_ENABLED'):
...
"""
NOTSET = NoValue()
BOOLEAN_TRUE_STRINGS = ('true', 'on', 'ok', 'y', 'yes', '1')
URL_CLASS = urlparse.ParseResult
DEFAULT_DATABASE_ENV = 'DATABASE_URL'
DB_SCHEMES = {
'postgres': 'django.db.backends.postgresql_psycopg2',
'postgresql': 'django.db.backends.postgresql_psycopg2',
'psql': 'django.db.backends.postgresql_psycopg2',
'pgsql': 'django.db.backends.postgresql_psycopg2',
'postgis': 'django.contrib.gis.db.backends.postgis',
'mysql': 'django.db.backends.mysql',
'mysql2': 'django.db.backends.mysql',
'mysqlgis': 'django.contrib.gis.db.backends.mysql',
'spatialite': 'django.contrib.gis.db.backends.spatialite',
'sqlite': 'django.db.backends.sqlite3',
'ldap': 'ldapdb.backends.ldap',
}
_DB_BASE_OPTIONS = ['CONN_MAX_AGE', 'ATOMIC_REQUESTS', 'AUTOCOMMIT']
DEFAULT_CACHE_ENV = 'CACHE_URL'
CACHE_SCHEMES = {
'dbcache': 'django.core.cache.backends.db.DatabaseCache',
'dummycache': 'django.core.cache.backends.dummy.DummyCache',
'filecache': 'django.core.cache.backends.filebased.FileBasedCache',
'locmemcache': 'django.core.cache.backends.locmem.LocMemCache',
'memcache': 'django.core.cache.backends.memcached.MemcachedCache',
'pymemcache': 'django.core.cache.backends.memcached.PyLibMCCache',
'rediscache': 'django_redis.cache.RedisCache',
'redis': 'django_redis.cache.RedisCache',
}
_CACHE_BASE_OPTIONS = ['TIMEOUT', 'KEY_PREFIX', 'VERSION', 'KEY_FUNCTION']
DEFAULT_EMAIL_ENV = 'EMAIL_URL'
EMAIL_SCHEMES = {
'smtp': 'django.core.mail.backends.smtp.EmailBackend',
'smtps': 'django.core.mail.backends.smtp.EmailBackend',
'smtp+tls': 'django.core.mail.backends.smtp.EmailBackend',
'smtp+ssl': 'django.core.mail.backends.smtp.EmailBackend',
'consolemail': 'django.core.mail.backends.console.EmailBackend',
'filemail': 'django.core.mail.backends.filebased.EmailBackend',
'memorymail': 'django.core.mail.backends.locmem.EmailBackend',
'dummymail': 'django.core.mail.backends.dummy.EmailBackend'
}
_EMAIL_BASE_OPTIONS = ['EMAIL_USE_TLS', 'EMAIL_USE_SSL']
DEFAULT_SEARCH_ENV = 'SEARCH_URL'
SEARCH_SCHEMES = {
"elasticsearch": "haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine",
"solr": "haystack.backends.solr_backend.SolrEngine",
"whoosh": "haystack.backends.whoosh_backend.WhooshEngine",
"simple": "haystack.backends.simple_backend.SimpleEngine",
}
def __init__(self, **scheme):
self.scheme = scheme
def __call__(self, var, cast=None, default=NOTSET, parse_default=False):
return self.get_value(var, cast=cast, default=default, parse_default=parse_default)
# Shortcuts
def str(self, var, default=NOTSET):
"""
:rtype: str
"""
return self.get_value(var, default=default)
def unicode(self, var, default=NOTSET):
"""Helper for python2
:rtype: unicode
"""
return self.get_value(var, cast=str, default=default)
def bool(self, var, default=NOTSET):
"""
:rtype: bool
"""
return self.get_value(var, cast=bool, default=default)
def int(self, var, default=NOTSET):
"""
:rtype: int
"""
return self.get_value(var, cast=int, default=default)
def float(self, var, default=NOTSET):
"""
:rtype: float
"""
return self.get_value(var, cast=float, default=default)
def json(self, var, default=NOTSET):
"""
:returns: Json parsed
"""
return self.get_value(var, cast=json.loads, default=default)
def list(self, var, cast=None, default=NOTSET):
"""
:rtype: list
"""
return self.get_value(var, cast=list if not cast else [cast], default=default)
def dict(self, var, cast=dict, default=NOTSET):
"""
:rtype: dict
"""
return self.get_value(var, cast=cast, default=default)
def url(self, var, default=NOTSET):
"""
:rtype: urlparse.ParseResult
"""
return self.get_value(var, cast=urlparse.urlparse, default=default, parse_default=True)
def db_url(self, var=DEFAULT_DATABASE_ENV, default=NOTSET, engine=None):
"""Returns a config dictionary, defaulting to DATABASE_URL.
:rtype: dict
"""
return self.db_url_config(self.get_value(var, default=default), engine=engine)
db = db_url
def cache_url(self, var=DEFAULT_CACHE_ENV, default=NOTSET, backend=None):
"""Returns a config dictionary, defaulting to CACHE_URL.
:rtype: dict
"""
return self.cache_url_config(self.url(var, default=default), backend=backend)
cache = cache_url
def email_url(self, var=DEFAULT_EMAIL_ENV, default=NOTSET, backend=None):
"""Returns a config dictionary, defaulting to EMAIL_URL.
:rtype: dict
"""
return self.email_url_config(self.url(var, default=default), backend=backend)
email = email_url
def search_url(self, var=DEFAULT_SEARCH_ENV, default=NOTSET, engine=None):
"""Returns a config dictionary, defaulting to SEARCH_URL.
:rtype: dict
"""
return self.search_url_config(self.url(var, default=default), engine=engine)
def path(self, var, default=NOTSET, **kwargs):
"""
:rtype: Path
"""
return Path(self.get_value(var, default=default), **kwargs)
def get_value(self, var, cast=None, default=NOTSET, parse_default=False):
"""Return value for given environment variable.
:param var: Name of variable.
:param cast: Type to cast return value as.
:param default: If var not present in environ, return this instead.
:param parse_default: force to parse default..
:returns: Value from environment or default (if set)
"""
logger.debug("get '{0}' casted as '{1}' with default '{2}'".format(var, cast, default))
if var in self.scheme:
var_info = self.scheme[var]
try:
has_default = len(var_info) == 2
except TypeError:
has_default = False
if has_default:
if not cast:
cast = var_info[0]
if default is self.NOTSET:
try:
default = var_info[1]
except IndexError:
pass
else:
if not cast:
cast = var_info
try:
value = os.environ[var]
except KeyError:
if default is self.NOTSET:
error_msg = "Set the {0} environment variable".format(var)
raise ImproperlyConfigured(error_msg)
value = default
# Resolve any proxied values
if hasattr(value, 'startswith') and value.startswith('$'):
value = value.lstrip('$')
value = self.get_value(value, cast=cast, default=default)
if value != default or parse_default:
value = self.parse_value(value, cast)
return value
# Class and static methods
@classmethod
def parse_value(cls, value, cast):
"""Parse and cast provided value
:param value: Stringed value.
:param cast: Type to cast return value as.
:returns: Casted value
"""
if cast is None:
return value
elif cast is bool:
try:
value = int(value) != 0
except ValueError:
value = value.lower() in cls.BOOLEAN_TRUE_STRINGS
elif isinstance(cast, list):
value = list(map(cast[0], [x for x in value.split(',') if x]))
elif isinstance(cast, dict):
key_cast = cast.get('key', str)
value_cast = cast.get('value', str)
value_cast_by_key = cast.get('cast', dict())
value = dict(map(
lambda kv: (key_cast(kv[0]), cls.parse_value(kv[1], value_cast_by_key.get(kv[0], value_cast))),
[val.split('=') for val in value.split(';') if val]
))
elif cast is dict:
value = dict([val.split('=') for val in value.split(',') if val])
elif cast is list:
value = [x for x in value.split(',') if x]
elif cast is float:
# clean string
float_str = re.sub(r'[^\d,\.]', '', value)
# split for avoid thousand separator and different locale comma/dot symbol
parts = re.split(r'[,\.]', float_str)
if len(parts) == 1:
float_str = parts[0]
else:
float_str = "{0}.{1}".format(''.join(parts[0:-1]), parts[-1])
value = float(float_str)
else:
value = cast(value)
return value
@classmethod
def db_url_config(cls, url, engine=None):
"""Pulled from DJ-Database-URL, parse an arbitrary Database URL.
Support currently exists for PostgreSQL, PostGIS, MySQL and SQLite.
SQLite connects to file based databases. The same URL format is used, omitting the hostname,
and using the "file" portion as the filename of the database.
This has the effect of four slashes being present for an absolute file path:
>>> from environ import Env
>>> Env.db_url_config('sqlite:////full/path/to/your/file.sqlite')
{'ENGINE': 'django.db.backends.sqlite3', 'HOST': None, 'NAME': '/full/path/to/your/file.sqlite', 'PASSWORD': None, 'PORT': None, 'USER': None}
>>> Env.db_url_config('postgres://uf07k1i6d8ia0v:[email protected]:5431/d8r82722r2kuvn')
{'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': 'ec2-107-21-253-135.compute-1.amazonaws.com', 'NAME': 'd8r82722r2kuvn', 'PASSWORD': 'wegauwhgeuioweg', 'PORT': 5431, 'USER': 'uf07k1i6d8ia0v'}
"""
if not isinstance(url, cls.URL_CLASS):
if url == 'sqlite://:memory:':
# this is a special case, because if we pass this URL into
# urlparse, urlparse will choke trying to interpret "memory"
# as a port number
return {
'ENGINE': cls.DB_SCHEMES['sqlite'],
'NAME': ':memory:'
}
# note: no other settings are required for sqlite
url = urlparse.urlparse(url)
config = {}
# Remove query strings.
path = url.path[1:]
path = path.split('?', 2)[0]
# if we are using sqlite and we have no path, then assume we
# want an in-memory database (this is the behaviour of sqlalchemy)
if url.scheme == 'sqlite' and path == '':
path = ':memory:'
if url.scheme == 'ldap':
path = '{scheme}://{hostname}'.format(scheme=url.scheme, hostname=url.hostname)
if url.port:
path += ':{port}'.format(port=url.port)
# Update with environment configuration.
config.update({
'NAME': path,
'USER': url.username,
'PASSWORD': url.password,
'HOST': url.hostname,
'PORT': _cast_int(url.port),
})
if url.query:
config_options = {}
for k, v in urlparse.parse_qs(url.query).items():
if k.upper() in cls._DB_BASE_OPTIONS:
config.update({k.upper(): _cast_int(v[0])})
else:
config_options.update({k: _cast_int(v[0])})
config['OPTIONS'] = config_options
if engine:
config['ENGINE'] = engine
if url.scheme in Env.DB_SCHEMES:
config['ENGINE'] = Env.DB_SCHEMES[url.scheme]
if not config.get('ENGINE', False):
warnings.warn("Engine not recognized from url: {0}".format(config))
return {}
return config
<|fim▁hole|> """Pulled from DJ-Cache-URL, parse an arbitrary Cache URL.
:param url:
:param overrides:
:return:
"""
url = urlparse.urlparse(url) if not isinstance(url, cls.URL_CLASS) else url
location = url.netloc.split(',')
if len(location) == 1:
location = location[0]
config = {
'BACKEND': cls.CACHE_SCHEMES[url.scheme],
'LOCATION': location,
}
if url.scheme == 'filecache':
config.update({
'LOCATION': url.netloc + url.path,
})
if url.path and url.scheme in ['memcache', 'pymemcache', 'rediscache']:
config.update({
'LOCATION': 'unix:' + url.path,
})
if url.query:
config_options = {}
for k, v in urlparse.parse_qs(url.query).items():
opt = {k.upper(): _cast_int(v[0])}
if k.upper() in cls._CACHE_BASE_OPTIONS:
config.update(opt)
else:
config_options.update(opt)
config['OPTIONS'] = config_options
if backend:
config['BACKEND'] = backend
return config
@classmethod
def email_url_config(cls, url, backend=None):
"""Parses an email URL."""
config = {}
url = urlparse.urlparse(url) if not isinstance(url, cls.URL_CLASS) else url
# Remove query strings
path = url.path[1:]
path = path.split('?', 2)[0]
# Update with environment configuration
config.update({
'EMAIL_FILE_PATH': path,
'EMAIL_HOST_USER': url.username,
'EMAIL_HOST_PASSWORD': url.password,
'EMAIL_HOST': url.hostname,
'EMAIL_PORT': _cast_int(url.port),
})
if backend:
config['EMAIL_BACKEND'] = backend
elif url.scheme in cls.EMAIL_SCHEMES:
config['EMAIL_BACKEND'] = cls.EMAIL_SCHEMES[url.scheme]
if url.scheme in ('smtps', 'smtp+tls'):
config['EMAIL_USE_TLS'] = True
elif url.scheme == 'smtp+ssl':
config['EMAIL_USE_SSL'] = True
if url.query:
config_options = {}
for k, v in urlparse.parse_qs(url.query).items():
opt = {k.upper(): _cast_int(v[0])}
if k.upper() in cls._EMAIL_BASE_OPTIONS:
config.update(opt)
else:
config_options.update(opt)
config['OPTIONS'] = config_options
return config
@classmethod
def search_url_config(cls, url, engine=None):
config = {}
url = urlparse.urlparse(url) if not isinstance(url, cls.URL_CLASS) else url
# Remove query strings.
path = url.path[1:]
path = path.split('?', 2)[0]
if url.scheme in cls.SEARCH_SCHEMES:
config["ENGINE"] = cls.SEARCH_SCHEMES[url.scheme]
if path.endswith("/"):
path = path[:-1]
split = path.rsplit("/", 1)
if len(split) > 1:
path = split[:-1]
index = split[-1]
else:
path = ""
index = split[0]
config.update({
"URL": urlparse.urlunparse(("http",) + url[1:2] + (path,) + url[3:]),
"INDEX_NAME": index,
})
if path:
config.update({
"PATH": path,
})
if engine:
config['ENGINE'] = engine
return config
@staticmethod
def read_env(env_file=None, **overrides):
"""Read a .env file into os.environ.
If not given a path to a dotenv path, does filthy magic stack backtracking
to find manage.py and then find the dotenv.
http://www.wellfireinteractive.com/blog/easier-12-factor-django/
https://gist.github.com/bennylope/2999704
"""
if env_file is None:
frame = sys._getframe()
env_file = os.path.join(os.path.dirname(frame.f_back.f_code.co_filename), '.env')
if not os.path.exists(env_file):
warnings.warn("not reading %s - it doesn't exist." % env_file)
return
try:
with open(env_file) if isinstance(env_file, string_types) else env_file as f:
content = f.read()
except IOError:
warnings.warn("not reading %s - it doesn't exist." % env_file)
return
logger.debug('Read environment variables from: {0}'.format(env_file))
for line in content.splitlines():
m1 = re.match(r'\A([A-Za-z_0-9]+)=(.*)\Z', line)
if m1:
key, val = m1.group(1), m1.group(2)
m2 = re.match(r"\A'(.*)'\Z", val)
if m2:
val = m2.group(1)
m3 = re.match(r'\A"(.*)"\Z', val)
if m3:
val = re.sub(r'\\(.)', r'\1', m3.group(1))
os.environ.setdefault(key, str(val))
# set defaults
for key, value in overrides.items():
os.environ.setdefault(key, value)
class Path(object):
"""Inspired to Django Two-scoops, handling File Paths in Settings.
>>> from environ import Path
>>> root = Path('/home')
>>> root, root(), root('dev')
(<Path:/home>, '/home', '/home/dev')
>>> root == Path('/home')
True
>>> root in Path('/'), root not in Path('/other/path')
(True, True)
>>> root('dev', 'not_existing_dir', required=True)
Traceback (most recent call last):
environ.environ.ImproperlyConfigured: Create required path: /home/not_existing_dir
>>> public = root.path('public')
>>> public, public.root, public('styles')
(<Path:/home/public>, '/home/public', '/home/public/styles')
>>> assets, scripts = public.path('assets'), public.path('assets', 'scripts')
>>> assets.root, scripts.root
('/home/public/assets', '/home/public/assets/scripts')
>>> assets + 'styles', str(assets + 'styles'), ~assets
(<Path:/home/public/assets/styles>, '/home/public/assets/styles', <Path:/home/public>)
"""
def path(self, *paths, **kwargs):
"""Create new Path based on self.root and provided paths.
:param paths: List of sub paths
:param kwargs: required=False
:rtype: Path
"""
return self.__class__(self.__root__, *paths, **kwargs)
def file(self, name, *args, **kwargs):
"""Open a file.
:param name: Filename appended to self.root
:param args: passed to open()
:param kwargs: passed to open()
:rtype: file
"""
return open(self(name), *args, **kwargs)
@property
def root(self):
"""Current directory for this Path"""
return self.__root__
def __init__(self, start='', *paths, **kwargs):
super(Path, self).__init__()
if kwargs.get('is_file', False):
start = os.path.dirname(start)
self.__root__ = self._absolute_join(start, *paths, **kwargs)
def __call__(self, *paths, **kwargs):
"""Retrieve the absolute path, with appended paths
:param paths: List of sub path of self.root
:param kwargs: required=False
"""
return self._absolute_join(self.__root__, *paths, **kwargs)
def __eq__(self, other):
return self.__root__ == other.__root__
def __ne__(self, other):
return not self.__eq__(other)
def __add__(self, other):
return Path(self.__root__, other if not isinstance(other, Path) else other.__root__)
def __sub__(self, other):
if isinstance(other, int):
return self.path('../' * other)
elif isinstance(other, string_types):
return Path(self.__root__.rstrip(other))
raise TypeError("unsupported operand type(s) for -: '{0}' and '{1}'".format(self, type(other)))
def __invert__(self):
return self.path('..')
def __contains__(self, item):
base_path = self.__root__
if len(base_path) > 1:
base_path = os.path.join(base_path, '')
return item.__root__.startswith(base_path)
def __repr__(self):
return "<Path:{0}>".format(self.__root__)
def __str__(self):
return self.__root__
def __unicode__(self):
return self.__str__()
@staticmethod
def _absolute_join(base, *paths, **kwargs):
absolute_path = os.path.abspath(os.path.join(base, *paths))
if kwargs.get('required', False) and not os.path.exists(absolute_path):
raise ImproperlyConfigured("Create required path: {0}".format(absolute_path))
return absolute_path
def register_scheme(scheme):
for method in dir(urlparse):
if method.startswith('uses_'):
getattr(urlparse, method).append(scheme)
def register_schemes(schemes):
for scheme in schemes:
register_scheme(scheme)
# Register database and cache schemes in URLs.
register_schemes(Env.DB_SCHEMES.keys())
register_schemes(Env.CACHE_SCHEMES.keys())
register_schemes(Env.SEARCH_SCHEMES.keys())
register_schemes(Env.EMAIL_SCHEMES.keys())<|fim▁end|> | @classmethod
def cache_url_config(cls, url, backend=None): |
<|file_name|>tokenizer.go<|end_file_name|><|fim▁begin|>// Copyright (c) 2014 Couchbase, Inc.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
package registry
import (
"fmt"
"github.com/blevesearch/bleve/analysis"
)
func RegisterTokenizer(name string, constructor TokenizerConstructor) {
_, exists := tokenizers[name]
if exists {
panic(fmt.Errorf("attempted to register duplicate tokenizer named '%s'", name))
}
tokenizers[name] = constructor
}
type TokenizerConstructor func(config map[string]interface{}, cache *Cache) (analysis.Tokenizer, error)
type TokenizerRegistry map[string]TokenizerConstructor
type TokenizerCache map[string]analysis.Tokenizer
func (c TokenizerCache) TokenizerNamed(name string, cache *Cache) (analysis.Tokenizer, error) {
tokenizer, cached := c[name]
if cached {
return tokenizer, nil
}
tokenizerConstructor, registered := tokenizers[name]
if !registered {
return nil, fmt.Errorf("no tokenizer with name or type '%s' registered", name)
}
tokenizer, err := tokenizerConstructor(nil, cache)
if err != nil {
return nil, fmt.Errorf("error building tokenizer '%s': %v", name, err)
}
c[name] = tokenizer
return tokenizer, nil
}
func (c TokenizerCache) DefineTokenizer(name string, typ string, config map[string]interface{}, cache *Cache) (analysis.Tokenizer, error) {
_, cached := c[name]
if cached {
return nil, fmt.Errorf("tokenizer named '%s' already defined", name)
}
tokenizerConstructor, registered := tokenizers[typ]
if !registered {
return nil, fmt.Errorf("no tokenizer type '%s' registered", typ)<|fim▁hole|> return nil, fmt.Errorf("error building tokenizer '%s': %v", name, err)
}
c[name] = tokenizer
return tokenizer, nil
}
func TokenizerTypesAndInstances() ([]string, []string) {
emptyConfig := map[string]interface{}{}
emptyCache := NewCache()
types := make([]string, 0)
instances := make([]string, 0)
for name, cons := range tokenizers {
_, err := cons(emptyConfig, emptyCache)
if err == nil {
instances = append(instances, name)
} else {
types = append(types, name)
}
}
return types, instances
}<|fim▁end|> | }
tokenizer, err := tokenizerConstructor(config, cache)
if err != nil { |
<|file_name|>App.tsx<|end_file_name|><|fim▁begin|>import React from 'react';
import { Provider } from 'react-redux';
import Home from './app/Home';
import { store } from './app/store';
declare const module: any;<|fim▁hole|> <Home />
</Provider>
);
if (module.hot) {
module.hot.accept();
}
export default App;<|fim▁end|> | const App = () => (
<Provider store={store}> |
<|file_name|>ShowTitleTrueTestCase.java<|end_file_name|><|fim▁begin|>package fr.jmini.asciidoctorj.testcases;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.asciidoctor.AttributesBuilder;
import org.asciidoctor.OptionsBuilder;
import org.asciidoctor.ast.Block;
import org.asciidoctor.ast.Document;
import org.asciidoctor.ast.Title;
public class ShowTitleTrueTestCase implements AdocTestCase {
public static final String ASCIIDOC = "" +
"= My page\n" +
"\n" +
"Some text\n" +
"";
@Override
public String getAdocInput() {
return ASCIIDOC;
}
@Override
public Map<String, Object> getInputOptions() {
AttributesBuilder attributesBuilder = AttributesBuilder.attributes()
.showTitle(true);
return OptionsBuilder.options()
.attributes(attributesBuilder)
.asMap();
}
// tag::expected-html[]
public static final String EXPECTED_HTML = "" +
"<h1>My page</h1>\n" +
"<div class=\"paragraph\">\n" +
"<p>Some text</p>\n" +
"</div>";
// end::expected-html[]
@Override
public String getHtmlOutput() {
return EXPECTED_HTML;
}
@Override
// tag::assert-code[]
public void checkAst(Document astDocument) {
Document document1 = astDocument;<|fim▁hole|> assertThat(document1.getId()).isNull();
assertThat(document1.getNodeName()).isEqualTo("document");
assertThat(document1.getParent()).isNull();
assertThat(document1.getContext()).isEqualTo("document");
assertThat(document1.getDocument()).isSameAs(document1);
assertThat(document1.isInline()).isFalse();
assertThat(document1.isBlock()).isTrue();
assertThat(document1.getAttributes()).containsEntry("doctitle", "My page")
.containsEntry("doctype", "article")
.containsEntry("example-caption", "Example")
.containsEntry("figure-caption", "Figure")
.containsEntry("filetype", "html")
.containsEntry("notitle", "")
.containsEntry("prewrap", "")
.containsEntry("showtitle", true)
.containsEntry("table-caption", "Table");
assertThat(document1.getRoles()).isNullOrEmpty();
assertThat(document1.isReftext()).isFalse();
assertThat(document1.getReftext()).isNull();
assertThat(document1.getCaption()).isNull();
assertThat(document1.getTitle()).isNull();
assertThat(document1.getStyle()).isNull();
assertThat(document1.getLevel()).isEqualTo(0);
assertThat(document1.getContentModel()).isEqualTo("compound");
assertThat(document1.getSourceLocation()).isNull();
assertThat(document1.getSubstitutions()).isNullOrEmpty();
assertThat(document1.getBlocks()).hasSize(1);
Block block1 = (Block) document1.getBlocks()
.get(0);
assertThat(block1.getId()).isNull();
assertThat(block1.getNodeName()).isEqualTo("paragraph");
assertThat(block1.getParent()).isSameAs(document1);
assertThat(block1.getContext()).isEqualTo("paragraph");
assertThat(block1.getDocument()).isSameAs(document1);
assertThat(block1.isInline()).isFalse();
assertThat(block1.isBlock()).isTrue();
assertThat(block1.getAttributes()).isNullOrEmpty();
assertThat(block1.getRoles()).isNullOrEmpty();
assertThat(block1.isReftext()).isFalse();
assertThat(block1.getReftext()).isNull();
assertThat(block1.getCaption()).isNull();
assertThat(block1.getTitle()).isNull();
assertThat(block1.getStyle()).isNull();
assertThat(block1.getLevel()).isEqualTo(0);
assertThat(block1.getContentModel()).isEqualTo("simple");
assertThat(block1.getSourceLocation()).isNull();
assertThat(block1.getSubstitutions()).containsExactly("specialcharacters", "quotes", "attributes", "replacements", "macros", "post_replacements");
assertThat(block1.getBlocks()).isNullOrEmpty();
assertThat(block1.getLines()).containsExactly("Some text");
assertThat(block1.getSource()).isEqualTo("Some text");
Title title1 = document1.getStructuredDoctitle();
assertThat(title1.getMain()).isEqualTo("My page");
assertThat(title1.getSubtitle()).isNull();
assertThat(title1.getCombined()).isEqualTo("My page");
assertThat(title1.isSanitized()).isFalse();
assertThat(document1.getDoctitle()).isEqualTo("My page");
assertThat(document1.getOptions()).containsEntry("header_footer", false);
}
// end::assert-code[]
@Override
// tag::mock-code[]
public Document createMock() {
Document mockDocument1 = mock(Document.class);
when(mockDocument1.getId()).thenReturn(null);
when(mockDocument1.getNodeName()).thenReturn("document");
when(mockDocument1.getParent()).thenReturn(null);
when(mockDocument1.getContext()).thenReturn("document");
when(mockDocument1.getDocument()).thenReturn(mockDocument1);
when(mockDocument1.isInline()).thenReturn(false);
when(mockDocument1.isBlock()).thenReturn(true);
Map<String, Object> map1 = new HashMap<>();
map1.put("doctitle", "My page");
map1.put("doctype", "article");
map1.put("example-caption", "Example");
map1.put("figure-caption", "Figure");
map1.put("filetype", "html");
map1.put("notitle", "");
map1.put("prewrap", "");
map1.put("showtitle", true);
map1.put("table-caption", "Table");
when(mockDocument1.getAttributes()).thenReturn(map1);
when(mockDocument1.getRoles()).thenReturn(Collections.emptyList());
when(mockDocument1.isReftext()).thenReturn(false);
when(mockDocument1.getReftext()).thenReturn(null);
when(mockDocument1.getCaption()).thenReturn(null);
when(mockDocument1.getTitle()).thenReturn(null);
when(mockDocument1.getStyle()).thenReturn(null);
when(mockDocument1.getLevel()).thenReturn(0);
when(mockDocument1.getContentModel()).thenReturn("compound");
when(mockDocument1.getSourceLocation()).thenReturn(null);
when(mockDocument1.getSubstitutions()).thenReturn(Collections.emptyList());
Block mockBlock1 = mock(Block.class);
when(mockBlock1.getId()).thenReturn(null);
when(mockBlock1.getNodeName()).thenReturn("paragraph");
when(mockBlock1.getParent()).thenReturn(mockDocument1);
when(mockBlock1.getContext()).thenReturn("paragraph");
when(mockBlock1.getDocument()).thenReturn(mockDocument1);
when(mockBlock1.isInline()).thenReturn(false);
when(mockBlock1.isBlock()).thenReturn(true);
when(mockBlock1.getAttributes()).thenReturn(Collections.emptyMap());
when(mockBlock1.getRoles()).thenReturn(Collections.emptyList());
when(mockBlock1.isReftext()).thenReturn(false);
when(mockBlock1.getReftext()).thenReturn(null);
when(mockBlock1.getCaption()).thenReturn(null);
when(mockBlock1.getTitle()).thenReturn(null);
when(mockBlock1.getStyle()).thenReturn(null);
when(mockBlock1.getLevel()).thenReturn(0);
when(mockBlock1.getContentModel()).thenReturn("simple");
when(mockBlock1.getSourceLocation()).thenReturn(null);
when(mockBlock1.getSubstitutions()).thenReturn(Arrays.asList("specialcharacters", "quotes", "attributes", "replacements", "macros", "post_replacements"));
when(mockBlock1.getBlocks()).thenReturn(Collections.emptyList());
when(mockBlock1.getLines()).thenReturn(Collections.singletonList("Some text"));
when(mockBlock1.getSource()).thenReturn("Some text");
when(mockDocument1.getBlocks()).thenReturn(Collections.singletonList(mockBlock1));
Title mockTitle1 = mock(Title.class);
when(mockTitle1.getMain()).thenReturn("My page");
when(mockTitle1.getSubtitle()).thenReturn(null);
when(mockTitle1.getCombined()).thenReturn("My page");
when(mockTitle1.isSanitized()).thenReturn(false);
when(mockDocument1.getStructuredDoctitle()).thenReturn(mockTitle1);
when(mockDocument1.getDoctitle()).thenReturn("My page");
Map<Object, Object> map2 = new HashMap<>();
map2.put("attributes", "{\"showtitle\"=>true}");
map2.put("header_footer", false);
when(mockDocument1.getOptions()).thenReturn(map2);
return mockDocument1;
}
// end::mock-code[]
}<|fim▁end|> | |
<|file_name|>radio.min.js<|end_file_name|><|fim▁begin|>((bbn)=>{let script=document.createElement('script');script.innerHTML=`<div :class="['bbn-iblock', componentClass]">
<input class="bbn-hidden"
ref="element"
:value="modelValue"
:disabled="disabled"
:required="required"
>
<div :style="getStyle()">
<div v-for="(d, idx) in source"
:class="{
'bbn-iblock': !vertical,
'bbn-right-space': !vertical && !separator && source[idx+1],
'bbn-bottom-sspace': !!vertical && !separator && source[idx+1]
}"
>
<input :value="d[sourceValue]"
:name="name"
class="bbn-radio"
type="radio"
:disabled="disabled || d.disabled"
:required="required"
:id="id + '_' + idx"
@change="changed(d[sourceValue], d, $event)"
:checked="d[sourceValue] === modelValue"
>
<label class="bbn-radio-label bbn-iflex bbn-vmiddle"
:for="id + '_' + idx"
>
<span class="bbn-left-sspace"
v-html="render ? render(d) : d[sourceText]"
></span>
</label>
<br v-if="!vertical && step && ((idx+1) % step === 0)">
<div v-if="(source[idx+1] !== undefined) && !!separator"<|fim▁hole|> :class="{
'bbn-w-100': vertical,
'bbn-iblock': !vertical
}"
v-html="separator"
></div>
</div>
</div>
</div>`;script.setAttribute('id','bbn-tpl-component-radio');script.setAttribute('type','text/x-template');document.body.insertAdjacentElement('beforeend',script);(function(bbn){"use strict";Vue.component('bbn-radio',{mixins:[bbn.vue.basicComponent,bbn.vue.inputComponent,bbn.vue.localStorageComponent,bbn.vue.eventsComponent],props:{separator:{type:String},vertical:{type:Boolean,default:false},step:{type:Number},id:{type:String,default(){return bbn.fn.randomString(10,25);}},render:{type:Function},sourceText:{type:String,default:'text'},sourceValue:{type:String,default:'value'},source:{type:Array,default(){return[{text:bbn._("Yes"),value:1},{text:bbn._("No"),value:0}];}},modelValue:{type:[String,Boolean,Number],default:undefined}},model:{prop:'modelValue',event:'input'},methods:{changed(val,d,e){this.$emit('input',val);this.$emit('change',val,d,e);},getStyle(){if(this.step&&!this.vertical){return'display: grid; grid-template-columns: '+'auto '.repeat(this.step)+';';}
else{return'';}}},beforeMount(){if(this.hasStorage){let v=this.getStorage();if(v&&(v!==this.modelValue)){this.changed(v);}}},watch:{modelValue(v){if(this.storage){if(v){this.setStorage(v);}
else{this.unsetStorage()}}},}});})(bbn);})(bbn);<|fim▁end|> | |
<|file_name|>test_div_bool.py<|end_file_name|><|fim▁begin|>import numpy as np
from parakeet import jit, testing_helpers
@jit
def true_divided(x):
return True / x
def test_true_divided_bool():
testing_helpers.expect(true_divided, [True], True)<|fim▁hole|> testing_helpers.expect(true_divided, [2], 0)
def test_true_divided_float():
testing_helpers.expect(true_divided, [1.0], 1.0)
testing_helpers.expect(true_divided, [2.0], 0.5)
def test_true_divided_uint8():
testing_helpers.expect(true_divided, [np.uint8(1)], 1)
testing_helpers.expect(true_divided, [np.uint8(2)], 0)
if __name__ == '__main__':
testing_helpers.run_local_tests()<|fim▁end|> |
def test_true_divided_int():
testing_helpers.expect(true_divided, [1], 1) |
<|file_name|>pip.rs<|end_file_name|><|fim▁begin|>use std::old_io::BufferedReader;
use std::old_io::EndOfFile;
use std::old_io::fs::File;
use super::super::context::{BuildContext};
use super::super::packages;
use super::generic::{run_command_at_env, capture_command};
pub fn scan_features(ver: u8, pkgs: &Vec<String>) -> Vec<packages::Package> {
let mut res = vec!();
res.push(packages::BuildEssential);
if ver == 2 {
res.push(packages::Python2);
res.push(packages::Python2Dev);
res.push(packages::PipPy2);
} else {
res.push(packages::Python3);
res.push(packages::Python3Dev);
res.push(packages::PipPy3);
}
for name in pkgs.iter() {
if name.as_slice().starts_with("git+") {
res.push(packages::Git);
} else if name.as_slice().starts_with("hg+") {
res.push(packages::Mercurial);
}
}
return res;
}
fn pip_args(ctx: &mut BuildContext, ver: u8) -> Vec<String> {
let mut args = vec!(
(if ver == 2 { "python2" } else { "python3" }).to_string(),<|fim▁hole|> "--ignore-installed".to_string(),
);
if ctx.pip_settings.index_urls.len() > 0 {
let mut indexes = ctx.pip_settings.index_urls.iter();
if let Some(ref lnk) = indexes.next() {
args.push(format!("--index-url={}", lnk));
for lnk in indexes {
args.push(format!("--extra-index-url={}", lnk));
}
}
}
ctx.pip_settings.trusted_hosts.iter().map(|h| {
args.push("--trusted-host".to_string());
args.push(h.to_string());
}).last();
if !ctx.pip_settings.dependencies {
args.push("--no-deps".to_string());
}
for lnk in ctx.pip_settings.find_links.iter() {
args.push(format!("--find-links={}", lnk));
}
return args;
}
pub fn pip_install(ctx: &mut BuildContext, ver: u8, pkgs: &Vec<String>)
-> Result<(), String>
{
try!(packages::ensure_packages(ctx, &scan_features(ver, pkgs)[0..]));
let mut pip_cli = pip_args(ctx, ver);
pip_cli.extend(pkgs.clone().into_iter());
run_command_at_env(ctx, pip_cli.as_slice(), &Path::new("/work"), &[
("PYTHONPATH", "/tmp/non-existent:/tmp/pip-install")])
}
pub fn pip_requirements(ctx: &mut BuildContext, ver: u8, reqtxt: &Path)
-> Result<(), String>
{
let f = try!(File::open(&Path::new("/work").join(reqtxt))
.map_err(|e| format!("Can't open requirements file: {}", e)));
let mut f = BufferedReader::new(f);
let mut names = vec!();
loop {
let line = match f.read_line() {
Ok(line) => line,
Err(ref e) if e.kind == EndOfFile => {
break;
}
Err(e) => {
return Err(format!("Error reading requirements: {}", e));
}
};
let chunk = line.as_slice().trim();
// Ignore empty lines and comments
if chunk.len() == 0 || chunk.starts_with("#") {
continue;
}
names.push(chunk.to_string());
}
try!(packages::ensure_packages(ctx, &scan_features(ver, &names)[0..]));
let mut pip_cli = pip_args(ctx, ver);
pip_cli.push("--requirement".to_string());
pip_cli.push(reqtxt.display().to_string()); // TODO(tailhook) fix conversion
run_command_at_env(ctx, pip_cli.as_slice(), &Path::new("/work"), &[
("PYTHONPATH", "/tmp/non-existent:/tmp/pip-install")])
}
pub fn configure(ctx: &mut BuildContext) -> Result<(), String> {
try!(ctx.add_cache_dir(Path::new("/tmp/pip-cache"),
"pip-cache".to_string()));
ctx.environ.insert("PIP_CACHE_DIR".to_string(),
"/tmp/pip-cache".to_string());
Ok(())
}
pub fn freeze(ctx: &mut BuildContext) -> Result<(), String> {
use std::fs::File; // TODO(tailhook) migrate whole module
use std::io::Write; // TODO(tailhook) migrate whole module
if ctx.featured_packages.contains(&packages::PipPy2) {
try!(capture_command(ctx, &[
"python2".to_string(),
"-m".to_string(),
"pip".to_string(),
"freeze".to_string(),
], &[("PYTHONPATH", "/tmp/non-existent:/tmp/pip-install")])
.and_then(|out| {
File::create("/vagga/container/pip2-freeze.txt")
.and_then(|mut f| f.write_all(&out))
.map_err(|e| format!("Error dumping package list: {}", e))
}));
}
if ctx.featured_packages.contains(&packages::PipPy3) {
try!(capture_command(ctx, &[
"python3".to_string(),
"-m".to_string(),
"pip".to_string(),
"freeze".to_string(),
], &[("PYTHONPATH", "/tmp/non-existent:/tmp/pip-install")])
.and_then(|out| {
File::create("/vagga/container/pip3-freeze.txt")
.and_then(|mut f| f.write_all(&out))
.map_err(|e| format!("Error dumping package list: {}", e))
}));
}
Ok(())
}<|fim▁end|> | "-m".to_string(), "pip".to_string(),
"install".to_string(), |
<|file_name|>HomeGraphService.java<|end_file_name|><|fim▁begin|>/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.homegraph.v1;
/**
* Service definition for HomeGraphService (v1).
*
* <p>
*
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://developers.google.com/actions/smarthome/create-app#request-sync" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link HomeGraphServiceRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class HomeGraphService extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
// Note: Leave this static initializer at the top of the file.
static {
com.google.api.client.util.Preconditions.checkState(
com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15,
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.15 of google-api-client to run version " +
"1.30.10 of the HomeGraph API library.", com.google.api.client.googleapis.GoogleUtils.VERSION);
}
/**
* The default encoded root URL of the service. This is determined when the library is generated
* and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_ROOT_URL = "https://homegraph.googleapis.com/";
/**
* The default encoded service path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_SERVICE_PATH = "";
/**
* The default encoded batch path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.23
*/
public static final String DEFAULT_BATCH_PATH = "batch";
/**
* The default encoded base URL of the service. This is determined when the library is generated
* and normally should not be changed.
*/
public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH;
/**
* Constructor.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public HomeGraphService(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
this(new Builder(transport, jsonFactory, httpRequestInitializer));
}
/**
* @param builder builder
*/
HomeGraphService(Builder builder) {
super(builder);
}
@Override
protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException {
super.initialize(httpClientRequest);
}
/**
* An accessor for creating requests from the AgentUsers collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code HomeGraphService homegraph = new HomeGraphService(...);}
* {@code HomeGraphService.AgentUsers.List request = homegraph.agentUsers().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public AgentUsers agentUsers() {
return new AgentUsers();
}
/**
* The "agentUsers" collection of methods.
*/
public class AgentUsers {
/**
* Unlinks the given third-party user from your smart home Action. All data related to this user
* will be deleted. For more details on how users link their accounts, see [fulfillment and
* authentication](https://developers.google.com/assistant/smarthome/concepts/fulfillment-
* authentication). The third-party user's identity is passed in via the `agent_user_id` (see
* DeleteAgentUserRequest). This request must be authorized using service account credentials from
* your Actions console project.
*
* Create a request for the method "agentUsers.delete".
*
* This request holds the parameters needed by the homegraph server. After setting any optional
* parameters, call the {@link Delete#execute()} method to invoke the remote operation.
*
* @param agentUserId Required. Third-party user ID.
* @return the request
*/
public Delete delete(java.lang.String agentUserId) throws java.io.IOException {
Delete result = new Delete(agentUserId);
initialize(result);
return result;
}
public class Delete extends HomeGraphServiceRequest<com.google.api.services.homegraph.v1.model.Empty> {
private static final String REST_PATH = "v1/{+agentUserId}";
private final java.util.regex.Pattern AGENT_USER_ID_PATTERN =
java.util.regex.Pattern.compile("^agentUsers/.*$");
/**
* Unlinks the given third-party user from your smart home Action. All data related to this user
* will be deleted. For more details on how users link their accounts, see [fulfillment and
* authentication](https://developers.google.com/assistant/smarthome/concepts/fulfillment-
* authentication). The third-party user's identity is passed in via the `agent_user_id` (see
* DeleteAgentUserRequest). This request must be authorized using service account credentials from
* your Actions console project.
*
* Create a request for the method "agentUsers.delete".
*
* This request holds the parameters needed by the the homegraph server. After setting any
* optional parameters, call the {@link Delete#execute()} method to invoke the remote operation.
* <p> {@link
* Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param agentUserId Required. Third-party user ID.
* @since 1.13
*/
protected Delete(java.lang.String agentUserId) {
super(HomeGraphService.this, "DELETE", REST_PATH, null, com.google.api.services.homegraph.v1.model.Empty.class);
this.agentUserId = com.google.api.client.util.Preconditions.checkNotNull(agentUserId, "Required parameter agentUserId must be specified.");
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(AGENT_USER_ID_PATTERN.matcher(agentUserId).matches(),
"Parameter agentUserId must conform to the pattern " +
"^agentUsers/.*$");
}
}
@Override
public Delete set$Xgafv(java.lang.String $Xgafv) {
return (Delete) super.set$Xgafv($Xgafv);
}
@Override
public Delete setAccessToken(java.lang.String accessToken) {
return (Delete) super.setAccessToken(accessToken);
}
@Override
public Delete setAlt(java.lang.String alt) {
return (Delete) super.setAlt(alt);
}
@Override
public Delete setCallback(java.lang.String callback) {
return (Delete) super.setCallback(callback);
}
@Override
public Delete setFields(java.lang.String fields) {
return (Delete) super.setFields(fields);
}
@Override
public Delete setKey(java.lang.String key) {
return (Delete) super.setKey(key);
}
@Override
public Delete setOauthToken(java.lang.String oauthToken) {
return (Delete) super.setOauthToken(oauthToken);
}
@Override
public Delete setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Delete) super.setPrettyPrint(prettyPrint);
}
@Override
public Delete setQuotaUser(java.lang.String quotaUser) {
return (Delete) super.setQuotaUser(quotaUser);
}
@Override
public Delete setUploadType(java.lang.String uploadType) {
return (Delete) super.setUploadType(uploadType);
}
@Override
public Delete setUploadProtocol(java.lang.String uploadProtocol) {
return (Delete) super.setUploadProtocol(uploadProtocol);
}
/** Required. Third-party user ID. */
@com.google.api.client.util.Key
private java.lang.String agentUserId;
/** Required. Third-party user ID.
*/
public java.lang.String getAgentUserId() {
return agentUserId;
}
/** Required. Third-party user ID. */
public Delete setAgentUserId(java.lang.String agentUserId) {
if (!getSuppressPatternChecks()) {
com.google.api.client.util.Preconditions.checkArgument(AGENT_USER_ID_PATTERN.matcher(agentUserId).matches(),
"Parameter agentUserId must conform to the pattern " +
"^agentUsers/.*$");
}
this.agentUserId = agentUserId;
return this;
}
/** Request ID used for debugging. */
@com.google.api.client.util.Key
private java.lang.String requestId;
/** Request ID used for debugging.
*/
public java.lang.String getRequestId() {
return requestId;
}
/** Request ID used for debugging. */
public Delete setRequestId(java.lang.String requestId) {
this.requestId = requestId;
return this;
}
@Override
public Delete set(String parameterName, Object value) {
return (Delete) super.set(parameterName, value);
}
}
}
/**
* An accessor for creating requests from the Devices collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code HomeGraphService homegraph = new HomeGraphService(...);}
* {@code HomeGraphService.Devices.List request = homegraph.devices().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Devices devices() {
return new Devices();
}
/**
* The "devices" collection of methods.
*/
public class Devices {
/**
* Gets the current states in Home Graph for the given set of the third-party user's devices. The
* third-party user's identity is passed in via the `agent_user_id` (see QueryRequest). This request
* must be authorized using service account credentials from your Actions console project.
*
* Create a request for the method "devices.query".
*
* This request holds the parameters needed by the homegraph server. After setting any optional
* parameters, call the {@link Query#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.homegraph.v1.model.QueryRequest}
* @return the request
*/
public Query query(com.google.api.services.homegraph.v1.model.QueryRequest content) throws java.io.IOException {
Query result = new Query(content);
initialize(result);
return result;
}
public class Query extends HomeGraphServiceRequest<com.google.api.services.homegraph.v1.model.QueryResponse> {
private static final String REST_PATH = "v1/devices:query";
/**
* Gets the current states in Home Graph for the given set of the third-party user's devices. The
* third-party user's identity is passed in via the `agent_user_id` (see QueryRequest). This
* request must be authorized using service account credentials from your Actions console project.
*
* Create a request for the method "devices.query".
*
* This request holds the parameters needed by the the homegraph server. After setting any
* optional parameters, call the {@link Query#execute()} method to invoke the remote operation.
* <p> {@link
* Query#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.homegraph.v1.model.QueryRequest}
* @since 1.13
*/
protected Query(com.google.api.services.homegraph.v1.model.QueryRequest content) {
super(HomeGraphService.this, "POST", REST_PATH, content, com.google.api.services.homegraph.v1.model.QueryResponse.class);
}
@Override
public Query set$Xgafv(java.lang.String $Xgafv) {
return (Query) super.set$Xgafv($Xgafv);
}
@Override
public Query setAccessToken(java.lang.String accessToken) {
return (Query) super.setAccessToken(accessToken);
}
@Override
public Query setAlt(java.lang.String alt) {
return (Query) super.setAlt(alt);
}
@Override
public Query setCallback(java.lang.String callback) {
return (Query) super.setCallback(callback);
}
@Override
public Query setFields(java.lang.String fields) {
return (Query) super.setFields(fields);
}
@Override
public Query setKey(java.lang.String key) {
return (Query) super.setKey(key);
}
@Override
public Query setOauthToken(java.lang.String oauthToken) {
return (Query) super.setOauthToken(oauthToken);
}
@Override
public Query setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Query) super.setPrettyPrint(prettyPrint);
}
@Override
public Query setQuotaUser(java.lang.String quotaUser) {
return (Query) super.setQuotaUser(quotaUser);
}
@Override
public Query setUploadType(java.lang.String uploadType) {
return (Query) super.setUploadType(uploadType);
}
@Override
public Query setUploadProtocol(java.lang.String uploadProtocol) {
return (Query) super.setUploadProtocol(uploadProtocol);
}
@Override
public Query set(String parameterName, Object value) {
return (Query) super.set(parameterName, value);
}
}
/**
* Reports device state and optionally sends device notifications. Called by your smart home Action
* when the state of a third-party device changes or you need to send a notification about the
* device. See [Implement Report State](https://developers.google.com/assistant/smarthome/develop
* /report-state) for more information. This method updates the device state according to its
* declared [traits](https://developers.google.com/assistant/smarthome/concepts/devices-traits).
* Publishing a new state value outside of these traits will result in an `INVALID_ARGUMENT` error
* response. The third-party user's identity is passed in via the `agent_user_id` (see
* ReportStateAndNotificationRequest). This request must be authorized using service account
* credentials from your Actions console project.
*
* Create a request for the method "devices.reportStateAndNotification".
*
* This request holds the parameters needed by the homegraph server. After setting any optional
* parameters, call the {@link ReportStateAndNotification#execute()} method to invoke the remote
* operation.
*
* @param content the {@link com.google.api.services.homegraph.v1.model.ReportStateAndNotificationRequest}
* @return the request
*/
public ReportStateAndNotification reportStateAndNotification(com.google.api.services.homegraph.v1.model.ReportStateAndNotificationRequest content) throws java.io.IOException {
ReportStateAndNotification result = new ReportStateAndNotification(content);
initialize(result);
return result;
}
public class ReportStateAndNotification extends HomeGraphServiceRequest<com.google.api.services.homegraph.v1.model.ReportStateAndNotificationResponse> {
private static final String REST_PATH = "v1/devices:reportStateAndNotification";
/**
* Reports device state and optionally sends device notifications. Called by your smart home
* Action when the state of a third-party device changes or you need to send a notification about
* the device. See [Implement Report
* State](https://developers.google.com/assistant/smarthome/develop/report-state) for more
* information. This method updates the device state according to its declared
* [traits](https://developers.google.com/assistant/smarthome/concepts/devices-traits). Publishing
* a new state value outside of these traits will result in an `INVALID_ARGUMENT` error response.
* The third-party user's identity is passed in via the `agent_user_id` (see
* ReportStateAndNotificationRequest). This request must be authorized using service account
* credentials from your Actions console project.
*
* Create a request for the method "devices.reportStateAndNotification".
*
* This request holds the parameters needed by the the homegraph server. After setting any
* optional parameters, call the {@link ReportStateAndNotification#execute()} method to invoke the
* remote operation. <p> {@link ReportStateAndNotification#initialize(com.google.api.client.google
* apis.services.AbstractGoogleClientRequest)} must be called to initialize this instance
* immediately after invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.homegraph.v1.model.ReportStateAndNotificationRequest}
* @since 1.13
*/
protected ReportStateAndNotification(com.google.api.services.homegraph.v1.model.ReportStateAndNotificationRequest content) {
super(HomeGraphService.this, "POST", REST_PATH, content, com.google.api.services.homegraph.v1.model.ReportStateAndNotificationResponse.class);
}
@Override
public ReportStateAndNotification set$Xgafv(java.lang.String $Xgafv) {
return (ReportStateAndNotification) super.set$Xgafv($Xgafv);
}
@Override
public ReportStateAndNotification setAccessToken(java.lang.String accessToken) {
return (ReportStateAndNotification) super.setAccessToken(accessToken);
}
@Override
public ReportStateAndNotification setAlt(java.lang.String alt) {
return (ReportStateAndNotification) super.setAlt(alt);
}
@Override
public ReportStateAndNotification setCallback(java.lang.String callback) {
return (ReportStateAndNotification) super.setCallback(callback);
}
@Override
public ReportStateAndNotification setFields(java.lang.String fields) {
return (ReportStateAndNotification) super.setFields(fields);
}
@Override
public ReportStateAndNotification setKey(java.lang.String key) {
return (ReportStateAndNotification) super.setKey(key);
}
@Override
public ReportStateAndNotification setOauthToken(java.lang.String oauthToken) {
return (ReportStateAndNotification) super.setOauthToken(oauthToken);
}
@Override
public ReportStateAndNotification setPrettyPrint(java.lang.Boolean prettyPrint) {
return (ReportStateAndNotification) super.setPrettyPrint(prettyPrint);
}
@Override
public ReportStateAndNotification setQuotaUser(java.lang.String quotaUser) {
return (ReportStateAndNotification) super.setQuotaUser(quotaUser);
}
@Override
public ReportStateAndNotification setUploadType(java.lang.String uploadType) {
return (ReportStateAndNotification) super.setUploadType(uploadType);
}
@Override
public ReportStateAndNotification setUploadProtocol(java.lang.String uploadProtocol) {
return (ReportStateAndNotification) super.setUploadProtocol(uploadProtocol);
}
@Override
public ReportStateAndNotification set(String parameterName, Object value) {
return (ReportStateAndNotification) super.set(parameterName, value);
}
}
/**
* Requests Google to send an `action.devices.SYNC`
* [intent](https://developers.google.com/assistant/smarthome/reference/intent/sync) to your smart
* home Action to update device metadata for the given user. The third-party user's identity is
* passed via the `agent_user_id` (see RequestSyncDevicesRequest). This request must be authorized
* using service account credentials from your Actions console project.
*
* Create a request for the method "devices.requestSync".
*
* This request holds the parameters needed by the homegraph server. After setting any optional
* parameters, call the {@link RequestSync#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.homegraph.v1.model.RequestSyncDevicesRequest}
* @return the request
*/
public RequestSync requestSync(com.google.api.services.homegraph.v1.model.RequestSyncDevicesRequest content) throws java.io.IOException {
RequestSync result = new RequestSync(content);
initialize(result);
return result;
}
public class RequestSync extends HomeGraphServiceRequest<com.google.api.services.homegraph.v1.model.RequestSyncDevicesResponse> {
private static final String REST_PATH = "v1/devices:requestSync";
/**
* Requests Google to send an `action.devices.SYNC`
* [intent](https://developers.google.com/assistant/smarthome/reference/intent/sync) to your smart
* home Action to update device metadata for the given user. The third-party user's identity is
* passed via the `agent_user_id` (see RequestSyncDevicesRequest). This request must be authorized
* using service account credentials from your Actions console project.
*
* Create a request for the method "devices.requestSync".
*
* This request holds the parameters needed by the the homegraph server. After setting any
* optional parameters, call the {@link RequestSync#execute()} method to invoke the remote
* operation. <p> {@link
* RequestSync#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.homegraph.v1.model.RequestSyncDevicesRequest}
* @since 1.13
*/
protected RequestSync(com.google.api.services.homegraph.v1.model.RequestSyncDevicesRequest content) {
super(HomeGraphService.this, "POST", REST_PATH, content, com.google.api.services.homegraph.v1.model.RequestSyncDevicesResponse.class);
}
@Override
public RequestSync set$Xgafv(java.lang.String $Xgafv) {
return (RequestSync) super.set$Xgafv($Xgafv);
}
@Override
public RequestSync setAccessToken(java.lang.String accessToken) {
return (RequestSync) super.setAccessToken(accessToken);
}
@Override
public RequestSync setAlt(java.lang.String alt) {
return (RequestSync) super.setAlt(alt);
}
@Override
public RequestSync setCallback(java.lang.String callback) {
return (RequestSync) super.setCallback(callback);
}
@Override
public RequestSync setFields(java.lang.String fields) {
return (RequestSync) super.setFields(fields);
}
@Override
public RequestSync setKey(java.lang.String key) {
return (RequestSync) super.setKey(key);
}
@Override
public RequestSync setOauthToken(java.lang.String oauthToken) {
return (RequestSync) super.setOauthToken(oauthToken);
}
@Override
public RequestSync setPrettyPrint(java.lang.Boolean prettyPrint) {
return (RequestSync) super.setPrettyPrint(prettyPrint);
}
@Override
public RequestSync setQuotaUser(java.lang.String quotaUser) {
return (RequestSync) super.setQuotaUser(quotaUser);
}
@Override
public RequestSync setUploadType(java.lang.String uploadType) {
return (RequestSync) super.setUploadType(uploadType);
}
@Override
public RequestSync setUploadProtocol(java.lang.String uploadProtocol) {
return (RequestSync) super.setUploadProtocol(uploadProtocol);
}
@Override
public RequestSync set(String parameterName, Object value) {
return (RequestSync) super.set(parameterName, value);
}
}
/**
* Gets all the devices associated with the given third-party user. The third-party user's identity
* is passed in via the `agent_user_id` (see SyncRequest). This request must be authorized using
* service account credentials from your Actions console project.
*
* Create a request for the method "devices.sync".
*
* This request holds the parameters needed by the homegraph server. After setting any optional
* parameters, call the {@link Sync#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.homegraph.v1.model.SyncRequest}
* @return the request
*/
public Sync sync(com.google.api.services.homegraph.v1.model.SyncRequest content) throws java.io.IOException {
Sync result = new Sync(content);
initialize(result);
return result;
}
public class Sync extends HomeGraphServiceRequest<com.google.api.services.homegraph.v1.model.SyncResponse> {
private static final String REST_PATH = "v1/devices:sync";
/**
* Gets all the devices associated with the given third-party user. The third-party user's
* identity is passed in via the `agent_user_id` (see SyncRequest). This request must be
* authorized using service account credentials from your Actions console project.
*
* Create a request for the method "devices.sync".<|fim▁hole|> * This request holds the parameters needed by the the homegraph server. After setting any
* optional parameters, call the {@link Sync#execute()} method to invoke the remote operation. <p>
* {@link Sync#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.homegraph.v1.model.SyncRequest}
* @since 1.13
*/
protected Sync(com.google.api.services.homegraph.v1.model.SyncRequest content) {
super(HomeGraphService.this, "POST", REST_PATH, content, com.google.api.services.homegraph.v1.model.SyncResponse.class);
}
@Override
public Sync set$Xgafv(java.lang.String $Xgafv) {
return (Sync) super.set$Xgafv($Xgafv);
}
@Override
public Sync setAccessToken(java.lang.String accessToken) {
return (Sync) super.setAccessToken(accessToken);
}
@Override
public Sync setAlt(java.lang.String alt) {
return (Sync) super.setAlt(alt);
}
@Override
public Sync setCallback(java.lang.String callback) {
return (Sync) super.setCallback(callback);
}
@Override
public Sync setFields(java.lang.String fields) {
return (Sync) super.setFields(fields);
}
@Override
public Sync setKey(java.lang.String key) {
return (Sync) super.setKey(key);
}
@Override
public Sync setOauthToken(java.lang.String oauthToken) {
return (Sync) super.setOauthToken(oauthToken);
}
@Override
public Sync setPrettyPrint(java.lang.Boolean prettyPrint) {
return (Sync) super.setPrettyPrint(prettyPrint);
}
@Override
public Sync setQuotaUser(java.lang.String quotaUser) {
return (Sync) super.setQuotaUser(quotaUser);
}
@Override
public Sync setUploadType(java.lang.String uploadType) {
return (Sync) super.setUploadType(uploadType);
}
@Override
public Sync setUploadProtocol(java.lang.String uploadProtocol) {
return (Sync) super.setUploadProtocol(uploadProtocol);
}
@Override
public Sync set(String parameterName, Object value) {
return (Sync) super.set(parameterName, value);
}
}
}
/**
* Builder for {@link HomeGraphService}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
DEFAULT_ROOT_URL,
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link HomeGraphService}. */
@Override
public HomeGraphService build() {
return new HomeGraphService(this);
}
@Override
public Builder setRootUrl(String rootUrl) {
return (Builder) super.setRootUrl(rootUrl);
}
@Override
public Builder setServicePath(String servicePath) {
return (Builder) super.setServicePath(servicePath);
}
@Override
public Builder setBatchPath(String batchPath) {
return (Builder) super.setBatchPath(batchPath);
}
@Override
public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
return (Builder) super.setHttpRequestInitializer(httpRequestInitializer);
}
@Override
public Builder setApplicationName(String applicationName) {
return (Builder) super.setApplicationName(applicationName);
}
@Override
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
return (Builder) super.setSuppressPatternChecks(suppressPatternChecks);
}
@Override
public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) {
return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks);
}
@Override
public Builder setSuppressAllChecks(boolean suppressAllChecks) {
return (Builder) super.setSuppressAllChecks(suppressAllChecks);
}
/**
* Set the {@link HomeGraphServiceRequestInitializer}.
*
* @since 1.12
*/
public Builder setHomeGraphServiceRequestInitializer(
HomeGraphServiceRequestInitializer homegraphserviceRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(homegraphserviceRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}<|fim▁end|> | * |
<|file_name|>StreamService.py<|end_file_name|><|fim▁begin|>from Source import Source
from Components.Element import cached
from Components.SystemInfo import SystemInfo
from enigma import eServiceReference
StreamServiceList = []
class StreamService(Source):
def __init__(self, navcore):
Source.__init__(self)
self.ref = None
self.__service = None
self.navcore = navcore
def serviceEvent(self, event):
pass
@cached
def getService(self):
return self.__service
service = property(getService)
def handleCommand(self, cmd):
print "[StreamService] handle command", cmd
self.ref = eServiceReference(cmd)
def recordEvent(self, service, event):
if service is self.__service:
return
print "[StreamService] RECORD event for us:", service
self.changed((self.CHANGED_ALL, ))<|fim▁hole|>
def execBegin(self):
if self.ref is None:
print "[StreamService] has no service ref set"
return
print "[StreamService]e execBegin", self.ref.toString()
if SystemInfo["CanNotDoSimultaneousTranscodeAndPIP"]:
from Screens.InfoBar import InfoBar
if InfoBar.instance and hasattr(InfoBar.instance.session, 'pipshown') and InfoBar.instance.session.pipshown:
hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP()
print "[StreamService] try to disable pip before start stream"
if hasattr(InfoBar.instance.session, 'pip'):
del InfoBar.instance.session.pip
InfoBar.instance.session.pipshown = False
self.__service = self.navcore.recordService(self.ref)
self.navcore.record_event.append(self.recordEvent)
if self.__service is not None:
if self.__service.__deref__() not in StreamServiceList:
StreamServiceList.append(self.__service.__deref__())
self.__service.prepareStreaming()
self.__service.start()
def execEnd(self):
print "[StreamService] execEnd", self.ref.toString()
self.navcore.record_event.remove(self.recordEvent)
if self.__service is not None:
if self.__service.__deref__() in StreamServiceList:
StreamServiceList.remove(self.__service.__deref__())
self.navcore.stopRecordService(self.__service)
self.__service = None
self.ref = None<|fim▁end|> | |
<|file_name|>parser.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/. */
//! The context within which CSS code is parsed.
use context::QuirksMode;
use cssparser::{Parser, SourceLocation, UnicodeRange};
use error_reporting::{ParseErrorReporter, ContextualParseError};
use style_traits::{OneOrMoreSeparated, ParseError, ParsingMode, Separator};
#[cfg(feature = "gecko")]
use style_traits::{PARSING_MODE_DEFAULT, PARSING_MODE_ALLOW_UNITLESS_LENGTH, PARSING_MODE_ALLOW_ALL_NUMERIC_VALUES};
use stylesheets::{CssRuleType, Origin, UrlExtraData, Namespaces};
/// Asserts that all ParsingMode flags have a matching ParsingMode value in gecko.
#[cfg(feature = "gecko")]
#[inline]
pub fn assert_parsing_mode_match() {
use gecko_bindings::structs;
macro_rules! check_parsing_modes {
( $( $a:ident => $b:ident ),*, ) => {
if cfg!(debug_assertions) {
let mut modes = ParsingMode::all();
$(
assert_eq!(structs::$a as usize, $b.bits() as usize, stringify!($b));<|fim▁hole|> )*
assert_eq!(modes, ParsingMode::empty(), "all ParsingMode bits should have an assertion");
}
}
}
check_parsing_modes! {
ParsingMode_Default => PARSING_MODE_DEFAULT,
ParsingMode_AllowUnitlessLength => PARSING_MODE_ALLOW_UNITLESS_LENGTH,
ParsingMode_AllowAllNumericValues => PARSING_MODE_ALLOW_ALL_NUMERIC_VALUES,
}
}
/// The data that the parser needs from outside in order to parse a stylesheet.
pub struct ParserContext<'a> {
/// The `Origin` of the stylesheet, whether it's a user, author or
/// user-agent stylesheet.
pub stylesheet_origin: Origin,
/// The extra data we need for resolving url values.
pub url_data: &'a UrlExtraData,
/// An error reporter to report syntax errors.
pub error_reporter: &'a ParseErrorReporter,
/// The current rule type, if any.
pub rule_type: Option<CssRuleType>,
/// Line number offsets for inline stylesheets
pub line_number_offset: u64,
/// The mode to use when parsing.
pub parsing_mode: ParsingMode,
/// The quirks mode of this stylesheet.
pub quirks_mode: QuirksMode,
/// The currently active namespaces.
pub namespaces: Option<&'a Namespaces>,
}
impl<'a> ParserContext<'a> {
/// Create a parser context.
pub fn new(stylesheet_origin: Origin,
url_data: &'a UrlExtraData,
error_reporter: &'a ParseErrorReporter,
rule_type: Option<CssRuleType>,
parsing_mode: ParsingMode,
quirks_mode: QuirksMode)
-> ParserContext<'a> {
ParserContext {
stylesheet_origin: stylesheet_origin,
url_data: url_data,
error_reporter: error_reporter,
rule_type: rule_type,
line_number_offset: 0u64,
parsing_mode: parsing_mode,
quirks_mode: quirks_mode,
namespaces: None,
}
}
/// Create a parser context for on-the-fly parsing in CSSOM
pub fn new_for_cssom(
url_data: &'a UrlExtraData,
error_reporter: &'a ParseErrorReporter,
rule_type: Option<CssRuleType>,
parsing_mode: ParsingMode,
quirks_mode: QuirksMode
) -> ParserContext<'a> {
Self::new(Origin::Author, url_data, error_reporter, rule_type, parsing_mode, quirks_mode)
}
/// Create a parser context based on a previous context, but with a modified rule type.
pub fn new_with_rule_type(
context: &'a ParserContext,
rule_type: Option<CssRuleType>
) -> ParserContext<'a> {
ParserContext {
stylesheet_origin: context.stylesheet_origin,
url_data: context.url_data,
error_reporter: context.error_reporter,
rule_type: rule_type,
line_number_offset: context.line_number_offset,
parsing_mode: context.parsing_mode,
quirks_mode: context.quirks_mode,
namespaces: context.namespaces,
}
}
/// Create a parser context for inline CSS which accepts additional line offset argument.
pub fn new_with_line_number_offset(
stylesheet_origin: Origin,
url_data: &'a UrlExtraData,
error_reporter: &'a ParseErrorReporter,
line_number_offset: u64,
parsing_mode: ParsingMode,
quirks_mode: QuirksMode
) -> ParserContext<'a> {
ParserContext {
stylesheet_origin: stylesheet_origin,
url_data: url_data,
error_reporter: error_reporter,
rule_type: None,
line_number_offset: line_number_offset,
parsing_mode: parsing_mode,
quirks_mode: quirks_mode,
namespaces: None,
}
}
/// Get the rule type, which assumes that one is available.
pub fn rule_type(&self) -> CssRuleType {
self.rule_type.expect("Rule type expected, but none was found.")
}
/// Record a CSS parse error with this context’s error reporting.
pub fn log_css_error(&self, location: SourceLocation, error: ContextualParseError) {
let location = SourceLocation {
line: location.line + self.line_number_offset as u32,
column: location.column,
};
self.error_reporter.report_error(self.url_data, location, error)
}
}
// XXXManishearth Replace all specified value parse impls with impls of this
// trait. This will make it easy to write more generic values in the future.
/// A trait to abstract parsing of a specified value given a `ParserContext` and
/// CSS input.
pub trait Parse : Sized {
/// Parse a value of this type.
///
/// Returns an error on failure.
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>>;
}
impl<T> Parse for Vec<T>
where
T: Parse + OneOrMoreSeparated,
<T as OneOrMoreSeparated>::S: Separator,
{
fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
<T as OneOrMoreSeparated>::S::parse(input, |i| T::parse(context, i))
}
}
impl Parse for UnicodeRange {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
UnicodeRange::parse(input).map_err(|e| e.into())
}
}<|fim▁end|> | modes.remove($b); |
<|file_name|>scala.js<|end_file_name|><|fim▁begin|>"use strict";
define("ace/snippets/scala", ["require", "exports", "module"], function (require, exports, module) {
"use strict";
<|fim▁hole|> exports.snippetText = undefined;
exports.scope = "scala";
});<|fim▁end|> | |
<|file_name|>res_users.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
import requests
from odoo.addons.microsoft_calendar.models.microsoft_sync import microsoft_calendar_token
from datetime import timedelta
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.loglevels import exception_to_unicode
from odoo.addons.microsoft_account.models.microsoft_service import MICROSOFT_TOKEN_ENDPOINT
from odoo.addons.microsoft_calendar.utils.microsoft_calendar import MicrosoftCalendarService, InvalidSyncToken
_logger = logging.getLogger(__name__)
class User(models.Model):
_inherit = 'res.users'
microsoft_calendar_sync_token = fields.Char('Microsoft Next Sync Token', copy=False)
def _microsoft_calendar_authenticated(self):
return bool(self.sudo().microsoft_calendar_rtoken)
def _get_microsoft_calendar_token(self):
self.ensure_one()
if self._is_microsoft_calendar_valid():
self._refresh_microsoft_calendar_token()
return self.microsoft_calendar_token
def _is_microsoft_calendar_valid(self):
return self.microsoft_calendar_token_validity and self.microsoft_calendar_token_validity < (fields.Datetime.now() + timedelta(minutes=1))
def _refresh_microsoft_calendar_token(self):
self.ensure_one()
get_param = self.env['ir.config_parameter'].sudo().get_param
client_id = get_param('microsoft_calendar_client_id')
client_secret = get_param('microsoft_calendar_client_secret')
if not client_id or not client_secret:
raise UserError(_("The account for the Outlook Calendar service is not configured."))
headers = {"content-type": "application/x-www-form-urlencoded"}
data = {
'refresh_token': self.microsoft_calendar_rtoken,
'client_id': client_id,
'client_secret': client_secret,
'grant_type': 'refresh_token',
}
try:
dummy, response, dummy = self.env['microsoft.service']._do_request(MICROSOFT_TOKEN_ENDPOINT, params=data, headers=headers, method='POST', preuri='')
ttl = response.get('expires_in')
self.write({
'microsoft_calendar_token': response.get('access_token'),
'microsoft_calendar_token_validity': fields.Datetime.now() + timedelta(seconds=ttl),
})
except requests.HTTPError as error:
if error.response.status_code == 400: # invalid grant
# Delete refresh token and make sure it's commited
with self.pool.cursor() as cr:
self.env.user.with_env(self.env(cr=cr)).write({'microsoft_calendar_rtoken': False})
error_key = error.response.json().get("error", "nc")
error_msg = _("Something went wrong during your token generation. Maybe your Authorization Code is invalid or already expired [%s]", error_key)
raise UserError(error_msg)
def _sync_microsoft_calendar(self, calendar_service: MicrosoftCalendarService):
self.ensure_one()
full_sync = not bool(self.microsoft_calendar_sync_token)
with microsoft_calendar_token(self) as token:
try:
events, next_sync_token, default_reminders = calendar_service.get_events(self.microsoft_calendar_sync_token, token=token)
except InvalidSyncToken:
events, next_sync_token, default_reminders = calendar_service.get_events(token=token)
full_sync = True
self.microsoft_calendar_sync_token = next_sync_token
# Microsoft -> Odoo
recurrences = events.filter(lambda e: e.is_recurrent())
synced_events, synced_recurrences = self.env['calendar.event']._sync_microsoft2odoo(events, default_reminders=default_reminders) if events else (self.env['calendar.event'], self.env['calendar.recurrence'])
# Odoo -> Microsoft
recurrences = self.env['calendar.recurrence']._get_microsoft_records_to_sync(full_sync=full_sync)
recurrences -= synced_recurrences
recurrences._sync_odoo2microsoft(calendar_service)
synced_events |= recurrences.calendar_event_ids
events = self.env['calendar.event']._get_microsoft_records_to_sync(full_sync=full_sync)
(events - synced_events)._sync_odoo2microsoft(calendar_service)
return bool(events | synced_events) or bool(recurrences | synced_recurrences)
@api.model
def _sync_all_microsoft_calendar(self):
""" Cron job """
users = self.env['res.users'].search([('microsoft_calendar_rtoken', '!=', False)])
microsoft = MicrosoftCalendarService(self.env['microsoft.service'])<|fim▁hole|> except Exception as e:
_logger.exception("[%s] Calendar Synchro - Exception : %s !", user, exception_to_unicode(e))<|fim▁end|> | for user in users:
_logger.info("Calendar Synchro - Starting synchronization for %s", user)
try:
user.with_user(user).sudo()._sync_microsoft_calendar(microsoft) |
<|file_name|>test_sdist.py<|end_file_name|><|fim▁begin|>"""Tests for distutils.command.sdist."""
import os
import tarfile
import unittest
import warnings
import zipfile
from os.path import join
from textwrap import dedent
from test.test_support import captured_stdout, check_warnings, run_unittest
# zlib is not used here, but if it's not available
# the tests that use zipfile may fail
try:
import zlib
except ImportError:
zlib = None
try:
import grp
import pwd
UID_GID_SUPPORT = True
except ImportError:
UID_GID_SUPPORT = False
from distutils.command.sdist import sdist, show_formats
from distutils.core import Distribution
from distutils.tests.test_config import PyPIRCCommandTestCase
from distutils.errors import DistutilsOptionError
from distutils.spawn import find_executable
from distutils.log import WARN
from distutils.filelist import FileList
from distutils.archive_util import ARCHIVE_FORMATS
SETUP_PY = """
from distutils.core import setup
import somecode
setup(name='fake')
"""
MANIFEST = """\
# file GENERATED by distutils, do NOT edit
README
buildout.cfg
inroot.txt
setup.py
data%(sep)sdata.dt
scripts%(sep)sscript.py
some%(sep)sfile.txt
some%(sep)sother_file.txt
somecode%(sep)s__init__.py
somecode%(sep)sdoc.dat
somecode%(sep)sdoc.txt
"""
class SDistTestCase(PyPIRCCommandTestCase):
def setUp(self):
# PyPIRCCommandTestCase creates a temp dir already
# and put it in self.tmp_dir
super(SDistTestCase, self).setUp()
# setting up an environment
self.old_path = os.getcwd()
os.mkdir(join(self.tmp_dir, 'somecode'))
os.mkdir(join(self.tmp_dir, 'dist'))
# a package, and a README
self.write_file((self.tmp_dir, 'README'), 'xxx')
self.write_file((self.tmp_dir, 'somecode', '__init__.py'), '#')
self.write_file((self.tmp_dir, 'setup.py'), SETUP_PY)
os.chdir(self.tmp_dir)
def tearDown(self):
# back to normal
os.chdir(self.old_path)
super(SDistTestCase, self).tearDown()
def get_cmd(self, metadata=None):
"""Returns a cmd"""
if metadata is None:
metadata = {'name': 'fake', 'version': '1.0',
'url': 'xxx', 'author': 'xxx',
'author_email': 'xxx'}
dist = Distribution(metadata)
dist.script_name = 'setup.py'
dist.packages = ['somecode']
dist.include_package_data = True
cmd = sdist(dist)
cmd.dist_dir = 'dist'
return dist, cmd
@unittest.skipUnless(zlib, "requires zlib")
def test_prune_file_list(self):
# this test creates a package with some vcs dirs in it
# and launch sdist to make sure they get pruned
# on all systems
# creating VCS directories with some files in them
os.mkdir(join(self.tmp_dir, 'somecode', '.svn'))
self.write_file((self.tmp_dir, 'somecode', '.svn', 'ok.py'), 'xxx')
os.mkdir(join(self.tmp_dir, 'somecode', '.hg'))
self.write_file((self.tmp_dir, 'somecode', '.hg',
'ok'), 'xxx')
os.mkdir(join(self.tmp_dir, 'somecode', '.git'))
self.write_file((self.tmp_dir, 'somecode', '.git',
'ok'), 'xxx')
# now building a sdist
dist, cmd = self.get_cmd()
# zip is available universally
# (tar might not be installed under win32)
cmd.formats = ['zip']
cmd.ensure_finalized()
cmd.run()
# now let's check what we have
dist_folder = join(self.tmp_dir, 'dist')
files = os.listdir(dist_folder)
self.assertEqual(files, ['fake-1.0.zip'])
zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip'))
try:
content = zip_file.namelist()
finally:
zip_file.close()
# making sure everything has been pruned correctly
self.assertEqual(len(content), 4)
@unittest.skipUnless(zlib, "requires zlib")<|fim▁hole|> if (find_executable('tar') is None or
find_executable('gzip') is None):
return
# now building a sdist
dist, cmd = self.get_cmd()
# creating a gztar then a tar
cmd.formats = ['gztar', 'tar']
cmd.ensure_finalized()
cmd.run()
# making sure we have two files
dist_folder = join(self.tmp_dir, 'dist')
result = os.listdir(dist_folder)
result.sort()
self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz'])
os.remove(join(dist_folder, 'fake-1.0.tar'))
os.remove(join(dist_folder, 'fake-1.0.tar.gz'))
# now trying a tar then a gztar
cmd.formats = ['tar', 'gztar']
cmd.ensure_finalized()
cmd.run()
result = os.listdir(dist_folder)
result.sort()
self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz'])
@unittest.skipUnless(zlib, "requires zlib")
def test_unicode_metadata_tgz(self):
"""
Unicode name or version should not break building to tar.gz format.
Reference issue #11638.
"""
# create the sdist command with unicode parameters
dist, cmd = self.get_cmd({'name': u'fake', 'version': u'1.0'})
# create the sdist as gztar and run the command
cmd.formats = ['gztar']
cmd.ensure_finalized()
cmd.run()
# The command should have created the .tar.gz file
dist_folder = join(self.tmp_dir, 'dist')
result = os.listdir(dist_folder)
self.assertEqual(result, ['fake-1.0.tar.gz'])
os.remove(join(dist_folder, 'fake-1.0.tar.gz'))
@unittest.skipUnless(zlib, "requires zlib")
def test_add_defaults(self):
# http://bugs.python.org/issue2279
# add_default should also include
# data_files and package_data
dist, cmd = self.get_cmd()
# filling data_files by pointing files
# in package_data
dist.package_data = {'': ['*.cfg', '*.dat'],
'somecode': ['*.txt']}
self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#')
self.write_file((self.tmp_dir, 'somecode', 'doc.dat'), '#')
# adding some data in data_files
data_dir = join(self.tmp_dir, 'data')
os.mkdir(data_dir)
self.write_file((data_dir, 'data.dt'), '#')
some_dir = join(self.tmp_dir, 'some')
os.mkdir(some_dir)
# make sure VCS directories are pruned (#14004)
hg_dir = join(self.tmp_dir, '.hg')
os.mkdir(hg_dir)
self.write_file((hg_dir, 'last-message.txt'), '#')
# a buggy regex used to prevent this from working on windows (#6884)
self.write_file((self.tmp_dir, 'buildout.cfg'), '#')
self.write_file((self.tmp_dir, 'inroot.txt'), '#')
self.write_file((some_dir, 'file.txt'), '#')
self.write_file((some_dir, 'other_file.txt'), '#')
dist.data_files = [('data', ['data/data.dt',
'buildout.cfg',
'inroot.txt',
'notexisting']),
'some/file.txt',
'some/other_file.txt']
# adding a script
script_dir = join(self.tmp_dir, 'scripts')
os.mkdir(script_dir)
self.write_file((script_dir, 'script.py'), '#')
dist.scripts = [join('scripts', 'script.py')]
cmd.formats = ['zip']
cmd.use_defaults = True
cmd.ensure_finalized()
cmd.run()
# now let's check what we have
dist_folder = join(self.tmp_dir, 'dist')
files = os.listdir(dist_folder)
self.assertEqual(files, ['fake-1.0.zip'])
zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip'))
try:
content = zip_file.namelist()
finally:
zip_file.close()
# making sure everything was added
self.assertEqual(len(content), 12)
# checking the MANIFEST
f = open(join(self.tmp_dir, 'MANIFEST'))
try:
manifest = f.read()
finally:
f.close()
self.assertEqual(manifest, MANIFEST % {'sep': os.sep})
@unittest.skipUnless(zlib, "requires zlib")
def test_metadata_check_option(self):
# testing the `medata-check` option
dist, cmd = self.get_cmd(metadata={})
# this should raise some warnings !
# with the `check` subcommand
cmd.ensure_finalized()
cmd.run()
warnings = [msg for msg in self.get_logs(WARN) if
msg.startswith('warning: check:')]
self.assertEqual(len(warnings), 2)
# trying with a complete set of metadata
self.clear_logs()
dist, cmd = self.get_cmd()
cmd.ensure_finalized()
cmd.metadata_check = 0
cmd.run()
warnings = [msg for msg in self.get_logs(WARN) if
msg.startswith('warning: check:')]
self.assertEqual(len(warnings), 0)
def test_check_metadata_deprecated(self):
# makes sure make_metadata is deprecated
dist, cmd = self.get_cmd()
with check_warnings() as w:
warnings.simplefilter("always")
cmd.check_metadata()
self.assertEqual(len(w.warnings), 1)
def test_show_formats(self):
with captured_stdout() as stdout:
show_formats()
# the output should be a header line + one line per format
num_formats = len(ARCHIVE_FORMATS.keys())
output = [line for line in stdout.getvalue().split('\n')
if line.strip().startswith('--formats=')]
self.assertEqual(len(output), num_formats)
def test_finalize_options(self):
dist, cmd = self.get_cmd()
cmd.finalize_options()
# default options set by finalize
self.assertEqual(cmd.manifest, 'MANIFEST')
self.assertEqual(cmd.template, 'MANIFEST.in')
self.assertEqual(cmd.dist_dir, 'dist')
# formats has to be a string splitable on (' ', ',') or
# a stringlist
cmd.formats = 1
self.assertRaises(DistutilsOptionError, cmd.finalize_options)
cmd.formats = ['zip']
cmd.finalize_options()
# formats has to be known
cmd.formats = 'supazipa'
self.assertRaises(DistutilsOptionError, cmd.finalize_options)
@unittest.skipUnless(zlib, "requires zlib")
@unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
def test_make_distribution_owner_group(self):
# check if tar and gzip are installed
if (find_executable('tar') is None or
find_executable('gzip') is None):
return
# now building a sdist
dist, cmd = self.get_cmd()
# creating a gztar and specifying the owner+group
cmd.formats = ['gztar']
cmd.owner = pwd.getpwuid(0)[0]
cmd.group = grp.getgrgid(0)[0]
cmd.ensure_finalized()
cmd.run()
# making sure we have the good rights
archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz')
archive = tarfile.open(archive_name)
try:
for member in archive.getmembers():
self.assertEqual(member.uid, 0)
self.assertEqual(member.gid, 0)
finally:
archive.close()
# building a sdist again
dist, cmd = self.get_cmd()
# creating a gztar
cmd.formats = ['gztar']
cmd.ensure_finalized()
cmd.run()
# making sure we have the good rights
archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz')
archive = tarfile.open(archive_name)
# note that we are not testing the group ownership here
# because, depending on the platforms and the container
# rights (see #7408)
try:
for member in archive.getmembers():
self.assertEqual(member.uid, os.getuid())
finally:
archive.close()
# the following tests make sure there is a nice error message instead
# of a traceback when parsing an invalid manifest template
def _check_template(self, content):
dist, cmd = self.get_cmd()
os.chdir(self.tmp_dir)
self.write_file('MANIFEST.in', content)
cmd.ensure_finalized()
cmd.filelist = FileList()
cmd.read_template()
warnings = self.get_logs(WARN)
self.assertEqual(len(warnings), 1)
def test_invalid_template_unknown_command(self):
self._check_template('taunt knights *')
def test_invalid_template_wrong_arguments(self):
# this manifest command takes one argument
self._check_template('prune')
@unittest.skipIf(os.name != 'nt', 'test relevant for Windows only')
def test_invalid_template_wrong_path(self):
# on Windows, trailing slashes are not allowed
# this used to crash instead of raising a warning: #8286
self._check_template('include examples/')
@unittest.skipUnless(zlib, "requires zlib")
def test_get_file_list(self):
# make sure MANIFEST is recalculated
dist, cmd = self.get_cmd()
# filling data_files by pointing files in package_data
dist.package_data = {'somecode': ['*.txt']}
self.write_file((self.tmp_dir, 'somecode', 'doc.txt'), '#')
cmd.formats = ['gztar']
cmd.ensure_finalized()
cmd.run()
f = open(cmd.manifest)
try:
manifest = [line.strip() for line in f.read().split('\n')
if line.strip() != '']
finally:
f.close()
self.assertEqual(len(manifest), 5)
# adding a file
self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#')
# make sure build_py is reinitialized, like a fresh run
build_py = dist.get_command_obj('build_py')
build_py.finalized = False
build_py.ensure_finalized()
cmd.run()
f = open(cmd.manifest)
try:
manifest2 = [line.strip() for line in f.read().split('\n')
if line.strip() != '']
finally:
f.close()
# do we have the new file in MANIFEST ?
self.assertEqual(len(manifest2), 6)
self.assertIn('doc2.txt', manifest2[-1])
@unittest.skipUnless(zlib, "requires zlib")
def test_manifest_marker(self):
# check that autogenerated MANIFESTs have a marker
dist, cmd = self.get_cmd()
cmd.ensure_finalized()
cmd.run()
f = open(cmd.manifest)
try:
manifest = [line.strip() for line in f.read().split('\n')
if line.strip() != '']
finally:
f.close()
self.assertEqual(manifest[0],
'# file GENERATED by distutils, do NOT edit')
@unittest.skipUnless(zlib, 'requires zlib')
def test_manifest_comments(self):
# make sure comments don't cause exceptions or wrong includes
contents = dedent("""\
# bad.py
#bad.py
good.py
""")
dist, cmd = self.get_cmd()
cmd.ensure_finalized()
self.write_file((self.tmp_dir, cmd.manifest), contents)
self.write_file((self.tmp_dir, 'good.py'), '# pick me!')
self.write_file((self.tmp_dir, 'bad.py'), "# don't pick me!")
self.write_file((self.tmp_dir, '#bad.py'), "# don't pick me!")
cmd.run()
self.assertEqual(cmd.filelist.files, ['good.py'])
@unittest.skipUnless(zlib, "requires zlib")
def test_manual_manifest(self):
# check that a MANIFEST without a marker is left alone
dist, cmd = self.get_cmd()
cmd.formats = ['gztar']
cmd.ensure_finalized()
self.write_file((self.tmp_dir, cmd.manifest), 'README.manual')
self.write_file((self.tmp_dir, 'README.manual'),
'This project maintains its MANIFEST file itself.')
cmd.run()
self.assertEqual(cmd.filelist.files, ['README.manual'])
f = open(cmd.manifest)
try:
manifest = [line.strip() for line in f.read().split('\n')
if line.strip() != '']
finally:
f.close()
self.assertEqual(manifest, ['README.manual'])
archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz')
archive = tarfile.open(archive_name)
try:
filenames = [tarinfo.name for tarinfo in archive]
finally:
archive.close()
self.assertEqual(sorted(filenames), ['fake-1.0', 'fake-1.0/PKG-INFO',
'fake-1.0/README.manual'])
def test_suite():
return unittest.makeSuite(SDistTestCase)
if __name__ == "__main__":
run_unittest(test_suite())<|fim▁end|> | def test_make_distribution(self):
# check if tar and gzip are installed |
<|file_name|>PrimitiveTypeImpl.java<|end_file_name|><|fim▁begin|>/**
*/
package es.um.nosql.streaminginference.NoSQLSchema.impl;
import es.um.nosql.streaminginference.NoSQLSchema.NoSQLSchemaPackage;
import es.um.nosql.streaminginference.NoSQLSchema.PrimitiveType;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Primitive Type</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link es.um.nosql.streaminginference.NoSQLSchema.impl.PrimitiveTypeImpl#getName <em>Name</em>}</li>
* </ul>
*
* @generated
*/
public class PrimitiveTypeImpl extends TypeImpl implements PrimitiveType {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final long serialVersionUID = 6870693875L;
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected PrimitiveTypeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return NoSQLSchemaPackage.Literals.PRIMITIVE_TYPE;<|fim▁hole|> }
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName) {
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, NoSQLSchemaPackage.PRIMITIVE_TYPE__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case NoSQLSchemaPackage.PRIMITIVE_TYPE__NAME:
return getName();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case NoSQLSchemaPackage.PRIMITIVE_TYPE__NAME:
setName((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case NoSQLSchemaPackage.PRIMITIVE_TYPE__NAME:
setName(NAME_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case NoSQLSchemaPackage.PRIMITIVE_TYPE__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: ");
result.append(name);
result.append(')');
return result.toString();
}
} //PrimitiveTypeImpl<|fim▁end|> | |
<|file_name|>stack.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""stack.py: Stack implementation"""
__author__ = 'Rohit Sinha'
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
def __str__(self):
return str(self.items).strip('[]')
if __name__ == '__main__':
s = Stack()
print(s.isEmpty())<|fim▁hole|> print(s.peek())
print(s.size())
print(s.pop())
print(s)<|fim▁end|> | s.push(5)
s.push('Hello')
print(s.peek())
s.push(True) |
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>use proc_macro2::TokenStream;
use quote::quote;
use std::env;
use std::fs::File;
use std::io::{prelude::*, BufReader, BufWriter};
use std::path::Path;
fn get_data_file(path_fragment: &str) -> BufReader<File> {
println!("cargo:rerun-if-changed=../data/{}", path_fragment);
let path = Path::new("../data").join(path_fragment);
BufReader::new(File::open(path).expect("Something went wrong reading the file"))
}
fn ivd_sequences() -> TokenStream {
let ivd_seqs_file = get_data_file("Unicode/IVD/IVD_Sequences.txt");
let lines: Vec<_> = ivd_seqs_file
.lines()
.map(Result::unwrap)
.filter(|line| !line.is_empty() && !line.starts_with('#'))
.collect();
let array_size = lines.len();
let structs: TokenStream = lines
.iter()
.map(|line| {
let parts: Vec<_> = line.split(';').map(|s| s.trim()).collect();
let codepoint_parts: Vec<_> = parts[0].split(' ').collect();
let base_codepoint = u32::from_str_radix(codepoint_parts[0].trim(), 16).unwrap();
let variation_selector = u32::from_str_radix(codepoint_parts[1].trim(), 16).unwrap();
let collection = parts[1].trim();
let item = parts[2].trim();
quote! {
IdeographicVariationSequence {
base_codepoint: #base_codepoint,
variation_selector: #variation_selector,
collection: #collection,
item: #item
},
}
})
.collect();
quote! {
pub(crate) const IVD_SEQUENCES: [IdeographicVariationSequence; #array_size] = [
#structs
];
}
}
fn build_encoding_table(name: &str, data_file: &str) -> TokenStream {
let encoding_table_file = get_data_file(data_file);
let lines: Vec<_> = encoding_table_file
.lines()
.map(Result::unwrap)
// remove text after first '#'
.map(|line| line.split('#').next().unwrap().to_string())
.filter(|line| !line.is_empty())
// weird format found in CP857 (and others)
.filter(|line| line != "\x1a")
.collect();
let mappings: TokenStream = lines
.iter()
.map(|line| line.split('\t').collect::<Vec<_>>())
.filter(|components| !components[1].trim().is_empty())
.map(|components| {
let coded_byte = u32::from_str_radix(&components[0][2..], 16).unwrap();
let codepoint = u32::from_str_radix(&components[1][2..], 16).unwrap();
quote! {
(#codepoint, #coded_byte),
}
})
.collect();
quote! {
encoding_table.insert(#name, [#mappings].iter().cloned().collect());
}
}
fn build_encodings() -> TokenStream {
let tables: TokenStream = [
build_encoding_table("ASCII", "ascii.txt"),
build_encoding_table(
"ASCII with typographical quotes",
"Unicode/Mappings/VENDORS/MISC/US-ASCII-QUOTES.TXT",
),
build_encoding_table(
"ISO-8859-1 (Latin-1 Western European)",
"Unicode/Mappings/ISO8859/8859-1.TXT",
),
build_encoding_table(
"ISO-8859-2 (Latin-2 Central European)",
"Unicode/Mappings/ISO8859/8859-2.TXT",
),
build_encoding_table(
"ISO-8859-3 (Latin-3 South European)",
"Unicode/Mappings/ISO8859/8859-3.TXT",
),
build_encoding_table(
"ISO-8859-4 (Latin-4 North European)",
"Unicode/Mappings/ISO8859/8859-4.TXT",
),
build_encoding_table(
"ISO-8859-5 (Latin/Cyrillic)",
"Unicode/Mappings/ISO8859/8859-5.TXT",
),
build_encoding_table(
"ISO-8859-6 (Latin/Arabic)",
"Unicode/Mappings/ISO8859/8859-6.TXT",
),
build_encoding_table(
"ISO-8859-7 (Latin/Greek)",
"Unicode/Mappings/ISO8859/8859-7.TXT",
),
build_encoding_table(
"ISO-8859-8 (Latin/Hebrew)",
"Unicode/Mappings/ISO8859/8859-8.TXT",
),
build_encoding_table(
"ISO-8859-9 (Latin-5 Turkish)",
"Unicode/Mappings/ISO8859/8859-9.TXT",
),
build_encoding_table(
"ISO-8859-10 (Latin-6 Nordic)",
"Unicode/Mappings/ISO8859/8859-10.TXT",
),
build_encoding_table(
"ISO-8859-11 (Latin/Thai)",
"Unicode/Mappings/ISO8859/8859-11.TXT",
),
build_encoding_table(
"ISO-8859-13 (Latin-7 Baltic Rim)",
"Unicode/Mappings/ISO8859/8859-13.TXT",
),
build_encoding_table(
"ISO-8859-14 (Latin-8 Celtic)",
"Unicode/Mappings/ISO8859/8859-14.TXT",
),
build_encoding_table(
"ISO-8859-15 (Latin-9)",
"Unicode/Mappings/ISO8859/8859-15.TXT",
),
build_encoding_table(
"ISO-8859-16 (Latin-10 South-Eastern European)",
"Unicode/Mappings/ISO8859/8859-16.TXT",
),
build_encoding_table(
"Code page 437 (MS-DOS Latin US)",
"Unicode/Mappings/VENDORS/MICSFT/PC/CP437.TXT",
),
build_encoding_table(
"Code page 737 (MS-DOS Greek)",
"Unicode/Mappings/VENDORS/MICSFT/PC/CP737.TXT",
),
build_encoding_table(
"Code page 775 (MS-DOS Baltic Rim)",
"Unicode/Mappings/VENDORS/MICSFT/PC/CP775.TXT",
),
build_encoding_table(
"Code page 850 (MS-DOS Latin 1)",
"Unicode/Mappings/VENDORS/MICSFT/PC/CP850.TXT",
),
build_encoding_table(
"Code page 852 (MS-DOS Latin 2)",
"Unicode/Mappings/VENDORS/MICSFT/PC/CP852.TXT",
),
build_encoding_table(
"Code page 855 (MS-DOS Cyrillic)",
"Unicode/Mappings/VENDORS/MICSFT/PC/CP855.TXT",
),
build_encoding_table(
"Code page 857 (MS-DOS Turkish)",
"Unicode/Mappings/VENDORS/MICSFT/PC/CP857.TXT",
),
build_encoding_table(
"Code page 860 (MS-DOS Portuguese)",
"Unicode/Mappings/VENDORS/MICSFT/PC/CP860.TXT",
),
build_encoding_table(
"Code page 861 (MS-DOS Icelandic)",
"Unicode/Mappings/VENDORS/MICSFT/PC/CP861.TXT",
),
build_encoding_table(
"Code page 862 (MS-DOS Hebrew)",
"Unicode/Mappings/VENDORS/MICSFT/PC/CP862.TXT",
),
build_encoding_table(
"Code page 863 (MS-DOS French Canada)",
"Unicode/Mappings/VENDORS/MICSFT/PC/CP863.TXT",
),
build_encoding_table(
"Code page 864 (MS-DOS Arabic)",
"Unicode/Mappings/VENDORS/MICSFT/PC/CP864.TXT",
),
build_encoding_table(
"Code page 865 (MS-DOS Nordic)",
"Unicode/Mappings/VENDORS/MICSFT/PC/CP865.TXT",
),
build_encoding_table(
"Code page 866 (MS-DOS Cyrillic CIS 1)",
"Unicode/Mappings/VENDORS/MICSFT/PC/CP866.TXT",
),
build_encoding_table(
"Code page 869 (MS-DOS Greek 2)",
"Unicode/Mappings/VENDORS/MICSFT/PC/CP869.TXT",
),
build_encoding_table(
"Code page 874 (Thai)",
"Unicode/Mappings/VENDORS/MICSFT/WINDOWS/CP874.TXT",
),
build_encoding_table(
"Code page 932 (Japanese; Shift-JIS extension)",
"Unicode/Mappings/VENDORS/MICSFT/WINDOWS/CP932.TXT",
),
build_encoding_table(
"Code page 936 (Simplified Chinese)",
"Unicode/Mappings/VENDORS/MICSFT/WINDOWS/CP936.TXT",
),
build_encoding_table(
"Code page 949 (Korean)",
"Unicode/Mappings/VENDORS/MICSFT/WINDOWS/CP949.TXT",
),
build_encoding_table(
"Code page 950 (Traditional Chinese)",
"Unicode/Mappings/VENDORS/MICSFT/WINDOWS/CP950.TXT",
),
build_encoding_table(
"Code page 1250 (Windows Latin 2 (Central Europe))",
"Unicode/Mappings/VENDORS/MICSFT/WINDOWS/CP1250.TXT",
),
build_encoding_table(
"Code page 1251 (Windows Cyrillic (Slavic))",
"Unicode/Mappings/VENDORS/MICSFT/WINDOWS/CP1251.TXT",
),
build_encoding_table(
"Code page 1252 (Windows Latin 1 (ANSI))",
"Unicode/Mappings/VENDORS/MICSFT/WINDOWS/CP1252.TXT",
),
build_encoding_table(
"Code page 1253 (Windows Greek)",
"Unicode/Mappings/VENDORS/MICSFT/WINDOWS/CP1253.TXT",
),
build_encoding_table(<|fim▁hole|> "Unicode/Mappings/VENDORS/MICSFT/WINDOWS/CP1254.TXT",
),
build_encoding_table(
"Code page 1255 (Windows Hebrew)",
"Unicode/Mappings/VENDORS/MICSFT/WINDOWS/CP1255.TXT",
),
build_encoding_table(
"Code page 1256 (Windows Arabic)",
"Unicode/Mappings/VENDORS/MICSFT/WINDOWS/CP1256.TXT",
),
build_encoding_table(
"Code page 1257 (Windows Baltic Rim)",
"Unicode/Mappings/VENDORS/MICSFT/WINDOWS/CP1257.TXT",
),
build_encoding_table(
"Code page 1258 (Windows Vietnamese)",
"Unicode/Mappings/VENDORS/MICSFT/WINDOWS/CP1258.TXT",
),
build_encoding_table(
"Code page 10000 (Macintosh Roman)",
"Unicode/Mappings/VENDORS/MICSFT/MAC/ROMAN.TXT",
),
build_encoding_table(
"Code page 10006 (Macintosh Greek)",
"Unicode/Mappings/VENDORS/MICSFT/MAC/GREEK.TXT",
),
build_encoding_table(
"Code page 10007 (Macintosh Cyrillic)",
"Unicode/Mappings/VENDORS/MICSFT/MAC/CYRILLIC.TXT",
),
build_encoding_table(
"Code page 10029 (Macintosh Latin 2)",
"Unicode/Mappings/VENDORS/MICSFT/MAC/LATIN2.TXT",
),
build_encoding_table(
"Code page 10079 (Macintosh Iceland)",
"Unicode/Mappings/VENDORS/MICSFT/MAC/ICELAND.TXT",
),
build_encoding_table(
"Code page 10081 (Macintosh Turkish)",
"Unicode/Mappings/VENDORS/MICSFT/MAC/TURKISH.TXT",
),
build_encoding_table(
"Code page 37 (Microsoft EBCDIC)",
"Unicode/Mappings/VENDORS/MICSFT/EBCDIC/CP037.TXT",
),
build_encoding_table(
"Code page 500 (Microsoft EBCDIC)",
"Unicode/Mappings/VENDORS/MICSFT/EBCDIC/CP500.TXT",
),
build_encoding_table(
"Code page 875 (Microsoft EBCDIC)",
"Unicode/Mappings/VENDORS/MICSFT/EBCDIC/CP875.TXT",
),
build_encoding_table(
"Code page 1026 (Microsoft EBCDIC)",
"Unicode/Mappings/VENDORS/MICSFT/EBCDIC/CP1026.TXT",
),
]
.iter()
.cloned()
.collect();
quote! {
lazy_static! {
pub(crate) static ref ENCODING_TABLES: HashMap<&'static str, EncodingTable> = {
let mut encoding_table = HashMap::new();
#tables
encoding_table
};
}
}
}
fn main() {
let out_dir = env::var_os("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("compiled-data.rs");
write!(
BufWriter::new(File::create(dest_path).unwrap()),
"{}{}",
ivd_sequences(),
build_encodings()
)
.unwrap();
}<|fim▁end|> | "Code page 1254 (Windows Latin 5 (Turkish))", |
<|file_name|>script.py<|end_file_name|><|fim▁begin|>from nider.core import Font
from nider.core import Outline
from nider.models import Header
from nider.models import Paragraph
from nider.models import Linkback
from nider.models import Content
from nider.models import TwitterPost
# TODO: change this fontpath to the fontpath on your machine
roboto_font_folder = '/home/ovd/.local/share/fonts/Roboto/'
outline = Outline(2, '#121212')
header = Header(text='Your super interesting title!',<|fim▁hole|> )
para = Paragraph(text='Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.',
font=Font(roboto_font_folder + 'Roboto-Medium.ttf', 29),
text_width=65,
align='left',
color='#ededed'
)
linkback = Linkback(text='foo.com | @username',
font=Font(roboto_font_folder + 'Roboto-Bold.ttf', 24),
color='#ededed'
)
content = Content(para, header, linkback)
img = TwitterPost(content,
fullpath='result.png'
)
# TODO: change this texture path to the texture path on your machine
img.draw_on_texture('texture.png')<|fim▁end|> | font=Font(roboto_font_folder + 'Roboto-Bold.ttf', 30),
text_width=40,
align='left',
color='#ededed' |
<|file_name|>ui-icon_spec.js<|end_file_name|><|fim▁begin|>/* -*- javascript -*- */
"use strict";
import {StageComponent} from 'aurelia-testing';
import {bootstrap} from 'aurelia-bootstrapper';
import {LogManager} from 'aurelia-framework';
import {ConsoleAppender} from 'aurelia-logging-console';
import {customMatchers} from '../helpers';
describe('ui-icon', () => {
let component, logger;
beforeAll(() => {
jasmine.addMatchers( customMatchers );
logger = LogManager.getLogger( 'ui-icon-spec' );
});
<|fim▁hole|> component = StageComponent.withResources('src/elements/ui-icon');
});
afterEach(() => {
component.dispose();
});
describe( 'as a custom attribute', () => {
it( 'adds semantic classes when bound', done => {
component.
inView(`
<i ui-icon="name: cloud"></i>
`).
boundTo({}).
create( bootstrap ).then( () => {
expect( component.element ).toHaveCssClasses( 'cloud', 'icon' );
}).
then( done ).
catch( done.fail );
});
it( 'has a reasonable name default', done => {
component.
inView(`
<i ui-icon></i>
`).
boundTo({}).
create( bootstrap ).then( () => {
expect( component.element ).toHaveCssClasses( 'help', 'circle', 'icon' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a size class when one is set', done => {
component.
inView(`
<i ui-icon="name: cloud; size: huge"></i>
`).
boundTo({}).
create( bootstrap ).then( () => {
expect( component.element ).toHaveCssClasses( 'huge', 'cloud', 'icon' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a color class when one is set', done => {
component.
inView(`
<i ui-icon="name: user; color: red">Erase History</i>
`).
boundTo({}).
create( bootstrap ).then( () => {
expect( component.element ).toHaveCssClasses( 'red', 'user', 'icon' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a disabled class when it is set', done => {
component.
inView(`
<i ui-icon="disabled: true">Eject!</i>
`).
boundTo({}).
create( bootstrap ).then( () => {
expect( component.element ).toHaveCssClasses( 'disabled', 'icon' );
}).
then( done ).
catch( done.fail );
});
});
describe( 'as a custom element', () => {
it( 'uses the icon name', done => {
component.
inView(`
<ui-icon name="cloud"></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'cloud' );
}).
then( done ).
catch( done.fail );
});
it( 'support multiple names', done => {
component.
inView(`
<ui-icon name="circular inverted users"></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'circular', 'inverted', 'users' );
}).
then( done ).
catch( done.fail );
});
it( 'has a reasonable default name', done => {
component.
inView(`
<ui-icon></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'help', 'circle' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a size class when one is set', done => {
component.
inView(`
<ui-icon size="huge"></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'huge' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a color class when one is set', done => {
component.
inView(`
<ui-icon color="red"></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'red' );
}).
then( done ).
catch( done.fail );
});
it( 'adds a disabled class when it is set', done => {
component.
inView(`
<ui-icon disabled="true"></ui-icon>
`).
boundTo({}).
create( bootstrap ).then( () => {
let icon = component.viewModel.semanticElement;
expect( icon ).toBeDefined();
expect( icon.nodeType ).toEqual( 1 );
expect( icon ).toHaveCssClasses( 'disabled' );
}).
then( done ).
catch( done.fail );
});
});
});<|fim▁end|> | beforeEach(() => { |
Subsets and Splits