file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
plane.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
// | |
// | System Syzygy 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. |
// | |
// | System Syzygy 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 details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use num_integer::div_floor;
use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use crate::gui::{
Action, Align, Canvas, Element, Event, Font, Point, Rect, Resources,
Sprite,
};
use crate::save::plane::{PlaneGrid, PlaneObj};
use crate::save::Direction;
// ========================================================================= //
pub enum PlaneCmd {
Changed,
PushUndo(Vec<(Point, Point)>),
}
// ========================================================================= //
const TILE_USIZE: u32 = 24;
const TILE_ISIZE: i32 = TILE_USIZE as i32;
pub struct PlaneGridView {
left: i32,
top: i32,
obj_sprites: Vec<Sprite>,
pipe_sprites: Vec<Sprite>,
drag_from: Option<Point>,
changes: Vec<(Point, Point)>,
font: Rc<Font>,
letters: HashMap<Point, char>,
}
impl PlaneGridView {
pub fn new(
resources: &mut Resources,
left: i32,
top: i32,
) -> PlaneGridView {
PlaneGridView {
left,
top,
obj_sprites: resources.get_sprites("plane/objects"),
pipe_sprites: resources.get_sprites("plane/pipes"),
drag_from: None,
changes: Vec::new(),
font: resources.get_font("roman"),
letters: HashMap::new(),
}
}
pub fn cancel_drag_and_clear_changes(&mut self) {
self.drag_from = None;
self.changes.clear();
}
pub fn cancel_drag_and_undo_changes(&mut self, grid: &mut PlaneGrid) {
self.drag_from = None;
for &(coords1, coords2) in self.changes.iter().rev() {
grid.toggle_pipe(coords1, coords2);
}
self.changes.clear();
}
pub fn add_letter(&mut self, coords: Point, letter: char) {
self.letters.insert(coords, letter);
}
fn rect(&self, grid: &PlaneGrid) -> Rect {
Rect::new(
self.left,
self.top,
grid.num_cols() * TILE_USIZE,
grid.num_rows() * TILE_USIZE,
)
}
fn pt_to_coords(&self, grid: &PlaneGrid, pt: Point) -> Option<Point> {
let col = div_floor(pt.x() - self.left, TILE_ISIZE);
let row = div_floor(pt.y() - self.top, TILE_ISIZE);
let coords = Point::new(col, row);
if grid.contains_coords(coords) {
Some(coords)
} else {
None
}
}
fn | (
&self,
grid: &PlaneGrid,
pos: Point,
dir: Direction,
canvas: &mut Canvas,
) {
let obj = grid.objects().get(&pos).cloned();
let sprite_index = match (dir, obj) {
(Direction::West, Some(PlaneObj::Cross)) => 10,
(Direction::West, Some(obj)) if obj.is_node() => 13,
(Direction::West, _) => 0,
(Direction::East, Some(PlaneObj::Cross)) => 11,
(Direction::East, Some(obj)) if obj.is_node() => 15,
(Direction::East, _) => 2,
(Direction::South, Some(obj)) if obj.is_node() => 14,
(Direction::South, _) => 1,
(Direction::North, Some(obj)) if obj.is_node() => 16,
(Direction::North, _) => 3,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, pos * TILE_ISIZE);
}
}
impl Element<PlaneGrid, PlaneCmd> for PlaneGridView {
fn draw(&self, grid: &PlaneGrid, canvas: &mut Canvas) {
let mut canvas = canvas.subcanvas(self.rect(grid));
canvas.clear((64, 64, 64));
for row in 0..(grid.num_rows() as i32) {
for col in 0..(grid.num_cols() as i32) {
let coords = Point::new(col, row);
if let Some(&obj) = grid.objects().get(&coords) {
let sprite_index = match obj {
PlaneObj::Wall => 0,
PlaneObj::Cross => 1,
PlaneObj::PurpleNode => 2,
PlaneObj::RedNode => 3,
PlaneObj::GreenNode => 4,
PlaneObj::BlueNode => 5,
PlaneObj::GrayNode => 6,
};
let sprite = &self.obj_sprites[sprite_index];
canvas.draw_sprite(sprite, coords * TILE_ISIZE);
} else {
let pt = coords * TILE_ISIZE;
let rect = Rect::new(
pt.x() + 1,
pt.y() + 1,
TILE_USIZE - 2,
TILE_USIZE - 2,
);
canvas.draw_rect((72, 72, 72), rect);
}
}
}
for pipe in grid.pipes() {
debug_assert!(pipe.len() >= 2);
let mut start = pipe[0];
let mut next = pipe[1];
let mut dir = Direction::from_delta(next - start);
self.draw_pipe_tip(grid, start, dir, &mut canvas);
for index in 2..pipe.len() {
start = next;
next = pipe[index];
let prev_dir = dir;
dir = Direction::from_delta(next - start);
let sprite_index = match (prev_dir, dir) {
(Direction::East, Direction::North) => 6,
(Direction::East, Direction::South) => 7,
(Direction::West, Direction::North) => 5,
(Direction::West, Direction::South) => 4,
(Direction::East, _) | (Direction::West, _) => {
let obj = grid.objects().get(&start).cloned();
if obj == Some(PlaneObj::Cross) {
12
} else {
8
}
}
(Direction::North, Direction::East) => 4,
(Direction::North, Direction::West) => 7,
(Direction::South, Direction::East) => 5,
(Direction::South, Direction::West) => 6,
(Direction::North, _) | (Direction::South, _) => 9,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, start * TILE_ISIZE);
}
dir = Direction::from_delta(start - next);
self.draw_pipe_tip(grid, next, dir, &mut canvas);
}
for (&coords, &letter) in self.letters.iter() {
let pt = Point::new(
coords.x() * TILE_ISIZE + TILE_ISIZE / 2,
coords.y() * TILE_ISIZE + TILE_ISIZE / 2 + 4,
);
canvas.draw_char(&self.font, Align::Center, pt, letter);
}
}
fn handle_event(
&mut self,
event: &Event,
grid: &mut PlaneGrid,
) -> Action<PlaneCmd> {
match event {
&Event::MouseDown(pt) if self.rect(grid).contains_point(pt) => {
self.drag_from = self.pt_to_coords(grid, pt);
Action::ignore().and_stop()
}
&Event::MouseDrag(pt) => {
if let Some(coords1) = self.drag_from {
if let Some(coords2) = self.pt_to_coords(grid, pt) {
self.drag_from = Some(coords2);
if grid.toggle_pipe(coords1, coords2) {
self.changes.push((coords1, coords2));
return Action::redraw()
.and_return(PlaneCmd::Changed);
}
}
}
Action::ignore()
}
&Event::MouseUp => {
self.drag_from = None;
if self.changes.is_empty() {
Action::ignore()
} else {
let vec = mem::replace(&mut self.changes, Vec::new());
Action::redraw().and_return(PlaneCmd::PushUndo(vec))
}
}
_ => Action::ignore(),
}
}
}
// ========================================================================= //
| draw_pipe_tip | identifier_name |
plane.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
// | |
// | System Syzygy 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. |
// | |
// | System Syzygy 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 details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use num_integer::div_floor;
use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use crate::gui::{
Action, Align, Canvas, Element, Event, Font, Point, Rect, Resources,
Sprite,
};
use crate::save::plane::{PlaneGrid, PlaneObj};
use crate::save::Direction;
// ========================================================================= //
pub enum PlaneCmd {
Changed,
PushUndo(Vec<(Point, Point)>),
}
// ========================================================================= //
const TILE_USIZE: u32 = 24;
const TILE_ISIZE: i32 = TILE_USIZE as i32;
pub struct PlaneGridView {
left: i32,
top: i32,
obj_sprites: Vec<Sprite>,
pipe_sprites: Vec<Sprite>,
drag_from: Option<Point>,
changes: Vec<(Point, Point)>,
font: Rc<Font>,
letters: HashMap<Point, char>,
}
impl PlaneGridView {
pub fn new(
resources: &mut Resources,
left: i32,
top: i32,
) -> PlaneGridView {
PlaneGridView {
left,
top,
obj_sprites: resources.get_sprites("plane/objects"),
pipe_sprites: resources.get_sprites("plane/pipes"),
drag_from: None,
changes: Vec::new(),
font: resources.get_font("roman"),
letters: HashMap::new(),
}
}
pub fn cancel_drag_and_clear_changes(&mut self) {
self.drag_from = None;
self.changes.clear();
}
pub fn cancel_drag_and_undo_changes(&mut self, grid: &mut PlaneGrid) {
self.drag_from = None;
for &(coords1, coords2) in self.changes.iter().rev() {
grid.toggle_pipe(coords1, coords2);
}
self.changes.clear();
}
pub fn add_letter(&mut self, coords: Point, letter: char) {
self.letters.insert(coords, letter);
}
fn rect(&self, grid: &PlaneGrid) -> Rect {
Rect::new(
self.left,
self.top,
grid.num_cols() * TILE_USIZE,
grid.num_rows() * TILE_USIZE,
)
}
fn pt_to_coords(&self, grid: &PlaneGrid, pt: Point) -> Option<Point> {
let col = div_floor(pt.x() - self.left, TILE_ISIZE);
let row = div_floor(pt.y() - self.top, TILE_ISIZE);
let coords = Point::new(col, row);
if grid.contains_coords(coords) {
Some(coords)
} else {
None
}
}
fn draw_pipe_tip(
&self,
grid: &PlaneGrid,
pos: Point,
dir: Direction,
canvas: &mut Canvas,
) {
let obj = grid.objects().get(&pos).cloned();
let sprite_index = match (dir, obj) {
(Direction::West, Some(PlaneObj::Cross)) => 10,
(Direction::West, Some(obj)) if obj.is_node() => 13,
(Direction::West, _) => 0,
(Direction::East, Some(PlaneObj::Cross)) => 11,
(Direction::East, Some(obj)) if obj.is_node() => 15,
(Direction::East, _) => 2,
(Direction::South, Some(obj)) if obj.is_node() => 14,
(Direction::South, _) => 1,
(Direction::North, Some(obj)) if obj.is_node() => 16,
(Direction::North, _) => 3,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, pos * TILE_ISIZE);
}
}
impl Element<PlaneGrid, PlaneCmd> for PlaneGridView {
fn draw(&self, grid: &PlaneGrid, canvas: &mut Canvas) {
let mut canvas = canvas.subcanvas(self.rect(grid));
canvas.clear((64, 64, 64));
for row in 0..(grid.num_rows() as i32) {
for col in 0..(grid.num_cols() as i32) {
let coords = Point::new(col, row);
if let Some(&obj) = grid.objects().get(&coords) {
let sprite_index = match obj {
PlaneObj::Wall => 0,
PlaneObj::Cross => 1,
PlaneObj::PurpleNode => 2,
PlaneObj::RedNode => 3,
PlaneObj::GreenNode => 4,
PlaneObj::BlueNode => 5,
PlaneObj::GrayNode => 6,
};
let sprite = &self.obj_sprites[sprite_index];
canvas.draw_sprite(sprite, coords * TILE_ISIZE);
} else {
let pt = coords * TILE_ISIZE;
let rect = Rect::new(
pt.x() + 1,
pt.y() + 1,
TILE_USIZE - 2,
TILE_USIZE - 2,
);
canvas.draw_rect((72, 72, 72), rect);
}
}
}
for pipe in grid.pipes() {
debug_assert!(pipe.len() >= 2);
let mut start = pipe[0];
let mut next = pipe[1];
let mut dir = Direction::from_delta(next - start);
self.draw_pipe_tip(grid, start, dir, &mut canvas);
for index in 2..pipe.len() {
start = next;
next = pipe[index];
let prev_dir = dir;
dir = Direction::from_delta(next - start);
let sprite_index = match (prev_dir, dir) {
(Direction::East, Direction::North) => 6,
(Direction::East, Direction::South) => 7,
(Direction::West, Direction::North) => 5,
(Direction::West, Direction::South) => 4,
(Direction::East, _) | (Direction::West, _) => {
let obj = grid.objects().get(&start).cloned();
if obj == Some(PlaneObj::Cross) {
12
} else |
}
(Direction::North, Direction::East) => 4,
(Direction::North, Direction::West) => 7,
(Direction::South, Direction::East) => 5,
(Direction::South, Direction::West) => 6,
(Direction::North, _) | (Direction::South, _) => 9,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, start * TILE_ISIZE);
}
dir = Direction::from_delta(start - next);
self.draw_pipe_tip(grid, next, dir, &mut canvas);
}
for (&coords, &letter) in self.letters.iter() {
let pt = Point::new(
coords.x() * TILE_ISIZE + TILE_ISIZE / 2,
coords.y() * TILE_ISIZE + TILE_ISIZE / 2 + 4,
);
canvas.draw_char(&self.font, Align::Center, pt, letter);
}
}
fn handle_event(
&mut self,
event: &Event,
grid: &mut PlaneGrid,
) -> Action<PlaneCmd> {
match event {
&Event::MouseDown(pt) if self.rect(grid).contains_point(pt) => {
self.drag_from = self.pt_to_coords(grid, pt);
Action::ignore().and_stop()
}
&Event::MouseDrag(pt) => {
if let Some(coords1) = self.drag_from {
if let Some(coords2) = self.pt_to_coords(grid, pt) {
self.drag_from = Some(coords2);
if grid.toggle_pipe(coords1, coords2) {
self.changes.push((coords1, coords2));
return Action::redraw()
.and_return(PlaneCmd::Changed);
}
}
}
Action::ignore()
}
&Event::MouseUp => {
self.drag_from = None;
if self.changes.is_empty() {
Action::ignore()
} else {
let vec = mem::replace(&mut self.changes, Vec::new());
Action::redraw().and_return(PlaneCmd::PushUndo(vec))
}
}
_ => Action::ignore(),
}
}
}
// ========================================================================= //
| {
8
} | conditional_block |
plane.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
// | |
// | System Syzygy 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. |
// | |
// | System Syzygy 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 details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use num_integer::div_floor;
use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use crate::gui::{
Action, Align, Canvas, Element, Event, Font, Point, Rect, Resources,
Sprite,
};
use crate::save::plane::{PlaneGrid, PlaneObj};
use crate::save::Direction;
// ========================================================================= //
pub enum PlaneCmd {
Changed,
PushUndo(Vec<(Point, Point)>),
}
// ========================================================================= //
const TILE_USIZE: u32 = 24;
const TILE_ISIZE: i32 = TILE_USIZE as i32;
pub struct PlaneGridView {
left: i32,
top: i32,
obj_sprites: Vec<Sprite>,
pipe_sprites: Vec<Sprite>,
drag_from: Option<Point>,
changes: Vec<(Point, Point)>,
font: Rc<Font>,
letters: HashMap<Point, char>,
}
impl PlaneGridView {
pub fn new(
resources: &mut Resources,
left: i32,
top: i32,
) -> PlaneGridView |
pub fn cancel_drag_and_clear_changes(&mut self) {
self.drag_from = None;
self.changes.clear();
}
pub fn cancel_drag_and_undo_changes(&mut self, grid: &mut PlaneGrid) {
self.drag_from = None;
for &(coords1, coords2) in self.changes.iter().rev() {
grid.toggle_pipe(coords1, coords2);
}
self.changes.clear();
}
pub fn add_letter(&mut self, coords: Point, letter: char) {
self.letters.insert(coords, letter);
}
fn rect(&self, grid: &PlaneGrid) -> Rect {
Rect::new(
self.left,
self.top,
grid.num_cols() * TILE_USIZE,
grid.num_rows() * TILE_USIZE,
)
}
fn pt_to_coords(&self, grid: &PlaneGrid, pt: Point) -> Option<Point> {
let col = div_floor(pt.x() - self.left, TILE_ISIZE);
let row = div_floor(pt.y() - self.top, TILE_ISIZE);
let coords = Point::new(col, row);
if grid.contains_coords(coords) {
Some(coords)
} else {
None
}
}
fn draw_pipe_tip(
&self,
grid: &PlaneGrid,
pos: Point,
dir: Direction,
canvas: &mut Canvas,
) {
let obj = grid.objects().get(&pos).cloned();
let sprite_index = match (dir, obj) {
(Direction::West, Some(PlaneObj::Cross)) => 10,
(Direction::West, Some(obj)) if obj.is_node() => 13,
(Direction::West, _) => 0,
(Direction::East, Some(PlaneObj::Cross)) => 11,
(Direction::East, Some(obj)) if obj.is_node() => 15,
(Direction::East, _) => 2,
(Direction::South, Some(obj)) if obj.is_node() => 14,
(Direction::South, _) => 1,
(Direction::North, Some(obj)) if obj.is_node() => 16,
(Direction::North, _) => 3,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, pos * TILE_ISIZE);
}
}
impl Element<PlaneGrid, PlaneCmd> for PlaneGridView {
fn draw(&self, grid: &PlaneGrid, canvas: &mut Canvas) {
let mut canvas = canvas.subcanvas(self.rect(grid));
canvas.clear((64, 64, 64));
for row in 0..(grid.num_rows() as i32) {
for col in 0..(grid.num_cols() as i32) {
let coords = Point::new(col, row);
if let Some(&obj) = grid.objects().get(&coords) {
let sprite_index = match obj {
PlaneObj::Wall => 0,
PlaneObj::Cross => 1,
PlaneObj::PurpleNode => 2,
PlaneObj::RedNode => 3,
PlaneObj::GreenNode => 4,
PlaneObj::BlueNode => 5,
PlaneObj::GrayNode => 6,
};
let sprite = &self.obj_sprites[sprite_index];
canvas.draw_sprite(sprite, coords * TILE_ISIZE);
} else {
let pt = coords * TILE_ISIZE;
let rect = Rect::new(
pt.x() + 1,
pt.y() + 1,
TILE_USIZE - 2,
TILE_USIZE - 2,
);
canvas.draw_rect((72, 72, 72), rect);
}
}
}
for pipe in grid.pipes() {
debug_assert!(pipe.len() >= 2);
let mut start = pipe[0];
let mut next = pipe[1];
let mut dir = Direction::from_delta(next - start);
self.draw_pipe_tip(grid, start, dir, &mut canvas);
for index in 2..pipe.len() {
start = next;
next = pipe[index];
let prev_dir = dir;
dir = Direction::from_delta(next - start);
let sprite_index = match (prev_dir, dir) {
(Direction::East, Direction::North) => 6,
(Direction::East, Direction::South) => 7,
(Direction::West, Direction::North) => 5,
(Direction::West, Direction::South) => 4,
(Direction::East, _) | (Direction::West, _) => {
let obj = grid.objects().get(&start).cloned();
if obj == Some(PlaneObj::Cross) {
12
} else {
8
}
}
(Direction::North, Direction::East) => 4,
(Direction::North, Direction::West) => 7,
(Direction::South, Direction::East) => 5,
(Direction::South, Direction::West) => 6,
(Direction::North, _) | (Direction::South, _) => 9,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, start * TILE_ISIZE);
}
dir = Direction::from_delta(start - next);
self.draw_pipe_tip(grid, next, dir, &mut canvas);
}
for (&coords, &letter) in self.letters.iter() {
let pt = Point::new(
coords.x() * TILE_ISIZE + TILE_ISIZE / 2,
coords.y() * TILE_ISIZE + TILE_ISIZE / 2 + 4,
);
canvas.draw_char(&self.font, Align::Center, pt, letter);
}
}
fn handle_event(
&mut self,
event: &Event,
grid: &mut PlaneGrid,
) -> Action<PlaneCmd> {
match event {
&Event::MouseDown(pt) if self.rect(grid).contains_point(pt) => {
self.drag_from = self.pt_to_coords(grid, pt);
Action::ignore().and_stop()
}
&Event::MouseDrag(pt) => {
if let Some(coords1) = self.drag_from {
if let Some(coords2) = self.pt_to_coords(grid, pt) {
self.drag_from = Some(coords2);
if grid.toggle_pipe(coords1, coords2) {
self.changes.push((coords1, coords2));
return Action::redraw()
.and_return(PlaneCmd::Changed);
}
}
}
Action::ignore()
}
&Event::MouseUp => {
self.drag_from = None;
if self.changes.is_empty() {
Action::ignore()
} else {
let vec = mem::replace(&mut self.changes, Vec::new());
Action::redraw().and_return(PlaneCmd::PushUndo(vec))
}
}
_ => Action::ignore(),
}
}
}
// ========================================================================= //
| {
PlaneGridView {
left,
top,
obj_sprites: resources.get_sprites("plane/objects"),
pipe_sprites: resources.get_sprites("plane/pipes"),
drag_from: None,
changes: Vec::new(),
font: resources.get_font("roman"),
letters: HashMap::new(),
}
} | identifier_body |
plane.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
// | |
// | System Syzygy 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. |
// | |
// | System Syzygy 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 details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use num_integer::div_floor;
use std::collections::HashMap;
use std::mem;
use std::rc::Rc;
use crate::gui::{
Action, Align, Canvas, Element, Event, Font, Point, Rect, Resources,
Sprite,
};
use crate::save::plane::{PlaneGrid, PlaneObj};
use crate::save::Direction;
// ========================================================================= //
pub enum PlaneCmd {
Changed,
PushUndo(Vec<(Point, Point)>),
}
// ========================================================================= //
const TILE_USIZE: u32 = 24;
const TILE_ISIZE: i32 = TILE_USIZE as i32;
pub struct PlaneGridView {
left: i32,
top: i32,
obj_sprites: Vec<Sprite>,
pipe_sprites: Vec<Sprite>,
drag_from: Option<Point>,
changes: Vec<(Point, Point)>,
font: Rc<Font>,
letters: HashMap<Point, char>,
}
impl PlaneGridView {
pub fn new(
resources: &mut Resources,
left: i32,
top: i32,
) -> PlaneGridView {
PlaneGridView {
left,
top,
obj_sprites: resources.get_sprites("plane/objects"),
pipe_sprites: resources.get_sprites("plane/pipes"),
drag_from: None,
changes: Vec::new(),
font: resources.get_font("roman"),
letters: HashMap::new(),
}
}
pub fn cancel_drag_and_clear_changes(&mut self) {
self.drag_from = None;
self.changes.clear();
}
pub fn cancel_drag_and_undo_changes(&mut self, grid: &mut PlaneGrid) {
self.drag_from = None;
for &(coords1, coords2) in self.changes.iter().rev() {
grid.toggle_pipe(coords1, coords2);
}
self.changes.clear();
}
pub fn add_letter(&mut self, coords: Point, letter: char) {
self.letters.insert(coords, letter);
}
fn rect(&self, grid: &PlaneGrid) -> Rect {
Rect::new(
self.left,
self.top,
grid.num_cols() * TILE_USIZE,
grid.num_rows() * TILE_USIZE,
)
}
fn pt_to_coords(&self, grid: &PlaneGrid, pt: Point) -> Option<Point> {
let col = div_floor(pt.x() - self.left, TILE_ISIZE);
let row = div_floor(pt.y() - self.top, TILE_ISIZE);
let coords = Point::new(col, row);
if grid.contains_coords(coords) {
Some(coords)
} else {
None
}
}
fn draw_pipe_tip(
&self,
grid: &PlaneGrid,
pos: Point,
dir: Direction,
canvas: &mut Canvas,
) {
let obj = grid.objects().get(&pos).cloned();
let sprite_index = match (dir, obj) {
(Direction::West, Some(PlaneObj::Cross)) => 10,
(Direction::West, Some(obj)) if obj.is_node() => 13,
(Direction::West, _) => 0,
(Direction::East, Some(PlaneObj::Cross)) => 11,
(Direction::East, Some(obj)) if obj.is_node() => 15,
(Direction::East, _) => 2,
(Direction::South, Some(obj)) if obj.is_node() => 14,
(Direction::South, _) => 1,
(Direction::North, Some(obj)) if obj.is_node() => 16,
(Direction::North, _) => 3,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, pos * TILE_ISIZE);
}
}
impl Element<PlaneGrid, PlaneCmd> for PlaneGridView {
fn draw(&self, grid: &PlaneGrid, canvas: &mut Canvas) {
let mut canvas = canvas.subcanvas(self.rect(grid));
canvas.clear((64, 64, 64));
for row in 0..(grid.num_rows() as i32) {
for col in 0..(grid.num_cols() as i32) {
let coords = Point::new(col, row);
if let Some(&obj) = grid.objects().get(&coords) {
let sprite_index = match obj {
PlaneObj::Wall => 0,
PlaneObj::Cross => 1,
PlaneObj::PurpleNode => 2,
PlaneObj::RedNode => 3,
PlaneObj::GreenNode => 4,
PlaneObj::BlueNode => 5,
PlaneObj::GrayNode => 6,
};
let sprite = &self.obj_sprites[sprite_index];
canvas.draw_sprite(sprite, coords * TILE_ISIZE);
} else {
let pt = coords * TILE_ISIZE;
let rect = Rect::new(
pt.x() + 1,
pt.y() + 1,
TILE_USIZE - 2,
TILE_USIZE - 2,
);
canvas.draw_rect((72, 72, 72), rect);
}
}
}
for pipe in grid.pipes() {
debug_assert!(pipe.len() >= 2);
let mut start = pipe[0];
let mut next = pipe[1];
let mut dir = Direction::from_delta(next - start);
self.draw_pipe_tip(grid, start, dir, &mut canvas);
for index in 2..pipe.len() {
start = next;
next = pipe[index];
let prev_dir = dir;
dir = Direction::from_delta(next - start);
let sprite_index = match (prev_dir, dir) {
(Direction::East, Direction::North) => 6,
(Direction::East, Direction::South) => 7,
(Direction::West, Direction::North) => 5,
(Direction::West, Direction::South) => 4,
(Direction::East, _) | (Direction::West, _) => {
let obj = grid.objects().get(&start).cloned();
if obj == Some(PlaneObj::Cross) {
12
} else {
8
}
}
(Direction::North, Direction::East) => 4, | (Direction::North, Direction::West) => 7,
(Direction::South, Direction::East) => 5,
(Direction::South, Direction::West) => 6,
(Direction::North, _) | (Direction::South, _) => 9,
};
let sprite = &self.pipe_sprites[sprite_index];
canvas.draw_sprite(sprite, start * TILE_ISIZE);
}
dir = Direction::from_delta(start - next);
self.draw_pipe_tip(grid, next, dir, &mut canvas);
}
for (&coords, &letter) in self.letters.iter() {
let pt = Point::new(
coords.x() * TILE_ISIZE + TILE_ISIZE / 2,
coords.y() * TILE_ISIZE + TILE_ISIZE / 2 + 4,
);
canvas.draw_char(&self.font, Align::Center, pt, letter);
}
}
fn handle_event(
&mut self,
event: &Event,
grid: &mut PlaneGrid,
) -> Action<PlaneCmd> {
match event {
&Event::MouseDown(pt) if self.rect(grid).contains_point(pt) => {
self.drag_from = self.pt_to_coords(grid, pt);
Action::ignore().and_stop()
}
&Event::MouseDrag(pt) => {
if let Some(coords1) = self.drag_from {
if let Some(coords2) = self.pt_to_coords(grid, pt) {
self.drag_from = Some(coords2);
if grid.toggle_pipe(coords1, coords2) {
self.changes.push((coords1, coords2));
return Action::redraw()
.and_return(PlaneCmd::Changed);
}
}
}
Action::ignore()
}
&Event::MouseUp => {
self.drag_from = None;
if self.changes.is_empty() {
Action::ignore()
} else {
let vec = mem::replace(&mut self.changes, Vec::new());
Action::redraw().and_return(PlaneCmd::PushUndo(vec))
}
}
_ => Action::ignore(),
}
}
}
// ========================================================================= // | random_line_split | |
JobSubmit.py | #!/usr/bin/env ganga
import getpass
from distutils.util import strtobool
polarity='MagDown'
datatype='MC'
substitution='None'
channel='11164031'
b=Job()
b.application=DaVinci(version="v36r5")
if datatype=='MC':
b.application.optsfile='NTupleMaker_{0}.py'.format(polarity)
if datatype=='Data':
if substitution=='None':
b.application.optsfile='DNTupleMaker.py'
if substitution=='PimforKm':
|
b.outputfiles=[DiracFile('Output.root')]
b.inputdata = b.application.readInputData('{0}_12_{1}_{2}.py'.format(datatype,channel,polarity))
if substitution=='None':
b.comment='{0}_12_{1}_{2}'.format(datatype,polarity,channel)
if substitution=='PimforKm':
b.comment='{0}_12_{1}_{2}_{3}'.format(datatype,polarity,channel,substitution)
if datatype=='Data':
b.splitter = SplitByFiles(filesPerJob=10)
if datatype=='MC':
b.splitter = SplitByFiles(filesPerJob=2)
#b.OutputSandbox=["stderr","stdout"]
b.backend=Dirac()
#b.submit()
queues.add(b.submit)
polarity='MagUp'
b2=Job()
b2.application=DaVinci(version="v36r5")
if datatype=='MC':
b2.application.optsfile='NTupleMaker_{0}.py'.format(polarity)
if datatype=='Data':
if substitution=='None':
b2.application.optsfile='DNTupleMaker.py'
if substitution=='PimforKm':
b2.application.optsfile='DNTupleMaker_PimforKm.py'
b2.outputfiles=[DiracFile('Output.root')]
b2.inputdata = b2.application.readInputData('{0}_12_{1}_{2}.py'.format(datatype,channel,polarity))
if substitution=='None':
b2.comment='{0}_12_{1}_{2}'.format(datatype,polarity,channel)
if substitution=='PimforKm':
b2.comment='{0}_12_{1}_{2}_{3}'.format(datatype,polarity,channel,substitution)
if datatype=='Data':
b2.splitter = SplitByFiles(filesPerJob=10)
if datatype=='MC':
b2.splitter = SplitByFiles(filesPerJob=2)
#b.OutputSandbox=["stderr","stdout"]
b2.backend=Dirac()
#b.submit()
queues.add(b2.submit)
| b.application.optsfile='DNTupleMaker_PimforKm.py' | conditional_block |
JobSubmit.py | #!/usr/bin/env ganga
import getpass
from distutils.util import strtobool
polarity='MagDown'
datatype='MC'
substitution='None'
channel='11164031'
b=Job()
b.application=DaVinci(version="v36r5")
if datatype=='MC':
b.application.optsfile='NTupleMaker_{0}.py'.format(polarity)
if datatype=='Data':
if substitution=='None':
b.application.optsfile='DNTupleMaker.py'
if substitution=='PimforKm':
b.application.optsfile='DNTupleMaker_PimforKm.py'
b.outputfiles=[DiracFile('Output.root')]
b.inputdata = b.application.readInputData('{0}_12_{1}_{2}.py'.format(datatype,channel,polarity))
if substitution=='None':
b.comment='{0}_12_{1}_{2}'.format(datatype,polarity,channel)
if substitution=='PimforKm':
b.comment='{0}_12_{1}_{2}_{3}'.format(datatype,polarity,channel,substitution)
if datatype=='Data':
b.splitter = SplitByFiles(filesPerJob=10)
if datatype=='MC':
b.splitter = SplitByFiles(filesPerJob=2)
#b.OutputSandbox=["stderr","stdout"]
b.backend=Dirac()
#b.submit()
queues.add(b.submit)
polarity='MagUp'
b2=Job()
b2.application=DaVinci(version="v36r5") | if datatype=='MC':
b2.application.optsfile='NTupleMaker_{0}.py'.format(polarity)
if datatype=='Data':
if substitution=='None':
b2.application.optsfile='DNTupleMaker.py'
if substitution=='PimforKm':
b2.application.optsfile='DNTupleMaker_PimforKm.py'
b2.outputfiles=[DiracFile('Output.root')]
b2.inputdata = b2.application.readInputData('{0}_12_{1}_{2}.py'.format(datatype,channel,polarity))
if substitution=='None':
b2.comment='{0}_12_{1}_{2}'.format(datatype,polarity,channel)
if substitution=='PimforKm':
b2.comment='{0}_12_{1}_{2}_{3}'.format(datatype,polarity,channel,substitution)
if datatype=='Data':
b2.splitter = SplitByFiles(filesPerJob=10)
if datatype=='MC':
b2.splitter = SplitByFiles(filesPerJob=2)
#b.OutputSandbox=["stderr","stdout"]
b2.backend=Dirac()
#b.submit()
queues.add(b2.submit) | random_line_split | |
test-trac-0218.py | # -*- coding: utf-8 -*-
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import pyxb.binding.generate
import pyxb.utils.domutils
from xml.dom import Node
import os.path
xst = '''<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="topLevel">
<xs:complexType>
<xs:sequence>
<xs:element name="item" type="xs:int" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
'''
code = pyxb.binding.generate.GeneratePython(schema_text=xst)
#print code
rv = compile(code, 'test', 'exec')
eval(rv)
from pyxb.exceptions_ import *
import unittest
class TestTrac0218 (unittest.TestCase):
def | (self):
instance = topLevel()
self.assertTrue(instance.item is not None)
self.assertFalse(instance.item is None)
self.assertTrue(instance.item != None)
self.assertTrue(None != instance.item)
self.assertFalse(instance.item)
instance.item.extend([1,2,3,4])
self.assertTrue(instance.item is not None)
self.assertFalse(instance.item is None)
self.assertTrue(instance.item != None)
self.assertTrue(None != instance.item)
self.assertTrue(instance.item)
if __name__ == '__main__':
unittest.main()
| testBasic | identifier_name |
test-trac-0218.py | # -*- coding: utf-8 -*-
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import pyxb.binding.generate
import pyxb.utils.domutils
from xml.dom import Node
import os.path
xst = '''<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="topLevel">
<xs:complexType>
<xs:sequence>
<xs:element name="item" type="xs:int" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
'''
code = pyxb.binding.generate.GeneratePython(schema_text=xst)
#print code
rv = compile(code, 'test', 'exec')
eval(rv)
from pyxb.exceptions_ import *
import unittest
class TestTrac0218 (unittest.TestCase):
|
if __name__ == '__main__':
unittest.main()
| def testBasic (self):
instance = topLevel()
self.assertTrue(instance.item is not None)
self.assertFalse(instance.item is None)
self.assertTrue(instance.item != None)
self.assertTrue(None != instance.item)
self.assertFalse(instance.item)
instance.item.extend([1,2,3,4])
self.assertTrue(instance.item is not None)
self.assertFalse(instance.item is None)
self.assertTrue(instance.item != None)
self.assertTrue(None != instance.item)
self.assertTrue(instance.item) | identifier_body |
test-trac-0218.py | # -*- coding: utf-8 -*-
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import pyxb.binding.generate
import pyxb.utils.domutils
from xml.dom import Node
import os.path
xst = '''<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="topLevel">
<xs:complexType>
<xs:sequence>
<xs:element name="item" type="xs:int" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
'''
code = pyxb.binding.generate.GeneratePython(schema_text=xst)
#print code
rv = compile(code, 'test', 'exec')
eval(rv)
from pyxb.exceptions_ import *
| instance = topLevel()
self.assertTrue(instance.item is not None)
self.assertFalse(instance.item is None)
self.assertTrue(instance.item != None)
self.assertTrue(None != instance.item)
self.assertFalse(instance.item)
instance.item.extend([1,2,3,4])
self.assertTrue(instance.item is not None)
self.assertFalse(instance.item is None)
self.assertTrue(instance.item != None)
self.assertTrue(None != instance.item)
self.assertTrue(instance.item)
if __name__ == '__main__':
unittest.main() | import unittest
class TestTrac0218 (unittest.TestCase):
def testBasic (self): | random_line_split |
test-trac-0218.py | # -*- coding: utf-8 -*-
import logging
if __name__ == '__main__':
|
_log = logging.getLogger(__name__)
import pyxb.binding.generate
import pyxb.utils.domutils
from xml.dom import Node
import os.path
xst = '''<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="topLevel">
<xs:complexType>
<xs:sequence>
<xs:element name="item" type="xs:int" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
'''
code = pyxb.binding.generate.GeneratePython(schema_text=xst)
#print code
rv = compile(code, 'test', 'exec')
eval(rv)
from pyxb.exceptions_ import *
import unittest
class TestTrac0218 (unittest.TestCase):
def testBasic (self):
instance = topLevel()
self.assertTrue(instance.item is not None)
self.assertFalse(instance.item is None)
self.assertTrue(instance.item != None)
self.assertTrue(None != instance.item)
self.assertFalse(instance.item)
instance.item.extend([1,2,3,4])
self.assertTrue(instance.item is not None)
self.assertFalse(instance.item is None)
self.assertTrue(instance.item != None)
self.assertTrue(None != instance.item)
self.assertTrue(instance.item)
if __name__ == '__main__':
unittest.main()
| logging.basicConfig() | conditional_block |
interfaces.ts | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A generic decoded JWT from the microapps API.
* Note that this is not exhaustive and only needed fields are typed.
*/
export interface DecodedToken {
exp: number; // The time the token expires, represented in Unix time (integer seconds)
}
/**
* A decoded Phone Number Token from the microapps API.
* Note that this is not exhaustive and only needed fields are typed.
* For the exhaustive list,
* refer to: https://developers.google.com/pay/spot/eap/reference/phonenumber-api
*/
export interface DecodedPhoneNumberToken extends DecodedToken {
// contactNumber format is E.123 international notation
// Note that the national phone number portion will only contain digits (no spaces)
// Eg: +91 1234567890
phone_number: string;
}
/**
* A decoded Identity Token from the microapps API.
* Note that this is not exhaustive and only needed fields are typed.
* For the exhaustive list,
* refer to: https://developers.google.com/pay/spot/eap/reference/identity-api
*/
export interface DecodedIdentityToken extends DecodedToken {
sub: string; // Unique identifier for a user in GPay
name: string;
}
/**
* CustomerIdentity object that contains the customer identity token and its decoded form.
*/
export interface CustomerIdentity {
idToken: string;
decodedToken: DecodedIdentityToken;
}
/**
* NonEmptyArray type enforces at least 1 element of type T in the array.
*/
export type NonEmptyArray<T> = [T, ...T[]];
export interface Image {
url: string;
alt?: string;
}
/**
* FontSize type that provides several preset options for a font size.
*/
type FontSize = 'small' | 'medium' | 'large';
/**
* CommitProgressFontSize type that provides several preset options for the font
* size of CommitProgress. It allows 3 values: 'small', 'medium' and 'large';
*/
export type CommitProgressFontSize = FontSize;
/**
* DeadlineFontSize type that provides several preset options for the font size
* of DeadlineTag. It allows 2 values: 'small' and 'medium';
*/
export type DeadlineFontSize = Omit<FontSize, 'large'>;
/**
* PriceFontSize type that provides several preset options for the font size of
* ListingPrice. It allows 2 values: 'medium' and 'large';
*/
export type PriceFontSize = Omit<FontSize, 'small'>;
/**
* FulfilmentDetails Interface that contains the fields of a fulfilment.
*/
export interface FulfilmentDetails {
name: string;
address: string;
// contactNumber format is E.123 international notation
// Note that the national phone number portion will only contain digits (no spaces)
// Eg: +91 1234567890
contactNumber: string;
}
/**
* Money Interface that represents an amount of money with its currency type.
* Value = dollars + (cents / 100)
*/
export interface Money {
currency: string; // The 3-letter currency code defined in ISO 4217
dollars: number;
cents: number; // A value of the range 0~99
}
/**
* ListingStatus type contains the different states of a Listing.
*/
export type ListingStatus =
| 'ongoing'
| 'successful'
| 'completed'
| 'unsuccessful';
/**
* Interface that contains the fields of Listing that are provided by the user through
* the Add Listing Form.
*/
export interface AddListingFormData {
name: string;
currency: string; // The 3-letter currency code defined in ISO 4217
price: number;
oldPrice: number;
imgUrl: string;
description: string;
deadline: string; // RFC 3339 string
minCommits: number;
}
/**
* ListingPayload Interface that contains the fields of the payload that
* would be sent to the server.
*/
export interface ListingPayload {
merchantId: number;
name: string;
price: Money;
oldPrice: Money;
imgUrl: string;
description: string;
deadline: string; // RFC 3339 string
minCommits: number;
}
/**
* Listing Interface that contains the fields of a Listing,
*/
export interface Listing extends ListingPayload {
id: number;
numCommits: number;
numPaid: number;
numCompleted: number;
listingStatus: ListingStatus;
}
/**
* ListingQueryParams Interface that contains the possible query parameters
* for Listings.
*/
export interface ListingQueryParams extends Listing {
ids: string;
}
/**
* ListingQuery Interface that contains the fields of the query that
* would be sent to the server to query for listings.
*/
export type ListingQuery = Partial<ListingQueryParams>;
/**
* CommitStatus type contains the different states of a Commit.
*/
export type CommitStatus =
| 'ongoing'
| 'successful'
| 'paid'
| 'completed'
| 'unsuccessful';
/**
* CommitPayload Interface that contains the fields of the payload that
* would be sent to the server to create commits.
*/
export interface CommitPayload {
customerId: number;
listingId: number;
}
/**
* CommitPaymentPayload Interface that contains the fields of the payload that
* would be sent to the server to pay for commits.
*/
export interface CommitPaymentPayload {
fulfilmentDetails: FulfilmentDetails;
}
/** | */
export type CommitQuery = Partial<
Pick<Commit, 'customerId' | 'listingId' | 'commitStatus'>
>;
/**
* Commit Interface that contains the fields of a Commit.
*/
export interface Commit extends CommitPayload, CommitPaymentPayload {
id: number;
createdAt: Date;
commitStatus: CommitStatus;
}
/**
* GroupedCommits type of commits grouped by their commit status.
*/
export type GroupedCommits = {
[key in CommitStatus]?: Commit[];
};
/**
* CustomerPayload Interface that contains the fields of the payload that
* would be sent to the server.
*/
export interface CustomerPayload {
gpayId: string;
defaultFulfilmentDetails?: FulfilmentDetails;
// gpayContactNumber format is E.123 international notation
// Note that the national phone number portion will only contain digits (no spaces)
// Eg: +91 1234567890
gpayContactNumber: string;
}
/**
* Customer Interface that contains the fields of a Customer.
*/
export interface Customer extends Required<CustomerPayload> {
id: number;
numUsedCommits: number;
}
/**
* MerchantPayload Interface that contains the fields of the payload that
* would be sent to the server to add the merchant to the database.
*/
export interface MerchantPayload {
name: string;
email: string;
vpa: string;
firebaseUid: string;
}
/**
* MerchantResponse Interface that contains the fields of the merchant object that
* client side would receive after sending an API request to /merchants endpoint.
*/
export interface MerchantResponse extends MerchantPayload {
id: number;
} | * CommitQuery Interface that contains the fields of the query that
* would be sent to the server to query for commits. | random_line_split |
livecd.py | #
# livecd.py: An anaconda backend to do an install from a live CD image
#
# The basic idea is that with a live CD, we already have an install
# and should be able to just copy those bits over to the disk. So we dd
# the image, move things to the "right" filesystem as needed, and then
# resize the rootfs to the size of its container.
#
# Copyright (C) 2007 Red Hat, Inc. All rights reserved.
#
# 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, see <http://www.gnu.org/licenses/>.
#
# Author(s): Jeremy Katz <katzj@redhat.com>
#
import os, sys
import stat
import shutil
import time
import subprocess
import storage
import selinux
from flags import flags
from constants import *
import gettext
_ = lambda x: gettext.ldgettext("anaconda", x)
import backend
import isys
import iutil
import packages
import logging
log = logging.getLogger("anaconda")
class Error(EnvironmentError):
pass
def copytree(src, dst, symlinks=False, preserveOwner=False,
preserveSelinux=False):
def tryChown(src, dest):
try:
os.chown(dest, os.stat(src)[stat.ST_UID], os.stat(src)[stat.ST_GID])
except OverflowError:
log.error("Could not set owner and group on file %s" % dest)
def trySetfilecon(src, dest):
try:
selinux.lsetfilecon(dest, selinux.lgetfilecon(src)[1])
except:
log.error("Could not set selinux context on file %s" % dest)
# copy of shutil.copytree which doesn't require dst to not exist
# and which also has options to preserve the owner and selinux contexts
names = os.listdir(src)
if not os.path.isdir(dst):
os.makedirs(dst)
errors = []
for name in names:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
if preserveSelinux:
trySetfilecon(srcname, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, preserveOwner, preserveSelinux)
else:
shutil.copyfile(srcname, dstname)
if preserveOwner:
tryChown(srcname, dstname)
if preserveSelinux:
trySetfilecon(srcname, dstname)
shutil.copystat(srcname, dstname)
except (IOError, os.error), why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error, err:
errors.extend(err.args[0])
try:
if preserveOwner:
tryChown(src, dst)
if preserveSelinux:
trySetfilecon(src, dst)
shutil.copystat(src, dst)
except OSError as e:
errors.extend((src, dst, e.strerror))
if errors:
raise Error, errors
class LiveCDCopyBackend(backend.AnacondaBackend):
def __init__(self, anaconda):
backend.AnacondaBackend.__init__(self, anaconda)
flags.livecdInstall = True
self.supportsUpgrades = False
self.supportsPackageSelection = False
self.skipFormatRoot = True
self.osimg = anaconda.methodstr[8:]
if not stat.S_ISBLK(os.stat(self.osimg)[stat.ST_MODE]):
anaconda.intf.messageWindow(_("Unable to find image"),
_("The given location isn't a valid %s "
"live CD to use as an installation source.")
%(productName,), type = "custom",
custom_icon="error",
custom_buttons=[_("Exit installer")])
sys.exit(0)
self.rootFsType = isys.readFSType(self.osimg)
def _getLiveBlockDevice(self):
return os.path.normpath(self.osimg)
def _getLiveSize(self):
def parseField(output, field):
for line in output.split("\n"):
if line.startswith(field + ":"):
return line[len(field) + 1:].strip()
raise KeyError("Failed to find field '%s' in output" % field)
output = subprocess.Popen(['/sbin/dumpe2fs', '-h', self.osimg],
stdout=subprocess.PIPE,
stderr=open('/dev/null', 'w')
).communicate()[0]
blkcnt = int(parseField(output, "Block count"))
blksize = int(parseField(output, "Block size"))
return blkcnt * blksize
def _getLiveSizeMB(self):
return self._getLiveSize() / 1048576
def _unmountNonFstabDirs(self, anaconda):
# unmount things that aren't listed in /etc/fstab. *sigh*
dirs = []
if flags.selinux:
dirs.append("/selinux")
for dir in dirs:
try:
isys.umount("%s/%s" %(anaconda.rootPath,dir), removeDir = False)
except Exception, e:
log.error("unable to unmount %s: %s" %(dir, e))
def postAction(self, anaconda):
self._unmountNonFstabDirs(anaconda)
try:
anaconda.id.storage.umountFilesystems(swapoff = False)
os.rmdir(anaconda.rootPath)
except Exception, e:
log.error("Unable to unmount filesystems: %s" % e)
def doPreInstall(self, anaconda):
if anaconda.dir == DISPATCH_BACK:
self._unmountNonFstabDirs(anaconda)
return
anaconda.id.storage.umountFilesystems(swapoff = False)
def doInstall(self, anaconda):
log.info("Preparing to install packages")
progress = anaconda.id.instProgress
progress.set_label(_("Copying live image to hard drive."))
progress.processEvents()
osimg = self._getLiveBlockDevice() # the real image
osfd = os.open(osimg, os.O_RDONLY)
rootDevice = anaconda.id.storage.rootDevice
rootDevice.setup()
rootfd = os.open(rootDevice.path, os.O_WRONLY)
readamt = 1024 * 1024 * 8 # 8 megs at a time
size = self._getLiveSize()
copied = 0
while copied < size:
try:
buf = os.read(osfd, readamt)
written = os.write(rootfd, buf)
except:
rc = anaconda.intf.messageWindow(_("Error"),
_("There was an error installing the live image to "
"your hard drive. This could be due to bad media. "
"Please verify your installation media.\n\nIf you "
"exit, your system will be left in an inconsistent "
"state that will require reinstallation."),
type="custom", custom_icon="error",
custom_buttons=[_("_Exit installer"), _("_Retry")])
if rc == 0:
sys.exit(0)
else:
os.lseek(osfd, 0, 0)
os.lseek(rootfd, 0, 0)
copied = 0
continue
if (written < readamt) and (written < len(buf)):
raise RuntimeError, "error copying filesystem!"
copied += written
progress.set_fraction(pct = copied / float(size))
progress.processEvents()
os.close(osfd)
os.close(rootfd)
anaconda.id.instProgress = None
def _doFilesystemMangling(self, anaconda):
log.info("doing post-install fs mangling")
wait = anaconda.intf.waitWindow(_("Post-Installation"),
_("Performing post-installation filesystem changes. This may take several minutes."))
# resize rootfs first, since it is 100% full due to genMinInstDelta
self._resizeRootfs(anaconda, wait)
# remount filesystems
anaconda.id.storage.mountFilesystems()
# restore the label of / to what we think it is
rootDevice = anaconda.id.storage.rootDevice
rootDevice.setup()
# ensure we have a random UUID on the rootfs
# FIXME: this should be abstracted per filesystem type
iutil.execWithRedirect("tune2fs",
["-U",
"random",
rootDevice.path],
stdout="/dev/tty5",
stderr="/dev/tty5")
# and now set the uuid in the storage layer
rootDevice.updateSysfsPath()
iutil.notify_kernel("/sys%s" %rootDevice.sysfsPath)
storage.udev.udev_settle()
rootDevice.updateSysfsPath()
info = storage.udev.udev_get_block_device(rootDevice.sysfsPath)
rootDevice.format.uuid = storage.udev.udev_device_get_uuid(info)
log.info("reset the rootdev (%s) to have a uuid of %s" %(rootDevice.sysfsPath, rootDevice.format.uuid))
# for any filesystem that's _not_ on the root, we need to handle
# moving the bits from the livecd -> the real filesystems.
# this is pretty distasteful, but should work with things like
# having a separate /usr/local
def _setupFilesystems(mounts, chroot="", teardown=False):
""" Setup or teardown all filesystems except for "/" """
mountpoints = sorted(mounts.keys(),
reverse=teardown is True)
if teardown:
method = "teardown"
kwargs = {}
else:
method = "setup"
kwargs = {"chroot": chroot}
mountpoints.remove("/")
for mountpoint in mountpoints:
device = mounts[mountpoint]
getattr(device.format, method)(**kwargs)
# Start by sorting the mountpoints in decreasing-depth order.
mountpoints = sorted(anaconda.id.storage.mountpoints.keys(),
reverse=True)
# We don't want to copy the root filesystem.
mountpoints.remove("/")
stats = {} # mountpoint: posix.stat_result
# unmount the filesystems, except for /
_setupFilesystems(anaconda.id.storage.mountpoints, teardown=True)
# mount all of the filesystems under /mnt so we can copy in content
_setupFilesystems(anaconda.id.storage.mountpoints,
chroot=anaconda.rootPath + "/mnt")
# And now let's do the real copies
for tocopy in mountpoints:
device = anaconda.id.storage.mountpoints[tocopy]
# FIXME: all calls to wait.refresh() are kind of a hack... we
# should do better about not doing blocking things in the
# main thread. but threading anaconda is a job for another
# time.
wait.refresh()
if not os.path.exists("%s/%s" % (anaconda.rootPath, tocopy)):
# the directory does not exist in the live image, so there's
# nothing to move
continue
copytree("%s/%s" % (anaconda.rootPath, tocopy),
"%s/mnt/%s" % (anaconda.rootPath, tocopy),
True, True, flags.selinux)
wait.refresh()
shutil.rmtree("%s/%s" % (anaconda.rootPath, tocopy))
wait.refresh()
# now unmount each fs, collect stat info for the mountpoint, then
# remove the entire tree containing the mountpoint
for tocopy in mountpoints:
device = anaconda.id.storage.mountpoints[tocopy]
device.format.teardown()
if not os.path.exists("%s/%s" % (anaconda.rootPath, tocopy)):
continue
try:
stats[tocopy]= os.stat("%s/mnt/%s" % (anaconda.rootPath,
tocopy))
except Exception as e:
log.info("failed to get stat info for mountpoint %s: %s"
% (tocopy, e))
shutil.rmtree("%s/mnt/%s" % (anaconda.rootPath,
tocopy.split("/")[1]))
wait.refresh()
# now mount all of the filesystems so that post-install writes end
# up where they're supposed to end up
_setupFilesystems(anaconda.id.storage.mountpoints,
chroot=anaconda.rootPath)
# restore stat info for each mountpoint
for mountpoint in reversed(mountpoints):
if mountpoint not in stats:
# there's no info to restore since the mountpoint did not
# exist in the live image
continue
dest = "%s/%s" % (anaconda.rootPath, mountpoint)
st = stats[mountpoint]
# restore the correct stat info for this mountpoint
os.utime(dest, (st.st_atime, st.st_mtime))
os.chown(dest, st.st_uid, st.st_gid)
os.chmod(dest, stat.S_IMODE(st.st_mode))
# ensure that non-fstab filesystems are mounted in the chroot
if flags.selinux:
try:
isys.mount("/selinux", anaconda.rootPath + "/selinux", "selinuxfs")
except Exception, e:
log.error("error mounting selinuxfs: %s" %(e,))
wait.pop()
def _resizeRootfs(self, anaconda, win = None):
log.info("going to do resize")
rootDevice = anaconda.id.storage.rootDevice
# FIXME: we'd like to have progress here to give an idea of
# how long it will take. or at least, to give an indefinite
# progress window. but, not for this time
cmd = ["resize2fs", rootDevice.path, "-p"]
out = open("/dev/tty5", "w")
proc = subprocess.Popen(cmd, stdout=out, stderr=out)
rc = proc.poll()
while rc is None:
win and win.refresh()
time.sleep(0.5)
rc = proc.poll()
if rc:
log.error("error running resize2fs; leaving filesystem as is")
return
# we should also do a fsck afterwards
cmd = ["e2fsck", "-f", "-y", rootDevice.path]
out = open("/dev/tty5", "w")
proc = subprocess.Popen(cmd, stdout=out, stderr=out)
rc = proc.poll()
while rc is None:
win and win.refresh()
time.sleep(0.5)
rc = proc.poll()
def doPostInstall(self, anaconda):
import rpm
self._doFilesystemMangling(anaconda)
# setup /etc/rpm/ for the post-install environment
iutil.writeRpmPlatform(anaconda.rootPath)
storage.writeEscrowPackets(anaconda)
packages.rpmSetupGraphicalSystem(anaconda)
# now write out the "real" fstab and mtab
anaconda.id.storage.write(anaconda.rootPath)
f = open(anaconda.rootPath + "/etc/mtab", "w+")
f.write(anaconda.id.storage.mtab)
f.close()
# copy over the modprobe.conf
if os.path.exists("/etc/modprobe.conf"):
shutil.copyfile("/etc/modprobe.conf",
anaconda.rootPath + "/etc/modprobe.conf")
# set the same keyboard the user selected in the keyboard dialog:
anaconda.id.keyboard.write(anaconda.rootPath)
# rebuild the initrd(s)
vers = self.kernelVersionList(anaconda.rootPath)
for (n, arch, tag) in vers:
packages.recreateInitrd(n, anaconda.rootPath)
def writeConfiguration(self):
pass
def kernelVersionList(self, rootPath = "/"):
return packages.rpmKernelVersionList(rootPath)
def getMinimumSizeMB(self, part):
if part == "/":
return self._getLiveSizeMB()
return 0
def doBackendSetup(self, anaconda):
# ensure there's enough space on the rootfs
# FIXME: really, this should be in the general sanity checking, but
# trying to weave that in is a little tricky at present.
ossize = self._getLiveSizeMB()
slash = anaconda.id.storage.rootDevice
if slash.size < ossize:
rc = anaconda.intf.messageWindow(_("Error"),
_("The root filesystem you created is "
"not large enough for this live "
"image (%.2f MB required).") % ossize,
type = "custom",
custom_icon = "error",
custom_buttons=[_("_Back"),
_("_Exit installer")])
if rc == 0:
return DISPATCH_BACK
else:
sys.exit(1)
# package/group selection doesn't apply for this backend
def groupExists(self, group):
pass
def selectGroup(self, group, *args):
pass
def deselectGroup(self, group, *args):
pass
def selectPackage(self, pkg, *args):
pass
def deselectPackage(self, pkg, *args):
pass
def | (self, pkg):
return True
def getDefaultGroups(self, anaconda):
return []
def writePackagesKS(self, f, anaconda):
pass
| packageExists | identifier_name |
livecd.py | #
# livecd.py: An anaconda backend to do an install from a live CD image
#
# The basic idea is that with a live CD, we already have an install
# and should be able to just copy those bits over to the disk. So we dd
# the image, move things to the "right" filesystem as needed, and then
# resize the rootfs to the size of its container.
#
# Copyright (C) 2007 Red Hat, Inc. All rights reserved.
#
# 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, see <http://www.gnu.org/licenses/>.
#
# Author(s): Jeremy Katz <katzj@redhat.com>
#
import os, sys
import stat
import shutil
import time
import subprocess
import storage
import selinux
from flags import flags
from constants import *
import gettext
_ = lambda x: gettext.ldgettext("anaconda", x)
import backend
import isys
import iutil
import packages
import logging
log = logging.getLogger("anaconda")
class Error(EnvironmentError):
pass
def copytree(src, dst, symlinks=False, preserveOwner=False,
preserveSelinux=False):
def tryChown(src, dest):
try:
os.chown(dest, os.stat(src)[stat.ST_UID], os.stat(src)[stat.ST_GID])
except OverflowError:
log.error("Could not set owner and group on file %s" % dest)
def trySetfilecon(src, dest):
try:
selinux.lsetfilecon(dest, selinux.lgetfilecon(src)[1])
except:
log.error("Could not set selinux context on file %s" % dest)
# copy of shutil.copytree which doesn't require dst to not exist
# and which also has options to preserve the owner and selinux contexts
names = os.listdir(src)
if not os.path.isdir(dst):
os.makedirs(dst)
errors = []
for name in names:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
if preserveSelinux:
trySetfilecon(srcname, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, preserveOwner, preserveSelinux)
else:
shutil.copyfile(srcname, dstname)
if preserveOwner:
tryChown(srcname, dstname)
if preserveSelinux:
trySetfilecon(srcname, dstname)
shutil.copystat(srcname, dstname)
except (IOError, os.error), why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error, err:
errors.extend(err.args[0])
try:
if preserveOwner:
tryChown(src, dst)
if preserveSelinux:
trySetfilecon(src, dst)
shutil.copystat(src, dst)
except OSError as e:
errors.extend((src, dst, e.strerror))
if errors:
raise Error, errors
class LiveCDCopyBackend(backend.AnacondaBackend):
def __init__(self, anaconda):
backend.AnacondaBackend.__init__(self, anaconda)
flags.livecdInstall = True
self.supportsUpgrades = False
self.supportsPackageSelection = False
self.skipFormatRoot = True
self.osimg = anaconda.methodstr[8:]
if not stat.S_ISBLK(os.stat(self.osimg)[stat.ST_MODE]):
|
self.rootFsType = isys.readFSType(self.osimg)
def _getLiveBlockDevice(self):
return os.path.normpath(self.osimg)
def _getLiveSize(self):
def parseField(output, field):
for line in output.split("\n"):
if line.startswith(field + ":"):
return line[len(field) + 1:].strip()
raise KeyError("Failed to find field '%s' in output" % field)
output = subprocess.Popen(['/sbin/dumpe2fs', '-h', self.osimg],
stdout=subprocess.PIPE,
stderr=open('/dev/null', 'w')
).communicate()[0]
blkcnt = int(parseField(output, "Block count"))
blksize = int(parseField(output, "Block size"))
return blkcnt * blksize
def _getLiveSizeMB(self):
return self._getLiveSize() / 1048576
def _unmountNonFstabDirs(self, anaconda):
# unmount things that aren't listed in /etc/fstab. *sigh*
dirs = []
if flags.selinux:
dirs.append("/selinux")
for dir in dirs:
try:
isys.umount("%s/%s" %(anaconda.rootPath,dir), removeDir = False)
except Exception, e:
log.error("unable to unmount %s: %s" %(dir, e))
def postAction(self, anaconda):
self._unmountNonFstabDirs(anaconda)
try:
anaconda.id.storage.umountFilesystems(swapoff = False)
os.rmdir(anaconda.rootPath)
except Exception, e:
log.error("Unable to unmount filesystems: %s" % e)
def doPreInstall(self, anaconda):
if anaconda.dir == DISPATCH_BACK:
self._unmountNonFstabDirs(anaconda)
return
anaconda.id.storage.umountFilesystems(swapoff = False)
def doInstall(self, anaconda):
log.info("Preparing to install packages")
progress = anaconda.id.instProgress
progress.set_label(_("Copying live image to hard drive."))
progress.processEvents()
osimg = self._getLiveBlockDevice() # the real image
osfd = os.open(osimg, os.O_RDONLY)
rootDevice = anaconda.id.storage.rootDevice
rootDevice.setup()
rootfd = os.open(rootDevice.path, os.O_WRONLY)
readamt = 1024 * 1024 * 8 # 8 megs at a time
size = self._getLiveSize()
copied = 0
while copied < size:
try:
buf = os.read(osfd, readamt)
written = os.write(rootfd, buf)
except:
rc = anaconda.intf.messageWindow(_("Error"),
_("There was an error installing the live image to "
"your hard drive. This could be due to bad media. "
"Please verify your installation media.\n\nIf you "
"exit, your system will be left in an inconsistent "
"state that will require reinstallation."),
type="custom", custom_icon="error",
custom_buttons=[_("_Exit installer"), _("_Retry")])
if rc == 0:
sys.exit(0)
else:
os.lseek(osfd, 0, 0)
os.lseek(rootfd, 0, 0)
copied = 0
continue
if (written < readamt) and (written < len(buf)):
raise RuntimeError, "error copying filesystem!"
copied += written
progress.set_fraction(pct = copied / float(size))
progress.processEvents()
os.close(osfd)
os.close(rootfd)
anaconda.id.instProgress = None
def _doFilesystemMangling(self, anaconda):
log.info("doing post-install fs mangling")
wait = anaconda.intf.waitWindow(_("Post-Installation"),
_("Performing post-installation filesystem changes. This may take several minutes."))
# resize rootfs first, since it is 100% full due to genMinInstDelta
self._resizeRootfs(anaconda, wait)
# remount filesystems
anaconda.id.storage.mountFilesystems()
# restore the label of / to what we think it is
rootDevice = anaconda.id.storage.rootDevice
rootDevice.setup()
# ensure we have a random UUID on the rootfs
# FIXME: this should be abstracted per filesystem type
iutil.execWithRedirect("tune2fs",
["-U",
"random",
rootDevice.path],
stdout="/dev/tty5",
stderr="/dev/tty5")
# and now set the uuid in the storage layer
rootDevice.updateSysfsPath()
iutil.notify_kernel("/sys%s" %rootDevice.sysfsPath)
storage.udev.udev_settle()
rootDevice.updateSysfsPath()
info = storage.udev.udev_get_block_device(rootDevice.sysfsPath)
rootDevice.format.uuid = storage.udev.udev_device_get_uuid(info)
log.info("reset the rootdev (%s) to have a uuid of %s" %(rootDevice.sysfsPath, rootDevice.format.uuid))
# for any filesystem that's _not_ on the root, we need to handle
# moving the bits from the livecd -> the real filesystems.
# this is pretty distasteful, but should work with things like
# having a separate /usr/local
def _setupFilesystems(mounts, chroot="", teardown=False):
""" Setup or teardown all filesystems except for "/" """
mountpoints = sorted(mounts.keys(),
reverse=teardown is True)
if teardown:
method = "teardown"
kwargs = {}
else:
method = "setup"
kwargs = {"chroot": chroot}
mountpoints.remove("/")
for mountpoint in mountpoints:
device = mounts[mountpoint]
getattr(device.format, method)(**kwargs)
# Start by sorting the mountpoints in decreasing-depth order.
mountpoints = sorted(anaconda.id.storage.mountpoints.keys(),
reverse=True)
# We don't want to copy the root filesystem.
mountpoints.remove("/")
stats = {} # mountpoint: posix.stat_result
# unmount the filesystems, except for /
_setupFilesystems(anaconda.id.storage.mountpoints, teardown=True)
# mount all of the filesystems under /mnt so we can copy in content
_setupFilesystems(anaconda.id.storage.mountpoints,
chroot=anaconda.rootPath + "/mnt")
# And now let's do the real copies
for tocopy in mountpoints:
device = anaconda.id.storage.mountpoints[tocopy]
# FIXME: all calls to wait.refresh() are kind of a hack... we
# should do better about not doing blocking things in the
# main thread. but threading anaconda is a job for another
# time.
wait.refresh()
if not os.path.exists("%s/%s" % (anaconda.rootPath, tocopy)):
# the directory does not exist in the live image, so there's
# nothing to move
continue
copytree("%s/%s" % (anaconda.rootPath, tocopy),
"%s/mnt/%s" % (anaconda.rootPath, tocopy),
True, True, flags.selinux)
wait.refresh()
shutil.rmtree("%s/%s" % (anaconda.rootPath, tocopy))
wait.refresh()
# now unmount each fs, collect stat info for the mountpoint, then
# remove the entire tree containing the mountpoint
for tocopy in mountpoints:
device = anaconda.id.storage.mountpoints[tocopy]
device.format.teardown()
if not os.path.exists("%s/%s" % (anaconda.rootPath, tocopy)):
continue
try:
stats[tocopy]= os.stat("%s/mnt/%s" % (anaconda.rootPath,
tocopy))
except Exception as e:
log.info("failed to get stat info for mountpoint %s: %s"
% (tocopy, e))
shutil.rmtree("%s/mnt/%s" % (anaconda.rootPath,
tocopy.split("/")[1]))
wait.refresh()
# now mount all of the filesystems so that post-install writes end
# up where they're supposed to end up
_setupFilesystems(anaconda.id.storage.mountpoints,
chroot=anaconda.rootPath)
# restore stat info for each mountpoint
for mountpoint in reversed(mountpoints):
if mountpoint not in stats:
# there's no info to restore since the mountpoint did not
# exist in the live image
continue
dest = "%s/%s" % (anaconda.rootPath, mountpoint)
st = stats[mountpoint]
# restore the correct stat info for this mountpoint
os.utime(dest, (st.st_atime, st.st_mtime))
os.chown(dest, st.st_uid, st.st_gid)
os.chmod(dest, stat.S_IMODE(st.st_mode))
# ensure that non-fstab filesystems are mounted in the chroot
if flags.selinux:
try:
isys.mount("/selinux", anaconda.rootPath + "/selinux", "selinuxfs")
except Exception, e:
log.error("error mounting selinuxfs: %s" %(e,))
wait.pop()
def _resizeRootfs(self, anaconda, win = None):
log.info("going to do resize")
rootDevice = anaconda.id.storage.rootDevice
# FIXME: we'd like to have progress here to give an idea of
# how long it will take. or at least, to give an indefinite
# progress window. but, not for this time
cmd = ["resize2fs", rootDevice.path, "-p"]
out = open("/dev/tty5", "w")
proc = subprocess.Popen(cmd, stdout=out, stderr=out)
rc = proc.poll()
while rc is None:
win and win.refresh()
time.sleep(0.5)
rc = proc.poll()
if rc:
log.error("error running resize2fs; leaving filesystem as is")
return
# we should also do a fsck afterwards
cmd = ["e2fsck", "-f", "-y", rootDevice.path]
out = open("/dev/tty5", "w")
proc = subprocess.Popen(cmd, stdout=out, stderr=out)
rc = proc.poll()
while rc is None:
win and win.refresh()
time.sleep(0.5)
rc = proc.poll()
def doPostInstall(self, anaconda):
import rpm
self._doFilesystemMangling(anaconda)
# setup /etc/rpm/ for the post-install environment
iutil.writeRpmPlatform(anaconda.rootPath)
storage.writeEscrowPackets(anaconda)
packages.rpmSetupGraphicalSystem(anaconda)
# now write out the "real" fstab and mtab
anaconda.id.storage.write(anaconda.rootPath)
f = open(anaconda.rootPath + "/etc/mtab", "w+")
f.write(anaconda.id.storage.mtab)
f.close()
# copy over the modprobe.conf
if os.path.exists("/etc/modprobe.conf"):
shutil.copyfile("/etc/modprobe.conf",
anaconda.rootPath + "/etc/modprobe.conf")
# set the same keyboard the user selected in the keyboard dialog:
anaconda.id.keyboard.write(anaconda.rootPath)
# rebuild the initrd(s)
vers = self.kernelVersionList(anaconda.rootPath)
for (n, arch, tag) in vers:
packages.recreateInitrd(n, anaconda.rootPath)
def writeConfiguration(self):
pass
def kernelVersionList(self, rootPath = "/"):
return packages.rpmKernelVersionList(rootPath)
def getMinimumSizeMB(self, part):
if part == "/":
return self._getLiveSizeMB()
return 0
def doBackendSetup(self, anaconda):
# ensure there's enough space on the rootfs
# FIXME: really, this should be in the general sanity checking, but
# trying to weave that in is a little tricky at present.
ossize = self._getLiveSizeMB()
slash = anaconda.id.storage.rootDevice
if slash.size < ossize:
rc = anaconda.intf.messageWindow(_("Error"),
_("The root filesystem you created is "
"not large enough for this live "
"image (%.2f MB required).") % ossize,
type = "custom",
custom_icon = "error",
custom_buttons=[_("_Back"),
_("_Exit installer")])
if rc == 0:
return DISPATCH_BACK
else:
sys.exit(1)
# package/group selection doesn't apply for this backend
def groupExists(self, group):
pass
def selectGroup(self, group, *args):
pass
def deselectGroup(self, group, *args):
pass
def selectPackage(self, pkg, *args):
pass
def deselectPackage(self, pkg, *args):
pass
def packageExists(self, pkg):
return True
def getDefaultGroups(self, anaconda):
return []
def writePackagesKS(self, f, anaconda):
pass
| anaconda.intf.messageWindow(_("Unable to find image"),
_("The given location isn't a valid %s "
"live CD to use as an installation source.")
%(productName,), type = "custom",
custom_icon="error",
custom_buttons=[_("Exit installer")])
sys.exit(0) | conditional_block |
livecd.py | #
# livecd.py: An anaconda backend to do an install from a live CD image
#
# The basic idea is that with a live CD, we already have an install
# and should be able to just copy those bits over to the disk. So we dd
# the image, move things to the "right" filesystem as needed, and then
# resize the rootfs to the size of its container.
#
# Copyright (C) 2007 Red Hat, Inc. All rights reserved.
#
# 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, see <http://www.gnu.org/licenses/>.
#
# Author(s): Jeremy Katz <katzj@redhat.com>
#
import os, sys
import stat
import shutil
import time
import subprocess
import storage
import selinux
from flags import flags
from constants import *
import gettext
_ = lambda x: gettext.ldgettext("anaconda", x)
import backend
import isys
import iutil
import packages
import logging
log = logging.getLogger("anaconda")
class Error(EnvironmentError):
pass
def copytree(src, dst, symlinks=False, preserveOwner=False,
preserveSelinux=False):
def tryChown(src, dest):
try:
os.chown(dest, os.stat(src)[stat.ST_UID], os.stat(src)[stat.ST_GID])
except OverflowError:
log.error("Could not set owner and group on file %s" % dest)
def trySetfilecon(src, dest):
try:
selinux.lsetfilecon(dest, selinux.lgetfilecon(src)[1])
except:
log.error("Could not set selinux context on file %s" % dest)
# copy of shutil.copytree which doesn't require dst to not exist
# and which also has options to preserve the owner and selinux contexts
names = os.listdir(src)
if not os.path.isdir(dst):
os.makedirs(dst)
errors = []
for name in names:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
if preserveSelinux:
trySetfilecon(srcname, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, preserveOwner, preserveSelinux)
else:
shutil.copyfile(srcname, dstname)
if preserveOwner:
tryChown(srcname, dstname)
if preserveSelinux:
trySetfilecon(srcname, dstname)
shutil.copystat(srcname, dstname)
except (IOError, os.error), why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error, err:
errors.extend(err.args[0])
try:
if preserveOwner:
tryChown(src, dst)
if preserveSelinux:
trySetfilecon(src, dst)
shutil.copystat(src, dst)
except OSError as e:
errors.extend((src, dst, e.strerror))
if errors:
raise Error, errors
class LiveCDCopyBackend(backend.AnacondaBackend):
def __init__(self, anaconda):
backend.AnacondaBackend.__init__(self, anaconda)
flags.livecdInstall = True
self.supportsUpgrades = False
self.supportsPackageSelection = False
self.skipFormatRoot = True
self.osimg = anaconda.methodstr[8:]
if not stat.S_ISBLK(os.stat(self.osimg)[stat.ST_MODE]):
anaconda.intf.messageWindow(_("Unable to find image"),
_("The given location isn't a valid %s "
"live CD to use as an installation source.")
%(productName,), type = "custom",
custom_icon="error",
custom_buttons=[_("Exit installer")])
sys.exit(0)
self.rootFsType = isys.readFSType(self.osimg)
def _getLiveBlockDevice(self):
return os.path.normpath(self.osimg)
def _getLiveSize(self):
def parseField(output, field):
for line in output.split("\n"):
if line.startswith(field + ":"):
return line[len(field) + 1:].strip()
raise KeyError("Failed to find field '%s' in output" % field)
output = subprocess.Popen(['/sbin/dumpe2fs', '-h', self.osimg],
stdout=subprocess.PIPE,
stderr=open('/dev/null', 'w')
).communicate()[0]
blkcnt = int(parseField(output, "Block count"))
blksize = int(parseField(output, "Block size"))
return blkcnt * blksize
def _getLiveSizeMB(self):
return self._getLiveSize() / 1048576
def _unmountNonFstabDirs(self, anaconda):
# unmount things that aren't listed in /etc/fstab. *sigh*
dirs = []
if flags.selinux:
dirs.append("/selinux")
for dir in dirs:
try:
isys.umount("%s/%s" %(anaconda.rootPath,dir), removeDir = False)
except Exception, e:
log.error("unable to unmount %s: %s" %(dir, e))
def postAction(self, anaconda):
|
def doPreInstall(self, anaconda):
if anaconda.dir == DISPATCH_BACK:
self._unmountNonFstabDirs(anaconda)
return
anaconda.id.storage.umountFilesystems(swapoff = False)
def doInstall(self, anaconda):
log.info("Preparing to install packages")
progress = anaconda.id.instProgress
progress.set_label(_("Copying live image to hard drive."))
progress.processEvents()
osimg = self._getLiveBlockDevice() # the real image
osfd = os.open(osimg, os.O_RDONLY)
rootDevice = anaconda.id.storage.rootDevice
rootDevice.setup()
rootfd = os.open(rootDevice.path, os.O_WRONLY)
readamt = 1024 * 1024 * 8 # 8 megs at a time
size = self._getLiveSize()
copied = 0
while copied < size:
try:
buf = os.read(osfd, readamt)
written = os.write(rootfd, buf)
except:
rc = anaconda.intf.messageWindow(_("Error"),
_("There was an error installing the live image to "
"your hard drive. This could be due to bad media. "
"Please verify your installation media.\n\nIf you "
"exit, your system will be left in an inconsistent "
"state that will require reinstallation."),
type="custom", custom_icon="error",
custom_buttons=[_("_Exit installer"), _("_Retry")])
if rc == 0:
sys.exit(0)
else:
os.lseek(osfd, 0, 0)
os.lseek(rootfd, 0, 0)
copied = 0
continue
if (written < readamt) and (written < len(buf)):
raise RuntimeError, "error copying filesystem!"
copied += written
progress.set_fraction(pct = copied / float(size))
progress.processEvents()
os.close(osfd)
os.close(rootfd)
anaconda.id.instProgress = None
def _doFilesystemMangling(self, anaconda):
log.info("doing post-install fs mangling")
wait = anaconda.intf.waitWindow(_("Post-Installation"),
_("Performing post-installation filesystem changes. This may take several minutes."))
# resize rootfs first, since it is 100% full due to genMinInstDelta
self._resizeRootfs(anaconda, wait)
# remount filesystems
anaconda.id.storage.mountFilesystems()
# restore the label of / to what we think it is
rootDevice = anaconda.id.storage.rootDevice
rootDevice.setup()
# ensure we have a random UUID on the rootfs
# FIXME: this should be abstracted per filesystem type
iutil.execWithRedirect("tune2fs",
["-U",
"random",
rootDevice.path],
stdout="/dev/tty5",
stderr="/dev/tty5")
# and now set the uuid in the storage layer
rootDevice.updateSysfsPath()
iutil.notify_kernel("/sys%s" %rootDevice.sysfsPath)
storage.udev.udev_settle()
rootDevice.updateSysfsPath()
info = storage.udev.udev_get_block_device(rootDevice.sysfsPath)
rootDevice.format.uuid = storage.udev.udev_device_get_uuid(info)
log.info("reset the rootdev (%s) to have a uuid of %s" %(rootDevice.sysfsPath, rootDevice.format.uuid))
# for any filesystem that's _not_ on the root, we need to handle
# moving the bits from the livecd -> the real filesystems.
# this is pretty distasteful, but should work with things like
# having a separate /usr/local
def _setupFilesystems(mounts, chroot="", teardown=False):
""" Setup or teardown all filesystems except for "/" """
mountpoints = sorted(mounts.keys(),
reverse=teardown is True)
if teardown:
method = "teardown"
kwargs = {}
else:
method = "setup"
kwargs = {"chroot": chroot}
mountpoints.remove("/")
for mountpoint in mountpoints:
device = mounts[mountpoint]
getattr(device.format, method)(**kwargs)
# Start by sorting the mountpoints in decreasing-depth order.
mountpoints = sorted(anaconda.id.storage.mountpoints.keys(),
reverse=True)
# We don't want to copy the root filesystem.
mountpoints.remove("/")
stats = {} # mountpoint: posix.stat_result
# unmount the filesystems, except for /
_setupFilesystems(anaconda.id.storage.mountpoints, teardown=True)
# mount all of the filesystems under /mnt so we can copy in content
_setupFilesystems(anaconda.id.storage.mountpoints,
chroot=anaconda.rootPath + "/mnt")
# And now let's do the real copies
for tocopy in mountpoints:
device = anaconda.id.storage.mountpoints[tocopy]
# FIXME: all calls to wait.refresh() are kind of a hack... we
# should do better about not doing blocking things in the
# main thread. but threading anaconda is a job for another
# time.
wait.refresh()
if not os.path.exists("%s/%s" % (anaconda.rootPath, tocopy)):
# the directory does not exist in the live image, so there's
# nothing to move
continue
copytree("%s/%s" % (anaconda.rootPath, tocopy),
"%s/mnt/%s" % (anaconda.rootPath, tocopy),
True, True, flags.selinux)
wait.refresh()
shutil.rmtree("%s/%s" % (anaconda.rootPath, tocopy))
wait.refresh()
# now unmount each fs, collect stat info for the mountpoint, then
# remove the entire tree containing the mountpoint
for tocopy in mountpoints:
device = anaconda.id.storage.mountpoints[tocopy]
device.format.teardown()
if not os.path.exists("%s/%s" % (anaconda.rootPath, tocopy)):
continue
try:
stats[tocopy]= os.stat("%s/mnt/%s" % (anaconda.rootPath,
tocopy))
except Exception as e:
log.info("failed to get stat info for mountpoint %s: %s"
% (tocopy, e))
shutil.rmtree("%s/mnt/%s" % (anaconda.rootPath,
tocopy.split("/")[1]))
wait.refresh()
# now mount all of the filesystems so that post-install writes end
# up where they're supposed to end up
_setupFilesystems(anaconda.id.storage.mountpoints,
chroot=anaconda.rootPath)
# restore stat info for each mountpoint
for mountpoint in reversed(mountpoints):
if mountpoint not in stats:
# there's no info to restore since the mountpoint did not
# exist in the live image
continue
dest = "%s/%s" % (anaconda.rootPath, mountpoint)
st = stats[mountpoint]
# restore the correct stat info for this mountpoint
os.utime(dest, (st.st_atime, st.st_mtime))
os.chown(dest, st.st_uid, st.st_gid)
os.chmod(dest, stat.S_IMODE(st.st_mode))
# ensure that non-fstab filesystems are mounted in the chroot
if flags.selinux:
try:
isys.mount("/selinux", anaconda.rootPath + "/selinux", "selinuxfs")
except Exception, e:
log.error("error mounting selinuxfs: %s" %(e,))
wait.pop()
def _resizeRootfs(self, anaconda, win = None):
log.info("going to do resize")
rootDevice = anaconda.id.storage.rootDevice
# FIXME: we'd like to have progress here to give an idea of
# how long it will take. or at least, to give an indefinite
# progress window. but, not for this time
cmd = ["resize2fs", rootDevice.path, "-p"]
out = open("/dev/tty5", "w")
proc = subprocess.Popen(cmd, stdout=out, stderr=out)
rc = proc.poll()
while rc is None:
win and win.refresh()
time.sleep(0.5)
rc = proc.poll()
if rc:
log.error("error running resize2fs; leaving filesystem as is")
return
# we should also do a fsck afterwards
cmd = ["e2fsck", "-f", "-y", rootDevice.path]
out = open("/dev/tty5", "w")
proc = subprocess.Popen(cmd, stdout=out, stderr=out)
rc = proc.poll()
while rc is None:
win and win.refresh()
time.sleep(0.5)
rc = proc.poll()
def doPostInstall(self, anaconda):
import rpm
self._doFilesystemMangling(anaconda)
# setup /etc/rpm/ for the post-install environment
iutil.writeRpmPlatform(anaconda.rootPath)
storage.writeEscrowPackets(anaconda)
packages.rpmSetupGraphicalSystem(anaconda)
# now write out the "real" fstab and mtab
anaconda.id.storage.write(anaconda.rootPath)
f = open(anaconda.rootPath + "/etc/mtab", "w+")
f.write(anaconda.id.storage.mtab)
f.close()
# copy over the modprobe.conf
if os.path.exists("/etc/modprobe.conf"):
shutil.copyfile("/etc/modprobe.conf",
anaconda.rootPath + "/etc/modprobe.conf")
# set the same keyboard the user selected in the keyboard dialog:
anaconda.id.keyboard.write(anaconda.rootPath)
# rebuild the initrd(s)
vers = self.kernelVersionList(anaconda.rootPath)
for (n, arch, tag) in vers:
packages.recreateInitrd(n, anaconda.rootPath)
def writeConfiguration(self):
pass
def kernelVersionList(self, rootPath = "/"):
return packages.rpmKernelVersionList(rootPath)
def getMinimumSizeMB(self, part):
if part == "/":
return self._getLiveSizeMB()
return 0
def doBackendSetup(self, anaconda):
# ensure there's enough space on the rootfs
# FIXME: really, this should be in the general sanity checking, but
# trying to weave that in is a little tricky at present.
ossize = self._getLiveSizeMB()
slash = anaconda.id.storage.rootDevice
if slash.size < ossize:
rc = anaconda.intf.messageWindow(_("Error"),
_("The root filesystem you created is "
"not large enough for this live "
"image (%.2f MB required).") % ossize,
type = "custom",
custom_icon = "error",
custom_buttons=[_("_Back"),
_("_Exit installer")])
if rc == 0:
return DISPATCH_BACK
else:
sys.exit(1)
# package/group selection doesn't apply for this backend
def groupExists(self, group):
pass
def selectGroup(self, group, *args):
pass
def deselectGroup(self, group, *args):
pass
def selectPackage(self, pkg, *args):
pass
def deselectPackage(self, pkg, *args):
pass
def packageExists(self, pkg):
return True
def getDefaultGroups(self, anaconda):
return []
def writePackagesKS(self, f, anaconda):
pass
| self._unmountNonFstabDirs(anaconda)
try:
anaconda.id.storage.umountFilesystems(swapoff = False)
os.rmdir(anaconda.rootPath)
except Exception, e:
log.error("Unable to unmount filesystems: %s" % e) | identifier_body |
livecd.py | #
# livecd.py: An anaconda backend to do an install from a live CD image
#
# The basic idea is that with a live CD, we already have an install
# and should be able to just copy those bits over to the disk. So we dd
# the image, move things to the "right" filesystem as needed, and then
# resize the rootfs to the size of its container.
#
# Copyright (C) 2007 Red Hat, Inc. All rights reserved.
#
# 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, see <http://www.gnu.org/licenses/>.
#
# Author(s): Jeremy Katz <katzj@redhat.com>
#
import os, sys
import stat
import shutil
import time
import subprocess
import storage
import selinux
from flags import flags
from constants import *
import gettext
_ = lambda x: gettext.ldgettext("anaconda", x)
import backend
import isys
import iutil
import packages
import logging
log = logging.getLogger("anaconda")
class Error(EnvironmentError):
pass
def copytree(src, dst, symlinks=False, preserveOwner=False,
preserveSelinux=False):
def tryChown(src, dest):
try:
os.chown(dest, os.stat(src)[stat.ST_UID], os.stat(src)[stat.ST_GID])
except OverflowError:
log.error("Could not set owner and group on file %s" % dest)
def trySetfilecon(src, dest):
try:
selinux.lsetfilecon(dest, selinux.lgetfilecon(src)[1])
except:
log.error("Could not set selinux context on file %s" % dest)
# copy of shutil.copytree which doesn't require dst to not exist
# and which also has options to preserve the owner and selinux contexts
names = os.listdir(src)
if not os.path.isdir(dst):
os.makedirs(dst)
errors = [] | try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
if preserveSelinux:
trySetfilecon(srcname, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, preserveOwner, preserveSelinux)
else:
shutil.copyfile(srcname, dstname)
if preserveOwner:
tryChown(srcname, dstname)
if preserveSelinux:
trySetfilecon(srcname, dstname)
shutil.copystat(srcname, dstname)
except (IOError, os.error), why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error, err:
errors.extend(err.args[0])
try:
if preserveOwner:
tryChown(src, dst)
if preserveSelinux:
trySetfilecon(src, dst)
shutil.copystat(src, dst)
except OSError as e:
errors.extend((src, dst, e.strerror))
if errors:
raise Error, errors
class LiveCDCopyBackend(backend.AnacondaBackend):
def __init__(self, anaconda):
backend.AnacondaBackend.__init__(self, anaconda)
flags.livecdInstall = True
self.supportsUpgrades = False
self.supportsPackageSelection = False
self.skipFormatRoot = True
self.osimg = anaconda.methodstr[8:]
if not stat.S_ISBLK(os.stat(self.osimg)[stat.ST_MODE]):
anaconda.intf.messageWindow(_("Unable to find image"),
_("The given location isn't a valid %s "
"live CD to use as an installation source.")
%(productName,), type = "custom",
custom_icon="error",
custom_buttons=[_("Exit installer")])
sys.exit(0)
self.rootFsType = isys.readFSType(self.osimg)
def _getLiveBlockDevice(self):
return os.path.normpath(self.osimg)
def _getLiveSize(self):
def parseField(output, field):
for line in output.split("\n"):
if line.startswith(field + ":"):
return line[len(field) + 1:].strip()
raise KeyError("Failed to find field '%s' in output" % field)
output = subprocess.Popen(['/sbin/dumpe2fs', '-h', self.osimg],
stdout=subprocess.PIPE,
stderr=open('/dev/null', 'w')
).communicate()[0]
blkcnt = int(parseField(output, "Block count"))
blksize = int(parseField(output, "Block size"))
return blkcnt * blksize
def _getLiveSizeMB(self):
return self._getLiveSize() / 1048576
def _unmountNonFstabDirs(self, anaconda):
# unmount things that aren't listed in /etc/fstab. *sigh*
dirs = []
if flags.selinux:
dirs.append("/selinux")
for dir in dirs:
try:
isys.umount("%s/%s" %(anaconda.rootPath,dir), removeDir = False)
except Exception, e:
log.error("unable to unmount %s: %s" %(dir, e))
def postAction(self, anaconda):
self._unmountNonFstabDirs(anaconda)
try:
anaconda.id.storage.umountFilesystems(swapoff = False)
os.rmdir(anaconda.rootPath)
except Exception, e:
log.error("Unable to unmount filesystems: %s" % e)
def doPreInstall(self, anaconda):
if anaconda.dir == DISPATCH_BACK:
self._unmountNonFstabDirs(anaconda)
return
anaconda.id.storage.umountFilesystems(swapoff = False)
def doInstall(self, anaconda):
log.info("Preparing to install packages")
progress = anaconda.id.instProgress
progress.set_label(_("Copying live image to hard drive."))
progress.processEvents()
osimg = self._getLiveBlockDevice() # the real image
osfd = os.open(osimg, os.O_RDONLY)
rootDevice = anaconda.id.storage.rootDevice
rootDevice.setup()
rootfd = os.open(rootDevice.path, os.O_WRONLY)
readamt = 1024 * 1024 * 8 # 8 megs at a time
size = self._getLiveSize()
copied = 0
while copied < size:
try:
buf = os.read(osfd, readamt)
written = os.write(rootfd, buf)
except:
rc = anaconda.intf.messageWindow(_("Error"),
_("There was an error installing the live image to "
"your hard drive. This could be due to bad media. "
"Please verify your installation media.\n\nIf you "
"exit, your system will be left in an inconsistent "
"state that will require reinstallation."),
type="custom", custom_icon="error",
custom_buttons=[_("_Exit installer"), _("_Retry")])
if rc == 0:
sys.exit(0)
else:
os.lseek(osfd, 0, 0)
os.lseek(rootfd, 0, 0)
copied = 0
continue
if (written < readamt) and (written < len(buf)):
raise RuntimeError, "error copying filesystem!"
copied += written
progress.set_fraction(pct = copied / float(size))
progress.processEvents()
os.close(osfd)
os.close(rootfd)
anaconda.id.instProgress = None
def _doFilesystemMangling(self, anaconda):
log.info("doing post-install fs mangling")
wait = anaconda.intf.waitWindow(_("Post-Installation"),
_("Performing post-installation filesystem changes. This may take several minutes."))
# resize rootfs first, since it is 100% full due to genMinInstDelta
self._resizeRootfs(anaconda, wait)
# remount filesystems
anaconda.id.storage.mountFilesystems()
# restore the label of / to what we think it is
rootDevice = anaconda.id.storage.rootDevice
rootDevice.setup()
# ensure we have a random UUID on the rootfs
# FIXME: this should be abstracted per filesystem type
iutil.execWithRedirect("tune2fs",
["-U",
"random",
rootDevice.path],
stdout="/dev/tty5",
stderr="/dev/tty5")
# and now set the uuid in the storage layer
rootDevice.updateSysfsPath()
iutil.notify_kernel("/sys%s" %rootDevice.sysfsPath)
storage.udev.udev_settle()
rootDevice.updateSysfsPath()
info = storage.udev.udev_get_block_device(rootDevice.sysfsPath)
rootDevice.format.uuid = storage.udev.udev_device_get_uuid(info)
log.info("reset the rootdev (%s) to have a uuid of %s" %(rootDevice.sysfsPath, rootDevice.format.uuid))
# for any filesystem that's _not_ on the root, we need to handle
# moving the bits from the livecd -> the real filesystems.
# this is pretty distasteful, but should work with things like
# having a separate /usr/local
def _setupFilesystems(mounts, chroot="", teardown=False):
""" Setup or teardown all filesystems except for "/" """
mountpoints = sorted(mounts.keys(),
reverse=teardown is True)
if teardown:
method = "teardown"
kwargs = {}
else:
method = "setup"
kwargs = {"chroot": chroot}
mountpoints.remove("/")
for mountpoint in mountpoints:
device = mounts[mountpoint]
getattr(device.format, method)(**kwargs)
# Start by sorting the mountpoints in decreasing-depth order.
mountpoints = sorted(anaconda.id.storage.mountpoints.keys(),
reverse=True)
# We don't want to copy the root filesystem.
mountpoints.remove("/")
stats = {} # mountpoint: posix.stat_result
# unmount the filesystems, except for /
_setupFilesystems(anaconda.id.storage.mountpoints, teardown=True)
# mount all of the filesystems under /mnt so we can copy in content
_setupFilesystems(anaconda.id.storage.mountpoints,
chroot=anaconda.rootPath + "/mnt")
# And now let's do the real copies
for tocopy in mountpoints:
device = anaconda.id.storage.mountpoints[tocopy]
# FIXME: all calls to wait.refresh() are kind of a hack... we
# should do better about not doing blocking things in the
# main thread. but threading anaconda is a job for another
# time.
wait.refresh()
if not os.path.exists("%s/%s" % (anaconda.rootPath, tocopy)):
# the directory does not exist in the live image, so there's
# nothing to move
continue
copytree("%s/%s" % (anaconda.rootPath, tocopy),
"%s/mnt/%s" % (anaconda.rootPath, tocopy),
True, True, flags.selinux)
wait.refresh()
shutil.rmtree("%s/%s" % (anaconda.rootPath, tocopy))
wait.refresh()
# now unmount each fs, collect stat info for the mountpoint, then
# remove the entire tree containing the mountpoint
for tocopy in mountpoints:
device = anaconda.id.storage.mountpoints[tocopy]
device.format.teardown()
if not os.path.exists("%s/%s" % (anaconda.rootPath, tocopy)):
continue
try:
stats[tocopy]= os.stat("%s/mnt/%s" % (anaconda.rootPath,
tocopy))
except Exception as e:
log.info("failed to get stat info for mountpoint %s: %s"
% (tocopy, e))
shutil.rmtree("%s/mnt/%s" % (anaconda.rootPath,
tocopy.split("/")[1]))
wait.refresh()
# now mount all of the filesystems so that post-install writes end
# up where they're supposed to end up
_setupFilesystems(anaconda.id.storage.mountpoints,
chroot=anaconda.rootPath)
# restore stat info for each mountpoint
for mountpoint in reversed(mountpoints):
if mountpoint not in stats:
# there's no info to restore since the mountpoint did not
# exist in the live image
continue
dest = "%s/%s" % (anaconda.rootPath, mountpoint)
st = stats[mountpoint]
# restore the correct stat info for this mountpoint
os.utime(dest, (st.st_atime, st.st_mtime))
os.chown(dest, st.st_uid, st.st_gid)
os.chmod(dest, stat.S_IMODE(st.st_mode))
# ensure that non-fstab filesystems are mounted in the chroot
if flags.selinux:
try:
isys.mount("/selinux", anaconda.rootPath + "/selinux", "selinuxfs")
except Exception, e:
log.error("error mounting selinuxfs: %s" %(e,))
wait.pop()
def _resizeRootfs(self, anaconda, win = None):
log.info("going to do resize")
rootDevice = anaconda.id.storage.rootDevice
# FIXME: we'd like to have progress here to give an idea of
# how long it will take. or at least, to give an indefinite
# progress window. but, not for this time
cmd = ["resize2fs", rootDevice.path, "-p"]
out = open("/dev/tty5", "w")
proc = subprocess.Popen(cmd, stdout=out, stderr=out)
rc = proc.poll()
while rc is None:
win and win.refresh()
time.sleep(0.5)
rc = proc.poll()
if rc:
log.error("error running resize2fs; leaving filesystem as is")
return
# we should also do a fsck afterwards
cmd = ["e2fsck", "-f", "-y", rootDevice.path]
out = open("/dev/tty5", "w")
proc = subprocess.Popen(cmd, stdout=out, stderr=out)
rc = proc.poll()
while rc is None:
win and win.refresh()
time.sleep(0.5)
rc = proc.poll()
def doPostInstall(self, anaconda):
import rpm
self._doFilesystemMangling(anaconda)
# setup /etc/rpm/ for the post-install environment
iutil.writeRpmPlatform(anaconda.rootPath)
storage.writeEscrowPackets(anaconda)
packages.rpmSetupGraphicalSystem(anaconda)
# now write out the "real" fstab and mtab
anaconda.id.storage.write(anaconda.rootPath)
f = open(anaconda.rootPath + "/etc/mtab", "w+")
f.write(anaconda.id.storage.mtab)
f.close()
# copy over the modprobe.conf
if os.path.exists("/etc/modprobe.conf"):
shutil.copyfile("/etc/modprobe.conf",
anaconda.rootPath + "/etc/modprobe.conf")
# set the same keyboard the user selected in the keyboard dialog:
anaconda.id.keyboard.write(anaconda.rootPath)
# rebuild the initrd(s)
vers = self.kernelVersionList(anaconda.rootPath)
for (n, arch, tag) in vers:
packages.recreateInitrd(n, anaconda.rootPath)
def writeConfiguration(self):
pass
def kernelVersionList(self, rootPath = "/"):
return packages.rpmKernelVersionList(rootPath)
def getMinimumSizeMB(self, part):
if part == "/":
return self._getLiveSizeMB()
return 0
def doBackendSetup(self, anaconda):
# ensure there's enough space on the rootfs
# FIXME: really, this should be in the general sanity checking, but
# trying to weave that in is a little tricky at present.
ossize = self._getLiveSizeMB()
slash = anaconda.id.storage.rootDevice
if slash.size < ossize:
rc = anaconda.intf.messageWindow(_("Error"),
_("The root filesystem you created is "
"not large enough for this live "
"image (%.2f MB required).") % ossize,
type = "custom",
custom_icon = "error",
custom_buttons=[_("_Back"),
_("_Exit installer")])
if rc == 0:
return DISPATCH_BACK
else:
sys.exit(1)
# package/group selection doesn't apply for this backend
def groupExists(self, group):
pass
def selectGroup(self, group, *args):
pass
def deselectGroup(self, group, *args):
pass
def selectPackage(self, pkg, *args):
pass
def deselectPackage(self, pkg, *args):
pass
def packageExists(self, pkg):
return True
def getDefaultGroups(self, anaconda):
return []
def writePackagesKS(self, f, anaconda):
pass | for name in names:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name) | random_line_split |
lib.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// 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/>.
//! A collection associating pair of keys (row and column) with a single value.
use std::hash::Hash;
use std::collections::HashMap;
use std::collections::hash_map::Keys;
/// Structure to hold double-indexed values
///
/// You can obviously use `HashMap<(Row,Col), Val>`, but this structure gives
/// you better access to all `Columns` in Specific `Row`. Namely you can get sub-hashmap
/// `HashMap<Col, Val>` for specific `Row`
#[derive(Default, Debug, PartialEq)]
pub struct Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
map: HashMap<Row, HashMap<Col, Val>>,
}
impl<Row, Col, Val> Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
/// Creates new Table
pub fn new() -> Self {
Table {
map: HashMap::new(),
}
}
/// Returns keys iterator for this Table.
pub fn keys(&self) -> Keys<Row, HashMap<Col, Val>> {
self.map.keys()
}
/// Removes all elements from this Table
pub fn clear(&mut self) {
self.map.clear();
}
/// Returns length of the Table (number of (row, col, val) tuples)
pub fn len(&self) -> usize {
self.map.values().fold(0, |acc, v| acc + v.len())
}
/// Check if there is any element in this Table
pub fn is_empty(&self) -> bool {
self.map.is_empty() || self.map.values().all(|v| v.is_empty())
}
/// Get mutable reference for single Table row.
pub fn row_mut(&mut self, row: &Row) -> Option<&mut HashMap<Col, Val>> {
self.map.get_mut(row)
}
/// Checks if row is defined for that table (note that even if defined it might be empty)
pub fn has_row(&self, row: &Row) -> bool {
self.map.contains_key(row)
}
/// Get immutable reference for single row in this Table
pub fn row(&self, row: &Row) -> Option<&HashMap<Col, Val>> {
self.map.get(row)
}
/// Get element in cell described by `(row, col)`
pub fn | (&self, row: &Row, col: &Col) -> Option<&Val> {
self.map.get(row).and_then(|r| r.get(col))
}
/// Remove value from specific cell
///
/// It will remove the row if it's the last value in it
pub fn remove(&mut self, row: &Row, col: &Col) -> Option<Val> {
let (val, is_empty) = {
let row_map = self.map.get_mut(row);
if let None = row_map {
return None;
}
let mut row_map = row_map.unwrap();
let val = row_map.remove(col);
(val, row_map.is_empty())
};
// Clean row
if is_empty {
self.map.remove(row);
}
val
}
/// Remove given row from Table if there are no values defined in it
///
/// When using `#row_mut` it may happen that all values from some row are drained.
/// Table however will not be aware that row is empty.
/// You can use this method to explicitly remove row entry from the Table.
pub fn clear_if_empty(&mut self, row: &Row) {
let is_empty = self.map.get(row).map_or(false, |m| m.is_empty());
if is_empty {
self.map.remove(row);
}
}
/// Inserts new value to specified cell
///
/// Returns previous value (if any)
pub fn insert(&mut self, row: Row, col: Col, val: Val) -> Option<Val> {
self.map.entry(row).or_insert_with(HashMap::new).insert(col, val)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn should_create_empty_table() {
// when
let table : Table<usize, usize, bool> = Table::new();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
}
#[test]
fn should_insert_elements_and_return_previous_if_any() {
// given
let mut table = Table::new();
// when
let r1 = table.insert(5, 4, true);
let r2 = table.insert(10, 4, true);
let r3 = table.insert(10, 10, true);
let r4 = table.insert(10, 10, false);
// then
assert!(r1.is_none());
assert!(r2.is_none());
assert!(r3.is_none());
assert!(r4.is_some());
assert!(!table.is_empty());
assert_eq!(r4.unwrap(), true);
assert_eq!(table.len(), 3);
}
#[test]
fn should_remove_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(!table.is_empty());
assert_eq!(table.len(), 1);
// when
let r = table.remove(&5, &4);
// then
assert!(table.is_empty());
assert_eq!(table.len() ,0);
assert_eq!(r.unwrap(), true);
}
#[test]
fn should_return_none_if_trying_to_remove_non_existing_element() {
// given
let mut table : Table<usize, usize, usize> = Table::new();
assert!(table.is_empty());
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_none());
}
#[test]
fn should_clear_row_if_removing_last_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(table.has_row(&5));
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_some());
assert!(!table.has_row(&5));
}
#[test]
fn should_return_element_given_row_and_col() {
// given
let mut table = Table::new();
table.insert(1551, 1234, 123);
// when
let r1 = table.get(&1551, &1234);
let r2 = table.get(&5, &4);
// then
assert!(r1.is_some());
assert!(r2.is_none());
assert_eq!(r1.unwrap(), &123);
}
#[test]
fn should_clear_table() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
assert_eq!(table.len(), 3);
// when
table.clear();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
assert_eq!(table.has_row(&1), false);
assert_eq!(table.has_row(&2), false);
}
#[test]
fn should_return_mutable_row() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
// when
{
let mut row = table.row_mut(&1).unwrap();
row.remove(&1);
row.remove(&2);
}
assert!(table.has_row(&1));
table.clear_if_empty(&1);
// then
assert!(!table.has_row(&1));
assert_eq!(table.len(), 1);
}
}
| get | identifier_name |
lib.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// 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/>.
//! A collection associating pair of keys (row and column) with a single value.
use std::hash::Hash;
use std::collections::HashMap;
use std::collections::hash_map::Keys;
/// Structure to hold double-indexed values
///
/// You can obviously use `HashMap<(Row,Col), Val>`, but this structure gives
/// you better access to all `Columns` in Specific `Row`. Namely you can get sub-hashmap
/// `HashMap<Col, Val>` for specific `Row`
#[derive(Default, Debug, PartialEq)]
pub struct Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
map: HashMap<Row, HashMap<Col, Val>>,
}
impl<Row, Col, Val> Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
/// Creates new Table
pub fn new() -> Self {
Table {
map: HashMap::new(),
}
}
/// Returns keys iterator for this Table.
pub fn keys(&self) -> Keys<Row, HashMap<Col, Val>> {
self.map.keys()
}
/// Removes all elements from this Table
pub fn clear(&mut self) {
self.map.clear();
}
/// Returns length of the Table (number of (row, col, val) tuples)
pub fn len(&self) -> usize {
self.map.values().fold(0, |acc, v| acc + v.len())
}
/// Check if there is any element in this Table
pub fn is_empty(&self) -> bool {
self.map.is_empty() || self.map.values().all(|v| v.is_empty())
}
/// Get mutable reference for single Table row.
pub fn row_mut(&mut self, row: &Row) -> Option<&mut HashMap<Col, Val>> {
self.map.get_mut(row)
}
/// Checks if row is defined for that table (note that even if defined it might be empty)
pub fn has_row(&self, row: &Row) -> bool |
/// Get immutable reference for single row in this Table
pub fn row(&self, row: &Row) -> Option<&HashMap<Col, Val>> {
self.map.get(row)
}
/// Get element in cell described by `(row, col)`
pub fn get(&self, row: &Row, col: &Col) -> Option<&Val> {
self.map.get(row).and_then(|r| r.get(col))
}
/// Remove value from specific cell
///
/// It will remove the row if it's the last value in it
pub fn remove(&mut self, row: &Row, col: &Col) -> Option<Val> {
let (val, is_empty) = {
let row_map = self.map.get_mut(row);
if let None = row_map {
return None;
}
let mut row_map = row_map.unwrap();
let val = row_map.remove(col);
(val, row_map.is_empty())
};
// Clean row
if is_empty {
self.map.remove(row);
}
val
}
/// Remove given row from Table if there are no values defined in it
///
/// When using `#row_mut` it may happen that all values from some row are drained.
/// Table however will not be aware that row is empty.
/// You can use this method to explicitly remove row entry from the Table.
pub fn clear_if_empty(&mut self, row: &Row) {
let is_empty = self.map.get(row).map_or(false, |m| m.is_empty());
if is_empty {
self.map.remove(row);
}
}
/// Inserts new value to specified cell
///
/// Returns previous value (if any)
pub fn insert(&mut self, row: Row, col: Col, val: Val) -> Option<Val> {
self.map.entry(row).or_insert_with(HashMap::new).insert(col, val)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn should_create_empty_table() {
// when
let table : Table<usize, usize, bool> = Table::new();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
}
#[test]
fn should_insert_elements_and_return_previous_if_any() {
// given
let mut table = Table::new();
// when
let r1 = table.insert(5, 4, true);
let r2 = table.insert(10, 4, true);
let r3 = table.insert(10, 10, true);
let r4 = table.insert(10, 10, false);
// then
assert!(r1.is_none());
assert!(r2.is_none());
assert!(r3.is_none());
assert!(r4.is_some());
assert!(!table.is_empty());
assert_eq!(r4.unwrap(), true);
assert_eq!(table.len(), 3);
}
#[test]
fn should_remove_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(!table.is_empty());
assert_eq!(table.len(), 1);
// when
let r = table.remove(&5, &4);
// then
assert!(table.is_empty());
assert_eq!(table.len() ,0);
assert_eq!(r.unwrap(), true);
}
#[test]
fn should_return_none_if_trying_to_remove_non_existing_element() {
// given
let mut table : Table<usize, usize, usize> = Table::new();
assert!(table.is_empty());
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_none());
}
#[test]
fn should_clear_row_if_removing_last_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(table.has_row(&5));
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_some());
assert!(!table.has_row(&5));
}
#[test]
fn should_return_element_given_row_and_col() {
// given
let mut table = Table::new();
table.insert(1551, 1234, 123);
// when
let r1 = table.get(&1551, &1234);
let r2 = table.get(&5, &4);
// then
assert!(r1.is_some());
assert!(r2.is_none());
assert_eq!(r1.unwrap(), &123);
}
#[test]
fn should_clear_table() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
assert_eq!(table.len(), 3);
// when
table.clear();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
assert_eq!(table.has_row(&1), false);
assert_eq!(table.has_row(&2), false);
}
#[test]
fn should_return_mutable_row() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
// when
{
let mut row = table.row_mut(&1).unwrap();
row.remove(&1);
row.remove(&2);
}
assert!(table.has_row(&1));
table.clear_if_empty(&1);
// then
assert!(!table.has_row(&1));
assert_eq!(table.len(), 1);
}
}
| {
self.map.contains_key(row)
} | identifier_body |
lib.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// 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/>.
//! A collection associating pair of keys (row and column) with a single value.
use std::hash::Hash;
use std::collections::HashMap;
use std::collections::hash_map::Keys;
/// Structure to hold double-indexed values
///
/// You can obviously use `HashMap<(Row,Col), Val>`, but this structure gives
/// you better access to all `Columns` in Specific `Row`. Namely you can get sub-hashmap
/// `HashMap<Col, Val>` for specific `Row`
#[derive(Default, Debug, PartialEq)]
pub struct Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
map: HashMap<Row, HashMap<Col, Val>>,
}
impl<Row, Col, Val> Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
/// Creates new Table
pub fn new() -> Self {
Table {
map: HashMap::new(),
}
}
/// Returns keys iterator for this Table.
pub fn keys(&self) -> Keys<Row, HashMap<Col, Val>> {
self.map.keys()
}
/// Removes all elements from this Table
pub fn clear(&mut self) {
self.map.clear();
}
/// Returns length of the Table (number of (row, col, val) tuples)
pub fn len(&self) -> usize {
self.map.values().fold(0, |acc, v| acc + v.len())
}
/// Check if there is any element in this Table
pub fn is_empty(&self) -> bool {
self.map.is_empty() || self.map.values().all(|v| v.is_empty())
}
/// Get mutable reference for single Table row.
pub fn row_mut(&mut self, row: &Row) -> Option<&mut HashMap<Col, Val>> {
self.map.get_mut(row)
}
/// Checks if row is defined for that table (note that even if defined it might be empty)
pub fn has_row(&self, row: &Row) -> bool {
self.map.contains_key(row)
}
/// Get immutable reference for single row in this Table
pub fn row(&self, row: &Row) -> Option<&HashMap<Col, Val>> {
self.map.get(row)
}
/// Get element in cell described by `(row, col)`
pub fn get(&self, row: &Row, col: &Col) -> Option<&Val> {
self.map.get(row).and_then(|r| r.get(col))
}
/// Remove value from specific cell
///
/// It will remove the row if it's the last value in it
pub fn remove(&mut self, row: &Row, col: &Col) -> Option<Val> {
let (val, is_empty) = {
let row_map = self.map.get_mut(row);
if let None = row_map {
return None;
}
let mut row_map = row_map.unwrap();
let val = row_map.remove(col);
(val, row_map.is_empty())
};
// Clean row
if is_empty {
self.map.remove(row);
}
val
}
/// Remove given row from Table if there are no values defined in it
///
/// When using `#row_mut` it may happen that all values from some row are drained.
/// Table however will not be aware that row is empty.
/// You can use this method to explicitly remove row entry from the Table.
pub fn clear_if_empty(&mut self, row: &Row) {
let is_empty = self.map.get(row).map_or(false, |m| m.is_empty());
if is_empty {
self.map.remove(row);
}
}
/// Inserts new value to specified cell
///
/// Returns previous value (if any)
pub fn insert(&mut self, row: Row, col: Col, val: Val) -> Option<Val> {
self.map.entry(row).or_insert_with(HashMap::new).insert(col, val)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn should_create_empty_table() {
// when
let table : Table<usize, usize, bool> = Table::new();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
}
#[test]
fn should_insert_elements_and_return_previous_if_any() {
// given
let mut table = Table::new();
// when
let r1 = table.insert(5, 4, true);
let r2 = table.insert(10, 4, true);
let r3 = table.insert(10, 10, true);
let r4 = table.insert(10, 10, false);
// then
assert!(r1.is_none());
assert!(r2.is_none());
assert!(r3.is_none());
assert!(r4.is_some());
assert!(!table.is_empty());
assert_eq!(r4.unwrap(), true);
assert_eq!(table.len(), 3);
}
#[test]
fn should_remove_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(!table.is_empty());
assert_eq!(table.len(), 1);
// when
let r = table.remove(&5, &4);
// then
assert!(table.is_empty());
assert_eq!(table.len() ,0);
assert_eq!(r.unwrap(), true);
}
#[test]
fn should_return_none_if_trying_to_remove_non_existing_element() {
// given
let mut table : Table<usize, usize, usize> = Table::new();
assert!(table.is_empty());
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_none());
}
#[test]
fn should_clear_row_if_removing_last_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(table.has_row(&5));
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_some());
assert!(!table.has_row(&5));
}
#[test]
fn should_return_element_given_row_and_col() {
// given
let mut table = Table::new();
table.insert(1551, 1234, 123);
// when
let r1 = table.get(&1551, &1234);
let r2 = table.get(&5, &4);
// then
assert!(r1.is_some());
assert!(r2.is_none());
assert_eq!(r1.unwrap(), &123);
}
#[test]
fn should_clear_table() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
assert_eq!(table.len(), 3);
// when
table.clear();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
assert_eq!(table.has_row(&1), false);
assert_eq!(table.has_row(&2), false);
}
#[test]
fn should_return_mutable_row() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
// when
{
let mut row = table.row_mut(&1).unwrap();
row.remove(&1);
row.remove(&2);
}
assert!(table.has_row(&1)); | // then
assert!(!table.has_row(&1));
assert_eq!(table.len(), 1);
}
} | table.clear_if_empty(&1);
| random_line_split |
lib.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// 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/>.
//! A collection associating pair of keys (row and column) with a single value.
use std::hash::Hash;
use std::collections::HashMap;
use std::collections::hash_map::Keys;
/// Structure to hold double-indexed values
///
/// You can obviously use `HashMap<(Row,Col), Val>`, but this structure gives
/// you better access to all `Columns` in Specific `Row`. Namely you can get sub-hashmap
/// `HashMap<Col, Val>` for specific `Row`
#[derive(Default, Debug, PartialEq)]
pub struct Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
map: HashMap<Row, HashMap<Col, Val>>,
}
impl<Row, Col, Val> Table<Row, Col, Val>
where Row: Eq + Hash + Clone,
Col: Eq + Hash {
/// Creates new Table
pub fn new() -> Self {
Table {
map: HashMap::new(),
}
}
/// Returns keys iterator for this Table.
pub fn keys(&self) -> Keys<Row, HashMap<Col, Val>> {
self.map.keys()
}
/// Removes all elements from this Table
pub fn clear(&mut self) {
self.map.clear();
}
/// Returns length of the Table (number of (row, col, val) tuples)
pub fn len(&self) -> usize {
self.map.values().fold(0, |acc, v| acc + v.len())
}
/// Check if there is any element in this Table
pub fn is_empty(&self) -> bool {
self.map.is_empty() || self.map.values().all(|v| v.is_empty())
}
/// Get mutable reference for single Table row.
pub fn row_mut(&mut self, row: &Row) -> Option<&mut HashMap<Col, Val>> {
self.map.get_mut(row)
}
/// Checks if row is defined for that table (note that even if defined it might be empty)
pub fn has_row(&self, row: &Row) -> bool {
self.map.contains_key(row)
}
/// Get immutable reference for single row in this Table
pub fn row(&self, row: &Row) -> Option<&HashMap<Col, Val>> {
self.map.get(row)
}
/// Get element in cell described by `(row, col)`
pub fn get(&self, row: &Row, col: &Col) -> Option<&Val> {
self.map.get(row).and_then(|r| r.get(col))
}
/// Remove value from specific cell
///
/// It will remove the row if it's the last value in it
pub fn remove(&mut self, row: &Row, col: &Col) -> Option<Val> {
let (val, is_empty) = {
let row_map = self.map.get_mut(row);
if let None = row_map {
return None;
}
let mut row_map = row_map.unwrap();
let val = row_map.remove(col);
(val, row_map.is_empty())
};
// Clean row
if is_empty |
val
}
/// Remove given row from Table if there are no values defined in it
///
/// When using `#row_mut` it may happen that all values from some row are drained.
/// Table however will not be aware that row is empty.
/// You can use this method to explicitly remove row entry from the Table.
pub fn clear_if_empty(&mut self, row: &Row) {
let is_empty = self.map.get(row).map_or(false, |m| m.is_empty());
if is_empty {
self.map.remove(row);
}
}
/// Inserts new value to specified cell
///
/// Returns previous value (if any)
pub fn insert(&mut self, row: Row, col: Col, val: Val) -> Option<Val> {
self.map.entry(row).or_insert_with(HashMap::new).insert(col, val)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn should_create_empty_table() {
// when
let table : Table<usize, usize, bool> = Table::new();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
}
#[test]
fn should_insert_elements_and_return_previous_if_any() {
// given
let mut table = Table::new();
// when
let r1 = table.insert(5, 4, true);
let r2 = table.insert(10, 4, true);
let r3 = table.insert(10, 10, true);
let r4 = table.insert(10, 10, false);
// then
assert!(r1.is_none());
assert!(r2.is_none());
assert!(r3.is_none());
assert!(r4.is_some());
assert!(!table.is_empty());
assert_eq!(r4.unwrap(), true);
assert_eq!(table.len(), 3);
}
#[test]
fn should_remove_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(!table.is_empty());
assert_eq!(table.len(), 1);
// when
let r = table.remove(&5, &4);
// then
assert!(table.is_empty());
assert_eq!(table.len() ,0);
assert_eq!(r.unwrap(), true);
}
#[test]
fn should_return_none_if_trying_to_remove_non_existing_element() {
// given
let mut table : Table<usize, usize, usize> = Table::new();
assert!(table.is_empty());
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_none());
}
#[test]
fn should_clear_row_if_removing_last_element() {
// given
let mut table = Table::new();
table.insert(5, 4, true);
assert!(table.has_row(&5));
// when
let r = table.remove(&5, &4);
// then
assert!(r.is_some());
assert!(!table.has_row(&5));
}
#[test]
fn should_return_element_given_row_and_col() {
// given
let mut table = Table::new();
table.insert(1551, 1234, 123);
// when
let r1 = table.get(&1551, &1234);
let r2 = table.get(&5, &4);
// then
assert!(r1.is_some());
assert!(r2.is_none());
assert_eq!(r1.unwrap(), &123);
}
#[test]
fn should_clear_table() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
assert_eq!(table.len(), 3);
// when
table.clear();
// then
assert!(table.is_empty());
assert_eq!(table.len(), 0);
assert_eq!(table.has_row(&1), false);
assert_eq!(table.has_row(&2), false);
}
#[test]
fn should_return_mutable_row() {
// given
let mut table = Table::new();
table.insert(1, 1, true);
table.insert(1, 2, false);
table.insert(2, 2, false);
// when
{
let mut row = table.row_mut(&1).unwrap();
row.remove(&1);
row.remove(&2);
}
assert!(table.has_row(&1));
table.clear_if_empty(&1);
// then
assert!(!table.has_row(&1));
assert_eq!(table.len(), 1);
}
}
| {
self.map.remove(row);
} | conditional_block |
keyids.py | KEYIDS = {
"KEY_RESERVED": 0,
"KEY_ESC": 1,
"KEY_1": 2,
"KEY_2": 3,
"KEY_3": 4,
"KEY_4": 5,
"KEY_5": 6,
"KEY_6": 7,
"KEY_7": 8,
"KEY_8": 9,
"KEY_9": 10,
"KEY_0": 11,
"KEY_MINUS": 12,
"KEY_EQUAL": 13,
"KEY_BACKSPACE": 14,
"KEY_TAB": 15,
"KEY_Q": 16,
"KEY_W": 17,
"KEY_E": 18,
"KEY_R": 19,
"KEY_T": 20,
"KEY_Y": 21,
"KEY_U": 22,
"KEY_I": 23,
"KEY_O": 24,
"KEY_P": 25,
"KEY_LEFTBRACE": 26,
"KEY_RIGHTBRACE": 27,
"KEY_ENTER": 28,
"KEY_LEFTCTRL": 29,
"KEY_A": 30,
"KEY_S": 31,
"KEY_D": 32,
"KEY_F": 33,
"KEY_G": 34,
"KEY_H": 35,
"KEY_J": 36,
"KEY_K": 37,
"KEY_L": 38,
"KEY_SEMICOLON": 39,
"KEY_APOSTROPHE": 40,
"KEY_GRAVE": 41,
"KEY_LEFTSHIFT": 42,
"KEY_BACKSLASH": 43,
"KEY_Z": 44,
"KEY_X": 45,
"KEY_C": 46,
"KEY_V": 47,
"KEY_B": 48,
"KEY_N": 49,
"KEY_M": 50,
"KEY_COMMA": 51,
"KEY_DOT": 52,
"KEY_SLASH": 53,
"KEY_RIGHTSHIFT": 54,
"KEY_KPASTERISK": 55,
"KEY_LEFTALT": 56,
"KEY_SPACE": 57,
"KEY_CAPSLOCK": 58,
"KEY_F1": 59,
"KEY_F2": 60,
"KEY_F3": 61,
"KEY_F4": 62,
"KEY_F5": 63,
"KEY_F6": 64,
"KEY_F7": 65,
"KEY_F8": 66,
"KEY_F9": 67,
"KEY_F10": 68,
"KEY_NUMLOCK": 69,
"KEY_SCROLLLOCK": 70,
"KEY_KP7": 71,
"KEY_KP8": 72,
"KEY_KP9": 73,
"KEY_KPMINUS": 74,
"KEY_KP4": 75,
"KEY_KP5": 76,
"KEY_KP6": 77,
"KEY_KPPLUS": 78,
"KEY_KP1": 79,
"KEY_KP2": 80,
"KEY_KP3": 81,
"KEY_KP0": 82,
"KEY_KPDOT": 83,
"KEY_103RD": 84,
"KEY_F13": 85,
"KEY_102ND": 86,
"KEY_F11": 87,
"KEY_F12": 88,
"KEY_F14": 89,
"KEY_F15": 90,
"KEY_F16": 91,
"KEY_F17": 92,
"KEY_F18": 93,
"KEY_F19": 94,
"KEY_F20": 95,
"KEY_KPENTER": 96,
"KEY_RIGHTCTRL": 97,
"KEY_KPSLASH": 98,
"KEY_SYSRQ": 99,
"KEY_RIGHTALT": 100,
"KEY_LINEFEED": 101,
"KEY_HOME": 102,
"KEY_UP": 103,
"KEY_PAGEUP": 104,
"KEY_LEFT": 105,
"KEY_RIGHT": 106,
"KEY_END": 107,
"KEY_DOWN": 108,
"KEY_PAGEDOWN": 109,
"KEY_INSERT": 110,
"KEY_DELETE": 111,
"KEY_MACRO": 112,
"KEY_MUTE": 113,
"KEY_VOLUMEDOWN": 114,
"KEY_VOLUMEUP": 115,
"KEY_POWER": 116,
"KEY_KPEQUAL": 117,
"KEY_KPPLUSMINUS": 118,
"KEY_PAUSE": 119,
"KEY_F21": 120,
"KEY_F22": 121,
"KEY_F23": 122,
"KEY_F24": 123,
"KEY_KPCOMMA": 124,
"KEY_LEFTMETA": 125,
"KEY_RIGHTMETA": 126,
"KEY_COMPOSE": 127,
"KEY_STOP": 128,
"KEY_AGAIN": 129,
"KEY_PROPS": 130,
"KEY_UNDO": 131,
"KEY_FRONT": 132,
"KEY_COPY": 133,
"KEY_OPEN": 134,
"KEY_PASTE": 135, | "KEY_CUT": 137,
"KEY_HELP": 138,
"KEY_MENU": 139,
"KEY_CALC": 140,
"KEY_SETUP": 141,
"KEY_SLEEP": 142,
"KEY_WAKEUP": 143,
"KEY_FILE": 144,
"KEY_SENDFILE": 145,
"KEY_DELETEFILE": 146,
"KEY_XFER": 147,
"KEY_PROG1": 148,
"KEY_PROG2": 149,
"KEY_WWW": 150,
"KEY_MSDOS": 151,
"KEY_COFFEE": 152,
"KEY_DIRECTION": 153,
"KEY_CYCLEWINDOWS": 154,
"KEY_MAIL": 155,
"KEY_BOOKMARKS": 156,
"KEY_COMPUTER": 157,
"KEY_BACK": 158,
"KEY_FORWARD": 159,
"KEY_CLOSECD": 160,
"KEY_EJECTCD": 161,
"KEY_EJECTCLOSECD": 162,
"KEY_NEXTSONG": 163,
"KEY_PLAYPAUSE": 164,
"KEY_PREVIOUSSONG": 165,
"KEY_STOPCD": 166,
"KEY_RECORD": 167,
"KEY_REWIND": 168,
"KEY_PHONE": 169,
"KEY_ISO": 170,
"KEY_CONFIG": 171,
"KEY_HOMEPAGE": 172,
"KEY_REFRESH": 173,
"KEY_EXIT": 174,
"KEY_MOVE": 175,
"KEY_EDIT": 176,
"KEY_SCROLLUP": 177,
"KEY_SCROLLDOWN": 178,
"KEY_KPLEFTPAREN": 179,
"KEY_KPRIGHTPAREN": 180,
"KEY_INTL1": 181,
"KEY_INTL2": 182,
"KEY_INTL3": 183,
"KEY_INTL4": 184,
"KEY_INTL5": 185,
"KEY_INTL6": 186,
"KEY_INTL7": 187,
"KEY_INTL8": 188,
"KEY_INTL9": 189,
"KEY_LANG1": 190,
"KEY_LANG2": 191,
"KEY_LANG3": 192,
"KEY_LANG4": 193,
"KEY_LANG5": 194,
"KEY_LANG6": 195,
"KEY_LANG7": 196,
"KEY_LANG8": 197,
"KEY_LANG9": 198,
"KEY_PLAYCD": 200,
"KEY_PAUSECD": 201,
"KEY_PROG3": 202,
"KEY_PROG4": 203,
"KEY_SUSPEND": 205,
"KEY_CLOSE": 206,
"KEY_PLAY": 207,
"KEY_FASTFORWARD": 208,
"KEY_BASSBOOST": 209,
"KEY_PRINT": 210,
"KEY_HP": 211,
"KEY_CAMERA": 212,
"KEY_SOUND": 213,
"KEY_QUESTION": 214,
"KEY_EMAIL": 215,
"KEY_CHAT": 216,
"KEY_SEARCH": 217,
"KEY_CONNECT": 218,
"KEY_FINANCE": 219,
"KEY_SPORT": 220,
"KEY_SHOP": 221,
"KEY_ALTERASE": 222,
"KEY_CANCEL": 223,
"KEY_BRIGHTNESSDOWN": 224,
"KEY_BRIGHTNESSUP": 225,
"KEY_MEDIA": 226,
"KEY_VMODE": 227,
"KEY_LAN": 238,
"KEY_UNKNOWN": 240,
"BtnA": 304,
"BtnY": 308,
"BtnB": 305,
"BtnX": 307,
"BtnTL": 310,
"BtnTR": 311,
"KEY_OK": 352,
"KEY_SELECT": 353,
"KEY_GOTO": 354,
"KEY_CLEAR": 355,
"KEY_POWER2": 356,
"KEY_OPTION": 357,
"KEY_INFO": 358,
"KEY_TIME": 359,
"KEY_VENDOR": 360,
"KEY_ARCHIVE": 361,
"KEY_PROGRAM": 362,
"KEY_CHANNEL": 363,
"KEY_FAVORITES": 364,
"KEY_EPG": 365,
"KEY_PVR": 366,
"KEY_MHP": 367,
"KEY_LANGUAGE": 368,
"KEY_TITLE": 369,
"KEY_SUBTITLE": 370,
"KEY_ANGLE": 371,
"KEY_ZOOM": 372,
"KEY_MODE": 373,
"KEY_KEYBOARD": 374,
"KEY_SCREEN": 375,
"KEY_PC": 376,
"KEY_TV": 377,
"KEY_TV2": 378,
"KEY_VCR": 379,
"KEY_VCR2": 380,
"KEY_SAT": 381,
"KEY_SAT2": 382,
"KEY_CD": 383,
"KEY_TAPE": 384,
"KEY_RADIO": 385,
"KEY_TUNER": 386,
"KEY_PLAYER": 387,
"KEY_TEXT": 388,
"KEY_DVD": 389,
"KEY_AUX": 390,
"KEY_MP3": 391,
"KEY_AUDIO": 392,
"KEY_VIDEO": 393,
"KEY_DIRECTORY": 394,
"KEY_LIST": 395,
"KEY_MEMO": 396,
"KEY_CALENDAR": 397,
"KEY_RED": 398,
"KEY_GREEN": 399,
"KEY_YELLOW": 400,
"KEY_BLUE": 401,
"KEY_CHANNELUP": 402,
"KEY_CHANNELDOWN": 403,
"KEY_FIRST": 404,
"KEY_LAST": 405,
"KEY_AB": 406,
"KEY_NEXT": 407,
"KEY_RESTART": 408,
"KEY_SLOW": 409,
"KEY_SHUFFLE": 410,
"KEY_BREAK": 411,
"KEY_PREVIOUS": 412,
"KEY_DIGITS": 413,
"KEY_TEEN": 414,
"KEY_TWEN": 415,
"KEY_CONTEXT_MENU": 438,
"KEY_DEL_EOL": 448,
"KEY_DEL_EOS": 449,
"KEY_INS_LINE": 450,
"KEY_DEL_LINE": 451,
"KEY_ASCII": 510,
"KEY_MAX": 511,
"BTN_0": 256,
"BTN_1": 257,
} | "KEY_FIND": 136, | random_line_split |
orthog.py | """
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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.
CVXPY 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 CVXPY. If not, see <http://www.gnu.org/licenses/>.
"""
from .noncvx_variable import NonCvxVariable
import cvxpy as cp
import numpy as np
class Orthog(NonCvxVariable):
""" A variable satisfying X^TX = I. """
def __init__(self, size, *args, **kwargs):
super().__init__(shape=(size, size), *args, **kwargs)
def init_z(self, random):
"""Initializes the value of the replicant variable.
"""
self.z.value = np.zeros(self.shape)
def _project(self, matrix):
|
# Constrain all entries to be the value in the matrix.
def _restrict(self, matrix):
return [self == matrix]
def relax(self):
"""Relaxation [I X; X^T I] is PSD.
"""
rows, cols = self.shape
constr = super(Orthog, self).relax()
mat = cp.bmat([[np.eye(rows), self], [X.T, np.eye(cols)]])
return constr + [mat >> 0]
| """All singular values except k-largest (by magnitude) set to zero.
"""
U, s, V = np.linalg.svd(matrix)
s[:] = 1
return U.dot(np.diag(s)).dot(V) | identifier_body |
orthog.py | """
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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.
CVXPY 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 CVXPY. If not, see <http://www.gnu.org/licenses/>.
"""
from .noncvx_variable import NonCvxVariable
import cvxpy as cp
import numpy as np
class Orthog(NonCvxVariable):
""" A variable satisfying X^TX = I. """
def __init__(self, size, *args, **kwargs):
super().__init__(shape=(size, size), *args, **kwargs)
def | (self, random):
"""Initializes the value of the replicant variable.
"""
self.z.value = np.zeros(self.shape)
def _project(self, matrix):
"""All singular values except k-largest (by magnitude) set to zero.
"""
U, s, V = np.linalg.svd(matrix)
s[:] = 1
return U.dot(np.diag(s)).dot(V)
# Constrain all entries to be the value in the matrix.
def _restrict(self, matrix):
return [self == matrix]
def relax(self):
"""Relaxation [I X; X^T I] is PSD.
"""
rows, cols = self.shape
constr = super(Orthog, self).relax()
mat = cp.bmat([[np.eye(rows), self], [X.T, np.eye(cols)]])
return constr + [mat >> 0]
| init_z | identifier_name |
orthog.py | """
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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.
CVXPY 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 CVXPY. If not, see <http://www.gnu.org/licenses/>.
"""
from .noncvx_variable import NonCvxVariable
import cvxpy as cp
import numpy as np
| """ A variable satisfying X^TX = I. """
def __init__(self, size, *args, **kwargs):
super().__init__(shape=(size, size), *args, **kwargs)
def init_z(self, random):
"""Initializes the value of the replicant variable.
"""
self.z.value = np.zeros(self.shape)
def _project(self, matrix):
"""All singular values except k-largest (by magnitude) set to zero.
"""
U, s, V = np.linalg.svd(matrix)
s[:] = 1
return U.dot(np.diag(s)).dot(V)
# Constrain all entries to be the value in the matrix.
def _restrict(self, matrix):
return [self == matrix]
def relax(self):
"""Relaxation [I X; X^T I] is PSD.
"""
rows, cols = self.shape
constr = super(Orthog, self).relax()
mat = cp.bmat([[np.eye(rows), self], [X.T, np.eye(cols)]])
return constr + [mat >> 0] | class Orthog(NonCvxVariable): | random_line_split |
karma.conf.js | // Karma configuration
// Generated on Thu Oct 01 2015 17:56:10 GMT+0900 (JST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'browserify'],
// list of files / patterns to load in the browser
files: [
'spec/**/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'src/js/**/*.js': ['browserify'],
'spec/**/*.js': ['browserify']
},
browserify: {
debug: true,
transform: ['rewireify', 'babelify']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['mocha'],
// web server port
port: 9876,
| // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// To prevent this error: https://github.com/karma-runner/karma/issues/598
browserNoActivityTimeout: 60000
})
} | // enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging | random_line_split |
replication_lib.py | """An implementation of the ReplicationConfig proto interface."""
from __future__ import print_function
import json
import os
import shutil
import sys
from chromite.api.gen.config import replication_config_pb2
from chromite.lib import constants
from chromite.lib import cros_logging as logging
from chromite.lib import osutils
from chromite.utils import field_mask_util
assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
def _ValidateFileReplicationRule(rule):
"""Raises an error if a FileReplicationRule is invalid.
For example, checks that if REPLICATION_TYPE_FILTER, destination_fields
are specified.
Args:
rule: (FileReplicationRule) The rule to validate.
"""
if rule.file_type == replication_config_pb2.FILE_TYPE_JSON:
if rule.replication_type != replication_config_pb2.REPLICATION_TYPE_FILTER:
raise ValueError(
'Rule for JSON source %s must use REPLICATION_TYPE_FILTER.' %
rule.source_path)
elif rule.file_type == replication_config_pb2.FILE_TYPE_OTHER:
if rule.replication_type != replication_config_pb2.REPLICATION_TYPE_COPY:
raise ValueError('Rule for source %s must use REPLICATION_TYPE_COPY.' %
rule.source_path)
else:
raise NotImplementedError('Replicate not implemented for file type %s' %
rule.file_type)
if rule.replication_type == replication_config_pb2.REPLICATION_TYPE_COPY:
if rule.destination_fields.paths:
raise ValueError(
'Rule with REPLICATION_TYPE_COPY cannot use destination_fields.')
elif rule.replication_type == replication_config_pb2.REPLICATION_TYPE_FILTER:
if not rule.destination_fields.paths:
raise ValueError(
'Rule with REPLICATION_TYPE_FILTER must use destination_fields.')
else:
raise NotImplementedError(
'Replicate not implemented for replication type %s' %
rule.replication_type)
if os.path.isabs(rule.source_path) or os.path.isabs(rule.destination_path):
raise ValueError(
'Only paths relative to the source root are allowed. In rule: %s' %
rule)
def _ApplyStringReplacementRules(destination_path, rules):
"""Read the file at destination path, apply rules, and write a new file.
Args:
destination_path: (str) Path to the destination file to read. The new file
will also be written at this path.
rules: (list[StringReplacementRule]) Rules to apply. Must not be empty.
"""
assert rules
with open(destination_path, 'r') as f:
dst_data = f.read()
for string_replacement_rule in rules:
dst_data = dst_data.replace(string_replacement_rule.before,
string_replacement_rule.after)
with open(destination_path, 'w') as f:
f.write(dst_data)
def Replicate(replication_config):
"""Run the replication described in replication_config.
Args:
replication_config: (ReplicationConfig) Describes the replication to run.
"""
# Validate all rules before any of them are run, to decrease chance of ending
# with a partial replication.
for rule in replication_config.file_replication_rules:
_ValidateFileReplicationRule(rule)
for rule in replication_config.file_replication_rules:
logging.info('Processing FileReplicationRule: %s', rule)
src = os.path.join(constants.SOURCE_ROOT, rule.source_path)
dst = os.path.join(constants.SOURCE_ROOT, rule.destination_path)
osutils.SafeMakedirs(os.path.dirname(dst))
if rule.file_type == replication_config_pb2.FILE_TYPE_JSON:
assert (rule.replication_type ==
replication_config_pb2.REPLICATION_TYPE_FILTER)
assert rule.destination_fields.paths
with open(src, 'r') as f:
source_json = json.load(f)
try:
source_device_configs = source_json['chromeos']['configs']
except KeyError:
raise NotImplementedError(
('Currently only ChromeOS Configs are supported (expected file %s '
'to have a list at "$.chromeos.configs")') % src)
destination_device_configs = []
for source_device_config in source_device_configs:
destination_device_configs.append(
field_mask_util.CreateFilteredDict(rule.destination_fields,
source_device_config))
destination_json = {'chromeos': {'configs': destination_device_configs}}
logging.info('Writing filtered JSON source to %s', dst)
with open(dst, 'w') as f:
# Use the print function, so the file ends in a newline.
print(
json.dumps(
destination_json,
sort_keys=True,
indent=2,
separators=(',', ': ')),
file=f)
else:
assert rule.file_type == replication_config_pb2.FILE_TYPE_OTHER
assert (
rule.replication_type == replication_config_pb2.REPLICATION_TYPE_COPY)
assert not rule.destination_fields.paths
logging.info('Copying full file from %s to %s', src, dst)
shutil.copy2(src, dst)
if rule.string_replacement_rules:
_ApplyStringReplacementRules(dst, rule.string_replacement_rules) | # -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
| random_line_split | |
replication_lib.py | # -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""An implementation of the ReplicationConfig proto interface."""
from __future__ import print_function
import json
import os
import shutil
import sys
from chromite.api.gen.config import replication_config_pb2
from chromite.lib import constants
from chromite.lib import cros_logging as logging
from chromite.lib import osutils
from chromite.utils import field_mask_util
assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
def _ValidateFileReplicationRule(rule):
|
def _ApplyStringReplacementRules(destination_path, rules):
"""Read the file at destination path, apply rules, and write a new file.
Args:
destination_path: (str) Path to the destination file to read. The new file
will also be written at this path.
rules: (list[StringReplacementRule]) Rules to apply. Must not be empty.
"""
assert rules
with open(destination_path, 'r') as f:
dst_data = f.read()
for string_replacement_rule in rules:
dst_data = dst_data.replace(string_replacement_rule.before,
string_replacement_rule.after)
with open(destination_path, 'w') as f:
f.write(dst_data)
def Replicate(replication_config):
"""Run the replication described in replication_config.
Args:
replication_config: (ReplicationConfig) Describes the replication to run.
"""
# Validate all rules before any of them are run, to decrease chance of ending
# with a partial replication.
for rule in replication_config.file_replication_rules:
_ValidateFileReplicationRule(rule)
for rule in replication_config.file_replication_rules:
logging.info('Processing FileReplicationRule: %s', rule)
src = os.path.join(constants.SOURCE_ROOT, rule.source_path)
dst = os.path.join(constants.SOURCE_ROOT, rule.destination_path)
osutils.SafeMakedirs(os.path.dirname(dst))
if rule.file_type == replication_config_pb2.FILE_TYPE_JSON:
assert (rule.replication_type ==
replication_config_pb2.REPLICATION_TYPE_FILTER)
assert rule.destination_fields.paths
with open(src, 'r') as f:
source_json = json.load(f)
try:
source_device_configs = source_json['chromeos']['configs']
except KeyError:
raise NotImplementedError(
('Currently only ChromeOS Configs are supported (expected file %s '
'to have a list at "$.chromeos.configs")') % src)
destination_device_configs = []
for source_device_config in source_device_configs:
destination_device_configs.append(
field_mask_util.CreateFilteredDict(rule.destination_fields,
source_device_config))
destination_json = {'chromeos': {'configs': destination_device_configs}}
logging.info('Writing filtered JSON source to %s', dst)
with open(dst, 'w') as f:
# Use the print function, so the file ends in a newline.
print(
json.dumps(
destination_json,
sort_keys=True,
indent=2,
separators=(',', ': ')),
file=f)
else:
assert rule.file_type == replication_config_pb2.FILE_TYPE_OTHER
assert (
rule.replication_type == replication_config_pb2.REPLICATION_TYPE_COPY)
assert not rule.destination_fields.paths
logging.info('Copying full file from %s to %s', src, dst)
shutil.copy2(src, dst)
if rule.string_replacement_rules:
_ApplyStringReplacementRules(dst, rule.string_replacement_rules)
| """Raises an error if a FileReplicationRule is invalid.
For example, checks that if REPLICATION_TYPE_FILTER, destination_fields
are specified.
Args:
rule: (FileReplicationRule) The rule to validate.
"""
if rule.file_type == replication_config_pb2.FILE_TYPE_JSON:
if rule.replication_type != replication_config_pb2.REPLICATION_TYPE_FILTER:
raise ValueError(
'Rule for JSON source %s must use REPLICATION_TYPE_FILTER.' %
rule.source_path)
elif rule.file_type == replication_config_pb2.FILE_TYPE_OTHER:
if rule.replication_type != replication_config_pb2.REPLICATION_TYPE_COPY:
raise ValueError('Rule for source %s must use REPLICATION_TYPE_COPY.' %
rule.source_path)
else:
raise NotImplementedError('Replicate not implemented for file type %s' %
rule.file_type)
if rule.replication_type == replication_config_pb2.REPLICATION_TYPE_COPY:
if rule.destination_fields.paths:
raise ValueError(
'Rule with REPLICATION_TYPE_COPY cannot use destination_fields.')
elif rule.replication_type == replication_config_pb2.REPLICATION_TYPE_FILTER:
if not rule.destination_fields.paths:
raise ValueError(
'Rule with REPLICATION_TYPE_FILTER must use destination_fields.')
else:
raise NotImplementedError(
'Replicate not implemented for replication type %s' %
rule.replication_type)
if os.path.isabs(rule.source_path) or os.path.isabs(rule.destination_path):
raise ValueError(
'Only paths relative to the source root are allowed. In rule: %s' %
rule) | identifier_body |
replication_lib.py | # -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""An implementation of the ReplicationConfig proto interface."""
from __future__ import print_function
import json
import os
import shutil
import sys
from chromite.api.gen.config import replication_config_pb2
from chromite.lib import constants
from chromite.lib import cros_logging as logging
from chromite.lib import osutils
from chromite.utils import field_mask_util
assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
def _ValidateFileReplicationRule(rule):
"""Raises an error if a FileReplicationRule is invalid.
For example, checks that if REPLICATION_TYPE_FILTER, destination_fields
are specified.
Args:
rule: (FileReplicationRule) The rule to validate.
"""
if rule.file_type == replication_config_pb2.FILE_TYPE_JSON:
if rule.replication_type != replication_config_pb2.REPLICATION_TYPE_FILTER:
raise ValueError(
'Rule for JSON source %s must use REPLICATION_TYPE_FILTER.' %
rule.source_path)
elif rule.file_type == replication_config_pb2.FILE_TYPE_OTHER:
if rule.replication_type != replication_config_pb2.REPLICATION_TYPE_COPY:
raise ValueError('Rule for source %s must use REPLICATION_TYPE_COPY.' %
rule.source_path)
else:
raise NotImplementedError('Replicate not implemented for file type %s' %
rule.file_type)
if rule.replication_type == replication_config_pb2.REPLICATION_TYPE_COPY:
if rule.destination_fields.paths:
raise ValueError(
'Rule with REPLICATION_TYPE_COPY cannot use destination_fields.')
elif rule.replication_type == replication_config_pb2.REPLICATION_TYPE_FILTER:
if not rule.destination_fields.paths:
raise ValueError(
'Rule with REPLICATION_TYPE_FILTER must use destination_fields.')
else:
raise NotImplementedError(
'Replicate not implemented for replication type %s' %
rule.replication_type)
if os.path.isabs(rule.source_path) or os.path.isabs(rule.destination_path):
raise ValueError(
'Only paths relative to the source root are allowed. In rule: %s' %
rule)
def _ApplyStringReplacementRules(destination_path, rules):
"""Read the file at destination path, apply rules, and write a new file.
Args:
destination_path: (str) Path to the destination file to read. The new file
will also be written at this path.
rules: (list[StringReplacementRule]) Rules to apply. Must not be empty.
"""
assert rules
with open(destination_path, 'r') as f:
dst_data = f.read()
for string_replacement_rule in rules:
dst_data = dst_data.replace(string_replacement_rule.before,
string_replacement_rule.after)
with open(destination_path, 'w') as f:
f.write(dst_data)
def Replicate(replication_config):
"""Run the replication described in replication_config.
Args:
replication_config: (ReplicationConfig) Describes the replication to run.
"""
# Validate all rules before any of them are run, to decrease chance of ending
# with a partial replication.
for rule in replication_config.file_replication_rules:
_ValidateFileReplicationRule(rule)
for rule in replication_config.file_replication_rules:
logging.info('Processing FileReplicationRule: %s', rule)
src = os.path.join(constants.SOURCE_ROOT, rule.source_path)
dst = os.path.join(constants.SOURCE_ROOT, rule.destination_path)
osutils.SafeMakedirs(os.path.dirname(dst))
if rule.file_type == replication_config_pb2.FILE_TYPE_JSON:
|
else:
assert rule.file_type == replication_config_pb2.FILE_TYPE_OTHER
assert (
rule.replication_type == replication_config_pb2.REPLICATION_TYPE_COPY)
assert not rule.destination_fields.paths
logging.info('Copying full file from %s to %s', src, dst)
shutil.copy2(src, dst)
if rule.string_replacement_rules:
_ApplyStringReplacementRules(dst, rule.string_replacement_rules)
| assert (rule.replication_type ==
replication_config_pb2.REPLICATION_TYPE_FILTER)
assert rule.destination_fields.paths
with open(src, 'r') as f:
source_json = json.load(f)
try:
source_device_configs = source_json['chromeos']['configs']
except KeyError:
raise NotImplementedError(
('Currently only ChromeOS Configs are supported (expected file %s '
'to have a list at "$.chromeos.configs")') % src)
destination_device_configs = []
for source_device_config in source_device_configs:
destination_device_configs.append(
field_mask_util.CreateFilteredDict(rule.destination_fields,
source_device_config))
destination_json = {'chromeos': {'configs': destination_device_configs}}
logging.info('Writing filtered JSON source to %s', dst)
with open(dst, 'w') as f:
# Use the print function, so the file ends in a newline.
print(
json.dumps(
destination_json,
sort_keys=True,
indent=2,
separators=(',', ': ')),
file=f) | conditional_block |
replication_lib.py | # -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""An implementation of the ReplicationConfig proto interface."""
from __future__ import print_function
import json
import os
import shutil
import sys
from chromite.api.gen.config import replication_config_pb2
from chromite.lib import constants
from chromite.lib import cros_logging as logging
from chromite.lib import osutils
from chromite.utils import field_mask_util
assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
def _ValidateFileReplicationRule(rule):
"""Raises an error if a FileReplicationRule is invalid.
For example, checks that if REPLICATION_TYPE_FILTER, destination_fields
are specified.
Args:
rule: (FileReplicationRule) The rule to validate.
"""
if rule.file_type == replication_config_pb2.FILE_TYPE_JSON:
if rule.replication_type != replication_config_pb2.REPLICATION_TYPE_FILTER:
raise ValueError(
'Rule for JSON source %s must use REPLICATION_TYPE_FILTER.' %
rule.source_path)
elif rule.file_type == replication_config_pb2.FILE_TYPE_OTHER:
if rule.replication_type != replication_config_pb2.REPLICATION_TYPE_COPY:
raise ValueError('Rule for source %s must use REPLICATION_TYPE_COPY.' %
rule.source_path)
else:
raise NotImplementedError('Replicate not implemented for file type %s' %
rule.file_type)
if rule.replication_type == replication_config_pb2.REPLICATION_TYPE_COPY:
if rule.destination_fields.paths:
raise ValueError(
'Rule with REPLICATION_TYPE_COPY cannot use destination_fields.')
elif rule.replication_type == replication_config_pb2.REPLICATION_TYPE_FILTER:
if not rule.destination_fields.paths:
raise ValueError(
'Rule with REPLICATION_TYPE_FILTER must use destination_fields.')
else:
raise NotImplementedError(
'Replicate not implemented for replication type %s' %
rule.replication_type)
if os.path.isabs(rule.source_path) or os.path.isabs(rule.destination_path):
raise ValueError(
'Only paths relative to the source root are allowed. In rule: %s' %
rule)
def _ApplyStringReplacementRules(destination_path, rules):
"""Read the file at destination path, apply rules, and write a new file.
Args:
destination_path: (str) Path to the destination file to read. The new file
will also be written at this path.
rules: (list[StringReplacementRule]) Rules to apply. Must not be empty.
"""
assert rules
with open(destination_path, 'r') as f:
dst_data = f.read()
for string_replacement_rule in rules:
dst_data = dst_data.replace(string_replacement_rule.before,
string_replacement_rule.after)
with open(destination_path, 'w') as f:
f.write(dst_data)
def | (replication_config):
"""Run the replication described in replication_config.
Args:
replication_config: (ReplicationConfig) Describes the replication to run.
"""
# Validate all rules before any of them are run, to decrease chance of ending
# with a partial replication.
for rule in replication_config.file_replication_rules:
_ValidateFileReplicationRule(rule)
for rule in replication_config.file_replication_rules:
logging.info('Processing FileReplicationRule: %s', rule)
src = os.path.join(constants.SOURCE_ROOT, rule.source_path)
dst = os.path.join(constants.SOURCE_ROOT, rule.destination_path)
osutils.SafeMakedirs(os.path.dirname(dst))
if rule.file_type == replication_config_pb2.FILE_TYPE_JSON:
assert (rule.replication_type ==
replication_config_pb2.REPLICATION_TYPE_FILTER)
assert rule.destination_fields.paths
with open(src, 'r') as f:
source_json = json.load(f)
try:
source_device_configs = source_json['chromeos']['configs']
except KeyError:
raise NotImplementedError(
('Currently only ChromeOS Configs are supported (expected file %s '
'to have a list at "$.chromeos.configs")') % src)
destination_device_configs = []
for source_device_config in source_device_configs:
destination_device_configs.append(
field_mask_util.CreateFilteredDict(rule.destination_fields,
source_device_config))
destination_json = {'chromeos': {'configs': destination_device_configs}}
logging.info('Writing filtered JSON source to %s', dst)
with open(dst, 'w') as f:
# Use the print function, so the file ends in a newline.
print(
json.dumps(
destination_json,
sort_keys=True,
indent=2,
separators=(',', ': ')),
file=f)
else:
assert rule.file_type == replication_config_pb2.FILE_TYPE_OTHER
assert (
rule.replication_type == replication_config_pb2.REPLICATION_TYPE_COPY)
assert not rule.destination_fields.paths
logging.info('Copying full file from %s to %s', src, dst)
shutil.copy2(src, dst)
if rule.string_replacement_rules:
_ApplyStringReplacementRules(dst, rule.string_replacement_rules)
| Replicate | identifier_name |
account.service.ts | import { HttpClient, HttpErrorResponse, HttpHeaders } from "@angular/common/http";
import { Account } from "../models/account.model"
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { WIMM_API_URL } from "../../wimm-constants";
@Injectable()
export class AccountService {
constructor(
private http: HttpClient,
) { }
| (): Observable<Account[]> {
let url = WIMM_API_URL + "accounts";
return this.http.get<Account[]>(
url, {
headers: new HttpHeaders().set('Authorization', 'token 0123456789abcdef')
}
)
// return this.http.get(API_URL + "accounts").subscribe(
// result => { return result as Account },
// error => { },
// () => { }
// );
}
getAccount(id: number): Promise<Account> {
return Promise.resolve(new Account(id, "short name", "fully callified name", null, null));
}
}
| getAccounts | identifier_name |
account.service.ts | import { HttpClient, HttpErrorResponse, HttpHeaders } from "@angular/common/http";
import { Account } from "../models/account.model"
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { WIMM_API_URL } from "../../wimm-constants";
@Injectable()
export class AccountService {
constructor(
private http: HttpClient,
) { }
getAccounts(): Observable<Account[]> {
let url = WIMM_API_URL + "accounts";
return this.http.get<Account[]>( |
// return this.http.get(API_URL + "accounts").subscribe(
// result => { return result as Account },
// error => { },
// () => { }
// );
}
getAccount(id: number): Promise<Account> {
return Promise.resolve(new Account(id, "short name", "fully callified name", null, null));
}
} | url, {
headers: new HttpHeaders().set('Authorization', 'token 0123456789abcdef')
}
) | random_line_split |
pymatrix.py | import math
import copy
def print_matrix(matrix):
"""
This function prettyprints a matrix
:param matrix: The matrix to prettyprint
"""
for i in range(len(matrix)):
print(matrix[i])
def transpose(matrix):
"""
This function transposes a matrix
:param matrix: The matrix to transpose
:return: The transposed matrix
"""
num_cols = len(matrix[0])
trans = []
for i in range(num_cols):
temp = []
for row in matrix:
temp.append(row[i])
trans.append(temp)
return trans
def minor_matrix(matrix, row_index, col_index):
"""
This function calculates the minor of a matrix for a given row and column
index. The matrix should be a square matrix, and the row and column
should be positive and smaller than the width and height of the matrix.
:param matrix: The matrix to calculate the minor
:param row_index: The row index of the minor to calculate
:param col_index: The column index of the minor to calculate
:return: The minor for the given row and column
"""
minor = matrix
num_rows = len(matrix)
num_cols = len(matrix[0])
if num_cols != num_rows:
raise ValueError("You should pass a square matrix")
if row_index > num_rows or col_index > num_cols or row_index < 1 or col_index < 1:
raise ValueError("Invalid row or column")
# remove the specified row
minor.pop(row_index - 1)
# remove the specified column
for row in minor:
row.pop(col_index - 1)
return minor
def determinant(matrix):
"""
This function calculates the determinant of a square matrix.
:param m_copy: The matrix to find the determinant
:return: The determinant of the matrix
"""
num_rows = len(matrix)
num_cols = len(matrix[0])
if num_cols != num_rows:
raise ValueError("You should pass a square matrix")
dim = num_cols
det = 0
if dim == 1:
return matrix[0][0]
if dim == 2:
det = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
return det
for j in range(dim):
m_copy = copy.deepcopy(matrix)
minor = minor_matrix(m_copy, 1, j+1)
d = determinant(minor)
det += matrix[0][j] * d * math.pow(-1, j)
return det
def inverse(matrix):
"""
This function inverts a square matrix. If the matrix is not square,
it returns nothing
:param matrix: The matrix to invert
:return: The inverse of the matrix passed as parameter
"""
num_rows = len(matrix)
num_cols = len(matrix[0])
if num_rows != num_cols:
raise ValueError("You should pass a square matrix")
|
if denom == 0:
raise ValueError("The determinant is 0. Can't invert matrix")
cofactors = [] # the matrix of cofactors, transposed
for i in range(dim):
cofactor_row = []
for j in range(dim):
m_copy = copy.deepcopy(matrix)
minor = minor_matrix(m_copy, j+1, i+1)
minor_det = determinant(minor) * math.pow(-1, i + j)
cofactor_row.append(minor_det)
cofactors.append(cofactor_row)
# multiply every cofactor with 1/denom
scalar_multiply(cofactors, 1 / denom)
return cofactors
def scalar_multiply(matrix, const):
"""
This function makes the scalar multiplication between a matrix and a number.
:param matrix: The matrix to multiply
:param const: The constant number which will multiply the matrix
:return: The result of the multiplication
"""
for i in range(len(matrix)):
for j in range(len(matrix[0])):
matrix[i][j] *= const
return matrix
def multiply(matrix1, matrix2):
"""
This function multiplies two matrices. In order to multiply, it makes sure
the width of matrix1 is the same as the height of matrix2
:param matrix1: Left matrix
:param matrix2: Right matrix
:return: The product matrix of the multiplication
"""
width1 = len(matrix1[0])
height2 = len(matrix2)
if width1 != height2:
raise ValueError("Can't multiply these matrices")
length = len(matrix1)
width = len(matrix2[0])
product_matrix = [] # product_matrix = matrix_A * matrix_B
for i in range(length):
product_row = [] # one row of product_matrix
for j in range(width):
val = 0
for a in range(height2):
val += matrix1[i][a] * matrix2[a][j]
product_row.append(val)
product_matrix.append(product_row)
return product_matrix
def linear_solver(coef, const):
"""
This function solves a system of linear equations of the standard form Ax = B
:param coef: The matrix of coefficients, A
:param const: The matrix of constant terms, B
:returns: A list of the solutions
"""
if len(coef) == 2:
y = (const[0][0] * coef[1][0] - coef[0][0] * const[1][0]) / (-coef[0][0] * coef[1][1] + coef[1][0] * coef[0][1])
x = (const[1][0] - coef[1][1] * y) / coef[1][0]
return [x, y]
return multiply(inverse(coef), const) | dim = num_rows
denom = determinant(matrix) | random_line_split |
pymatrix.py | import math
import copy
def print_matrix(matrix):
"""
This function prettyprints a matrix
:param matrix: The matrix to prettyprint
"""
for i in range(len(matrix)):
print(matrix[i])
def transpose(matrix):
"""
This function transposes a matrix
:param matrix: The matrix to transpose
:return: The transposed matrix
"""
num_cols = len(matrix[0])
trans = []
for i in range(num_cols):
temp = []
for row in matrix:
temp.append(row[i])
trans.append(temp)
return trans
def minor_matrix(matrix, row_index, col_index):
|
def determinant(matrix):
"""
This function calculates the determinant of a square matrix.
:param m_copy: The matrix to find the determinant
:return: The determinant of the matrix
"""
num_rows = len(matrix)
num_cols = len(matrix[0])
if num_cols != num_rows:
raise ValueError("You should pass a square matrix")
dim = num_cols
det = 0
if dim == 1:
return matrix[0][0]
if dim == 2:
det = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
return det
for j in range(dim):
m_copy = copy.deepcopy(matrix)
minor = minor_matrix(m_copy, 1, j+1)
d = determinant(minor)
det += matrix[0][j] * d * math.pow(-1, j)
return det
def inverse(matrix):
"""
This function inverts a square matrix. If the matrix is not square,
it returns nothing
:param matrix: The matrix to invert
:return: The inverse of the matrix passed as parameter
"""
num_rows = len(matrix)
num_cols = len(matrix[0])
if num_rows != num_cols:
raise ValueError("You should pass a square matrix")
dim = num_rows
denom = determinant(matrix)
if denom == 0:
raise ValueError("The determinant is 0. Can't invert matrix")
cofactors = [] # the matrix of cofactors, transposed
for i in range(dim):
cofactor_row = []
for j in range(dim):
m_copy = copy.deepcopy(matrix)
minor = minor_matrix(m_copy, j+1, i+1)
minor_det = determinant(minor) * math.pow(-1, i + j)
cofactor_row.append(minor_det)
cofactors.append(cofactor_row)
# multiply every cofactor with 1/denom
scalar_multiply(cofactors, 1 / denom)
return cofactors
def scalar_multiply(matrix, const):
"""
This function makes the scalar multiplication between a matrix and a number.
:param matrix: The matrix to multiply
:param const: The constant number which will multiply the matrix
:return: The result of the multiplication
"""
for i in range(len(matrix)):
for j in range(len(matrix[0])):
matrix[i][j] *= const
return matrix
def multiply(matrix1, matrix2):
"""
This function multiplies two matrices. In order to multiply, it makes sure
the width of matrix1 is the same as the height of matrix2
:param matrix1: Left matrix
:param matrix2: Right matrix
:return: The product matrix of the multiplication
"""
width1 = len(matrix1[0])
height2 = len(matrix2)
if width1 != height2:
raise ValueError("Can't multiply these matrices")
length = len(matrix1)
width = len(matrix2[0])
product_matrix = [] # product_matrix = matrix_A * matrix_B
for i in range(length):
product_row = [] # one row of product_matrix
for j in range(width):
val = 0
for a in range(height2):
val += matrix1[i][a] * matrix2[a][j]
product_row.append(val)
product_matrix.append(product_row)
return product_matrix
def linear_solver(coef, const):
"""
This function solves a system of linear equations of the standard form Ax = B
:param coef: The matrix of coefficients, A
:param const: The matrix of constant terms, B
:returns: A list of the solutions
"""
if len(coef) == 2:
y = (const[0][0] * coef[1][0] - coef[0][0] * const[1][0]) / (-coef[0][0] * coef[1][1] + coef[1][0] * coef[0][1])
x = (const[1][0] - coef[1][1] * y) / coef[1][0]
return [x, y]
return multiply(inverse(coef), const)
| """
This function calculates the minor of a matrix for a given row and column
index. The matrix should be a square matrix, and the row and column
should be positive and smaller than the width and height of the matrix.
:param matrix: The matrix to calculate the minor
:param row_index: The row index of the minor to calculate
:param col_index: The column index of the minor to calculate
:return: The minor for the given row and column
"""
minor = matrix
num_rows = len(matrix)
num_cols = len(matrix[0])
if num_cols != num_rows:
raise ValueError("You should pass a square matrix")
if row_index > num_rows or col_index > num_cols or row_index < 1 or col_index < 1:
raise ValueError("Invalid row or column")
# remove the specified row
minor.pop(row_index - 1)
# remove the specified column
for row in minor:
row.pop(col_index - 1)
return minor | identifier_body |
pymatrix.py | import math
import copy
def print_matrix(matrix):
"""
This function prettyprints a matrix
:param matrix: The matrix to prettyprint
"""
for i in range(len(matrix)):
print(matrix[i])
def transpose(matrix):
"""
This function transposes a matrix
:param matrix: The matrix to transpose
:return: The transposed matrix
"""
num_cols = len(matrix[0])
trans = []
for i in range(num_cols):
temp = []
for row in matrix:
temp.append(row[i])
trans.append(temp)
return trans
def minor_matrix(matrix, row_index, col_index):
"""
This function calculates the minor of a matrix for a given row and column
index. The matrix should be a square matrix, and the row and column
should be positive and smaller than the width and height of the matrix.
:param matrix: The matrix to calculate the minor
:param row_index: The row index of the minor to calculate
:param col_index: The column index of the minor to calculate
:return: The minor for the given row and column
"""
minor = matrix
num_rows = len(matrix)
num_cols = len(matrix[0])
if num_cols != num_rows:
raise ValueError("You should pass a square matrix")
if row_index > num_rows or col_index > num_cols or row_index < 1 or col_index < 1:
raise ValueError("Invalid row or column")
# remove the specified row
minor.pop(row_index - 1)
# remove the specified column
for row in minor:
row.pop(col_index - 1)
return minor
def determinant(matrix):
"""
This function calculates the determinant of a square matrix.
:param m_copy: The matrix to find the determinant
:return: The determinant of the matrix
"""
num_rows = len(matrix)
num_cols = len(matrix[0])
if num_cols != num_rows:
raise ValueError("You should pass a square matrix")
dim = num_cols
det = 0
if dim == 1:
return matrix[0][0]
if dim == 2:
det = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
return det
for j in range(dim):
m_copy = copy.deepcopy(matrix)
minor = minor_matrix(m_copy, 1, j+1)
d = determinant(minor)
det += matrix[0][j] * d * math.pow(-1, j)
return det
def inverse(matrix):
"""
This function inverts a square matrix. If the matrix is not square,
it returns nothing
:param matrix: The matrix to invert
:return: The inverse of the matrix passed as parameter
"""
num_rows = len(matrix)
num_cols = len(matrix[0])
if num_rows != num_cols:
raise ValueError("You should pass a square matrix")
dim = num_rows
denom = determinant(matrix)
if denom == 0:
raise ValueError("The determinant is 0. Can't invert matrix")
cofactors = [] # the matrix of cofactors, transposed
for i in range(dim):
cofactor_row = []
for j in range(dim):
m_copy = copy.deepcopy(matrix)
minor = minor_matrix(m_copy, j+1, i+1)
minor_det = determinant(minor) * math.pow(-1, i + j)
cofactor_row.append(minor_det)
cofactors.append(cofactor_row)
# multiply every cofactor with 1/denom
scalar_multiply(cofactors, 1 / denom)
return cofactors
def scalar_multiply(matrix, const):
"""
This function makes the scalar multiplication between a matrix and a number.
:param matrix: The matrix to multiply
:param const: The constant number which will multiply the matrix
:return: The result of the multiplication
"""
for i in range(len(matrix)):
|
return matrix
def multiply(matrix1, matrix2):
"""
This function multiplies two matrices. In order to multiply, it makes sure
the width of matrix1 is the same as the height of matrix2
:param matrix1: Left matrix
:param matrix2: Right matrix
:return: The product matrix of the multiplication
"""
width1 = len(matrix1[0])
height2 = len(matrix2)
if width1 != height2:
raise ValueError("Can't multiply these matrices")
length = len(matrix1)
width = len(matrix2[0])
product_matrix = [] # product_matrix = matrix_A * matrix_B
for i in range(length):
product_row = [] # one row of product_matrix
for j in range(width):
val = 0
for a in range(height2):
val += matrix1[i][a] * matrix2[a][j]
product_row.append(val)
product_matrix.append(product_row)
return product_matrix
def linear_solver(coef, const):
"""
This function solves a system of linear equations of the standard form Ax = B
:param coef: The matrix of coefficients, A
:param const: The matrix of constant terms, B
:returns: A list of the solutions
"""
if len(coef) == 2:
y = (const[0][0] * coef[1][0] - coef[0][0] * const[1][0]) / (-coef[0][0] * coef[1][1] + coef[1][0] * coef[0][1])
x = (const[1][0] - coef[1][1] * y) / coef[1][0]
return [x, y]
return multiply(inverse(coef), const)
| for j in range(len(matrix[0])):
matrix[i][j] *= const | conditional_block |
pymatrix.py | import math
import copy
def print_matrix(matrix):
"""
This function prettyprints a matrix
:param matrix: The matrix to prettyprint
"""
for i in range(len(matrix)):
print(matrix[i])
def | (matrix):
"""
This function transposes a matrix
:param matrix: The matrix to transpose
:return: The transposed matrix
"""
num_cols = len(matrix[0])
trans = []
for i in range(num_cols):
temp = []
for row in matrix:
temp.append(row[i])
trans.append(temp)
return trans
def minor_matrix(matrix, row_index, col_index):
"""
This function calculates the minor of a matrix for a given row and column
index. The matrix should be a square matrix, and the row and column
should be positive and smaller than the width and height of the matrix.
:param matrix: The matrix to calculate the minor
:param row_index: The row index of the minor to calculate
:param col_index: The column index of the minor to calculate
:return: The minor for the given row and column
"""
minor = matrix
num_rows = len(matrix)
num_cols = len(matrix[0])
if num_cols != num_rows:
raise ValueError("You should pass a square matrix")
if row_index > num_rows or col_index > num_cols or row_index < 1 or col_index < 1:
raise ValueError("Invalid row or column")
# remove the specified row
minor.pop(row_index - 1)
# remove the specified column
for row in minor:
row.pop(col_index - 1)
return minor
def determinant(matrix):
"""
This function calculates the determinant of a square matrix.
:param m_copy: The matrix to find the determinant
:return: The determinant of the matrix
"""
num_rows = len(matrix)
num_cols = len(matrix[0])
if num_cols != num_rows:
raise ValueError("You should pass a square matrix")
dim = num_cols
det = 0
if dim == 1:
return matrix[0][0]
if dim == 2:
det = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
return det
for j in range(dim):
m_copy = copy.deepcopy(matrix)
minor = minor_matrix(m_copy, 1, j+1)
d = determinant(minor)
det += matrix[0][j] * d * math.pow(-1, j)
return det
def inverse(matrix):
"""
This function inverts a square matrix. If the matrix is not square,
it returns nothing
:param matrix: The matrix to invert
:return: The inverse of the matrix passed as parameter
"""
num_rows = len(matrix)
num_cols = len(matrix[0])
if num_rows != num_cols:
raise ValueError("You should pass a square matrix")
dim = num_rows
denom = determinant(matrix)
if denom == 0:
raise ValueError("The determinant is 0. Can't invert matrix")
cofactors = [] # the matrix of cofactors, transposed
for i in range(dim):
cofactor_row = []
for j in range(dim):
m_copy = copy.deepcopy(matrix)
minor = minor_matrix(m_copy, j+1, i+1)
minor_det = determinant(minor) * math.pow(-1, i + j)
cofactor_row.append(minor_det)
cofactors.append(cofactor_row)
# multiply every cofactor with 1/denom
scalar_multiply(cofactors, 1 / denom)
return cofactors
def scalar_multiply(matrix, const):
"""
This function makes the scalar multiplication between a matrix and a number.
:param matrix: The matrix to multiply
:param const: The constant number which will multiply the matrix
:return: The result of the multiplication
"""
for i in range(len(matrix)):
for j in range(len(matrix[0])):
matrix[i][j] *= const
return matrix
def multiply(matrix1, matrix2):
"""
This function multiplies two matrices. In order to multiply, it makes sure
the width of matrix1 is the same as the height of matrix2
:param matrix1: Left matrix
:param matrix2: Right matrix
:return: The product matrix of the multiplication
"""
width1 = len(matrix1[0])
height2 = len(matrix2)
if width1 != height2:
raise ValueError("Can't multiply these matrices")
length = len(matrix1)
width = len(matrix2[0])
product_matrix = [] # product_matrix = matrix_A * matrix_B
for i in range(length):
product_row = [] # one row of product_matrix
for j in range(width):
val = 0
for a in range(height2):
val += matrix1[i][a] * matrix2[a][j]
product_row.append(val)
product_matrix.append(product_row)
return product_matrix
def linear_solver(coef, const):
"""
This function solves a system of linear equations of the standard form Ax = B
:param coef: The matrix of coefficients, A
:param const: The matrix of constant terms, B
:returns: A list of the solutions
"""
if len(coef) == 2:
y = (const[0][0] * coef[1][0] - coef[0][0] * const[1][0]) / (-coef[0][0] * coef[1][1] + coef[1][0] * coef[0][1])
x = (const[1][0] - coef[1][1] * y) / coef[1][0]
return [x, y]
return multiply(inverse(coef), const)
| transpose | identifier_name |
_FormWidget.js | /*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dijit.form._FormWidget"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.form._FormWidget"] = true;
dojo.provide("dijit.form._FormWidget");
dojo.require("dojo.window");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dijit._CssStateMixin");
dojo.declare("dijit.form._FormWidget", [dijit._Widget, dijit._Templated, dijit._CssStateMixin],
{
// summary:
// Base class for widgets corresponding to native HTML elements such as <checkbox> or <button>,
// which can be children of a <form> node or a `dijit.form.Form` widget.
//
// description:
// Represents a single HTML element.
// All these widgets should have these attributes just like native HTML input elements.
// You can set them during widget construction or afterwards, via `dijit._Widget.attr`.
//
// They also share some common methods.
// name: [const] String
// Name used when submitting form; same as "name" attribute or plain HTML elements
name: "",
// alt: String
// Corresponds to the native HTML <input> element's attribute.
alt: "",
// value: String
// Corresponds to the native HTML <input> element's attribute.
value: "",
// type: String
// Corresponds to the native HTML <input> element's attribute.
type: "text",
// tabIndex: Integer
// Order fields are traversed when user hits the tab key
tabIndex: "0",
// disabled: Boolean
// Should this widget respond to user input?
// In markup, this is specified as "disabled='disabled'", or just "disabled".
disabled: false,
// intermediateChanges: Boolean | // Fires onChange for each value change or only on demand
intermediateChanges: false,
// scrollOnFocus: Boolean
// On focus, should this widget scroll into view?
scrollOnFocus: true,
// These mixins assume that the focus node is an INPUT, as many but not all _FormWidgets are.
attributeMap: dojo.delegate(dijit._Widget.prototype.attributeMap, {
value: "focusNode",
id: "focusNode",
tabIndex: "focusNode",
alt: "focusNode",
title: "focusNode"
}),
postMixInProperties: function(){
// Setup name=foo string to be referenced from the template (but only if a name has been specified)
// Unfortunately we can't use attributeMap to set the name due to IE limitations, see #8660
// Regarding escaping, see heading "Attribute values" in
// http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.3.2
this.nameAttrSetting = this.name ? ('name="' + this.name.replace(/'/g, """) + '"') : '';
this.inherited(arguments);
},
postCreate: function(){
this.inherited(arguments);
this.connect(this.domNode, "onmousedown", "_onMouseDown");
},
_setDisabledAttr: function(/*Boolean*/ value){
this._set("disabled", value);
dojo.attr(this.focusNode, 'disabled', value);
if(this.valueNode){
dojo.attr(this.valueNode, 'disabled', value);
}
dijit.setWaiState(this.focusNode, "disabled", value);
if(value){
// reset these, because after the domNode is disabled, we can no longer receive
// mouse related events, see #4200
this._set("hovering", false);
this._set("active", false);
// clear tab stop(s) on this widget's focusable node(s) (ComboBox has two focusable nodes)
var attachPointNames = "tabIndex" in this.attributeMap ? this.attributeMap.tabIndex : "focusNode";
dojo.forEach(dojo.isArray(attachPointNames) ? attachPointNames : [attachPointNames], function(attachPointName){
var node = this[attachPointName];
// complex code because tabIndex=-1 on a <div> doesn't work on FF
if(dojo.isWebKit || dijit.hasDefaultTabStop(node)){ // see #11064 about webkit bug
node.setAttribute('tabIndex', "-1");
}else{
node.removeAttribute('tabIndex');
}
}, this);
}else{
if(this.tabIndex != ""){
this.focusNode.setAttribute('tabIndex', this.tabIndex);
}
}
},
setDisabled: function(/*Boolean*/ disabled){
// summary:
// Deprecated. Use set('disabled', ...) instead.
dojo.deprecated("setDisabled("+disabled+") is deprecated. Use set('disabled',"+disabled+") instead.", "", "2.0");
this.set('disabled', disabled);
},
_onFocus: function(e){
if(this.scrollOnFocus){
dojo.window.scrollIntoView(this.domNode);
}
this.inherited(arguments);
},
isFocusable: function(){
// summary:
// Tells if this widget is focusable or not. Used internally by dijit.
// tags:
// protected
return !this.disabled && this.focusNode && (dojo.style(this.domNode, "display") != "none");
},
focus: function(){
// summary:
// Put focus on this widget
if(!this.disabled){
dijit.focus(this.focusNode);
}
},
compare: function(/*anything*/ val1, /*anything*/ val2){
// summary:
// Compare 2 values (as returned by get('value') for this widget).
// tags:
// protected
if(typeof val1 == "number" && typeof val2 == "number"){
return (isNaN(val1) && isNaN(val2)) ? 0 : val1 - val2;
}else if(val1 > val2){
return 1;
}else if(val1 < val2){
return -1;
}else{
return 0;
}
},
onChange: function(newValue){
// summary:
// Callback when this widget's value is changed.
// tags:
// callback
},
// _onChangeActive: [private] Boolean
// Indicates that changes to the value should call onChange() callback.
// This is false during widget initialization, to avoid calling onChange()
// when the initial value is set.
_onChangeActive: false,
_handleOnChange: function(/*anything*/ newValue, /*Boolean?*/ priorityChange){
// summary:
// Called when the value of the widget is set. Calls onChange() if appropriate
// newValue:
// the new value
// priorityChange:
// For a slider, for example, dragging the slider is priorityChange==false,
// but on mouse up, it's priorityChange==true. If intermediateChanges==false,
// onChange is only called form priorityChange=true events.
// tags:
// private
if(this._lastValueReported == undefined && (priorityChange === null || !this._onChangeActive)){
// this block executes not for a change, but during initialization,
// and is used to store away the original value (or for ToggleButton, the original checked state)
this._resetValue = this._lastValueReported = newValue;
}
this._pendingOnChange = this._pendingOnChange
|| (typeof newValue != typeof this._lastValueReported)
|| (this.compare(newValue, this._lastValueReported) != 0);
if((this.intermediateChanges || priorityChange || priorityChange === undefined) && this._pendingOnChange){
this._lastValueReported = newValue;
this._pendingOnChange = false;
if(this._onChangeActive){
if(this._onChangeHandle){
clearTimeout(this._onChangeHandle);
}
// setTimout allows hidden value processing to run and
// also the onChange handler can safely adjust focus, etc
this._onChangeHandle = setTimeout(dojo.hitch(this,
function(){
this._onChangeHandle = null;
this.onChange(newValue);
}), 0); // try to collapse multiple onChange's fired faster than can be processed
}
}
},
create: function(){
// Overrides _Widget.create()
this.inherited(arguments);
this._onChangeActive = true;
},
destroy: function(){
if(this._onChangeHandle){ // destroy called before last onChange has fired
clearTimeout(this._onChangeHandle);
this.onChange(this._lastValueReported);
}
this.inherited(arguments);
},
setValue: function(/*String*/ value){
// summary:
// Deprecated. Use set('value', ...) instead.
dojo.deprecated("dijit.form._FormWidget:setValue("+value+") is deprecated. Use set('value',"+value+") instead.", "", "2.0");
this.set('value', value);
},
getValue: function(){
// summary:
// Deprecated. Use get('value') instead.
dojo.deprecated(this.declaredClass+"::getValue() is deprecated. Use get('value') instead.", "", "2.0");
return this.get('value');
},
_onMouseDown: function(e){
// If user clicks on the button, even if the mouse is released outside of it,
// this button should get focus (to mimics native browser buttons).
// This is also needed on chrome because otherwise buttons won't get focus at all,
// which leads to bizarre focus restore on Dialog close etc.
if(!e.ctrlKey && dojo.mouseButtons.isLeft(e) && this.isFocusable()){ // !e.ctrlKey to ignore right-click on mac
// Set a global event to handle mouseup, so it fires properly
// even if the cursor leaves this.domNode before the mouse up event.
var mouseUpConnector = this.connect(dojo.body(), "onmouseup", function(){
if (this.isFocusable()) {
this.focus();
}
this.disconnect(mouseUpConnector);
});
}
}
});
dojo.declare("dijit.form._FormValueWidget", dijit.form._FormWidget,
{
// summary:
// Base class for widgets corresponding to native HTML elements such as <input> or <select> that have user changeable values.
// description:
// Each _FormValueWidget represents a single input value, and has a (possibly hidden) <input> element,
// to which it serializes it's input value, so that form submission (either normal submission or via FormBind?)
// works as expected.
// Don't attempt to mixin the 'type', 'name' attributes here programatically -- they must be declared
// directly in the template as read by the parser in order to function. IE is known to specifically
// require the 'name' attribute at element creation time. See #8484, #8660.
// TODO: unclear what that {value: ""} is for; FormWidget.attributeMap copies value to focusNode,
// so maybe {value: ""} is so the value *doesn't* get copied to focusNode?
// Seems like we really want value removed from attributeMap altogether
// (although there's no easy way to do that now)
// readOnly: Boolean
// Should this widget respond to user input?
// In markup, this is specified as "readOnly".
// Similar to disabled except readOnly form values are submitted.
readOnly: false,
attributeMap: dojo.delegate(dijit.form._FormWidget.prototype.attributeMap, {
value: "",
readOnly: "focusNode"
}),
_setReadOnlyAttr: function(/*Boolean*/ value){
dojo.attr(this.focusNode, 'readOnly', value);
dijit.setWaiState(this.focusNode, "readonly", value);
this._set("readOnly", value);
},
postCreate: function(){
this.inherited(arguments);
if(dojo.isIE < 9 || (dojo.isIE && dojo.isQuirks)){ // IE won't stop the event with keypress
this.connect(this.focusNode || this.domNode, "onkeydown", this._onKeyDown);
}
// Update our reset value if it hasn't yet been set (because this.set()
// is only called when there *is* a value)
if(this._resetValue === undefined){
this._lastValueReported = this._resetValue = this.value;
}
},
_setValueAttr: function(/*anything*/ newValue, /*Boolean?*/ priorityChange){
// summary:
// Hook so set('value', value) works.
// description:
// Sets the value of the widget.
// If the value has changed, then fire onChange event, unless priorityChange
// is specified as null (or false?)
this._handleOnChange(newValue, priorityChange);
},
_handleOnChange: function(/*anything*/ newValue, /*Boolean?*/ priorityChange){
// summary:
// Called when the value of the widget has changed. Saves the new value in this.value,
// and calls onChange() if appropriate. See _FormWidget._handleOnChange() for details.
this._set("value", newValue);
this.inherited(arguments);
},
undo: function(){
// summary:
// Restore the value to the last value passed to onChange
this._setValueAttr(this._lastValueReported, false);
},
reset: function(){
// summary:
// Reset the widget's value to what it was at initialization time
this._hasBeenBlurred = false;
this._setValueAttr(this._resetValue, true);
},
_onKeyDown: function(e){
if(e.keyCode == dojo.keys.ESCAPE && !(e.ctrlKey || e.altKey || e.metaKey)){
var te;
if(dojo.isIE){
e.preventDefault(); // default behavior needs to be stopped here since keypress is too late
te = document.createEventObject();
te.keyCode = dojo.keys.ESCAPE;
te.shiftKey = e.shiftKey;
e.srcElement.fireEvent('onkeypress', te);
}
}
},
_layoutHackIE7: function(){
// summary:
// Work around table sizing bugs on IE7 by forcing redraw
if(dojo.isIE == 7){ // fix IE7 layout bug when the widget is scrolled out of sight
var domNode = this.domNode;
var parent = domNode.parentNode;
var pingNode = domNode.firstChild || domNode; // target node most unlikely to have a custom filter
var origFilter = pingNode.style.filter; // save custom filter, most likely nothing
var _this = this;
while(parent && parent.clientHeight == 0){ // search for parents that haven't rendered yet
(function ping(){
var disconnectHandle = _this.connect(parent, "onscroll",
function(e){
_this.disconnect(disconnectHandle); // only call once
pingNode.style.filter = (new Date()).getMilliseconds(); // set to anything that's unique
setTimeout(function(){ pingNode.style.filter = origFilter }, 0); // restore custom filter, if any
}
);
})();
parent = parent.parentNode;
}
}
}
});
} | random_line_split | |
__init__.py | #!/usr/bin/env python
# Copyright (c) 2013, Carnegie Mellon University
# All rights reserved.
# Authors: Michael Koval <mkoval@cs.cmu.edu>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# - Neither the name of Carnegie Mellon University nor the names of its
# contributors may be used to endorse or promote products derived from this | #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import base, dependency_manager, logger, ik_ranking, planning, perception, simulation, tsr, viz
from named_config import ConfigurationLibrary
from clone import Clone, Cloned
from bind import bind_subclass
import compatibility | # software without specific prior written permission. | random_line_split |
paged_results.rs | use super::{ControlParser, MakeCritical, RawControl};
use bytes::BytesMut;
use lber::common::TagClass;
use lber::IResult;
use lber::parse::{parse_uint, parse_tag};
use lber::structures::{ASNTag, Integer, OctetString, Sequence, Tag};
use lber::universal::Types;
use lber::write;
/// Paged Results control ([RFC 2696](https://tools.ietf.org/html/rfc2696)).
///
/// This struct can be used both for requests and responses, although `size`
/// means different things in each case.
#[derive(Clone, Debug)]
pub struct PagedResults {
/// For requests, desired page size. For responses, a server's estimate
/// of the result set size, if non-zero.
pub size: i32,
/// Paging cookie.
pub cookie: Vec<u8>,
}
pub const PAGED_RESULTS_OID: &'static str = "1.2.840.113556.1.4.319";
impl MakeCritical for PagedResults { }
impl From<PagedResults> for RawControl {
fn from(pr: PagedResults) -> RawControl |
}
impl ControlParser for PagedResults {
fn parse(val: &[u8]) -> PagedResults {
let mut pr_comps = match parse_tag(val) {
IResult::Done(_, tag) => tag,
_ => panic!("failed to parse paged results value components"),
}.expect_constructed().expect("paged results components").into_iter();
let size = match parse_uint(pr_comps.next().expect("element")
.match_class(TagClass::Universal)
.and_then(|t| t.match_id(Types::Integer as u64))
.and_then(|t| t.expect_primitive()).expect("paged results size")
.as_slice()) {
IResult::Done(_, size) => size as i32,
_ => panic!("failed to parse size"),
};
let cookie = pr_comps.next().expect("element").expect_primitive().expect("octet string");
PagedResults { size: size, cookie: cookie }
}
}
| {
let cookie_len = pr.cookie.len();
let cval = Tag::Sequence(Sequence {
inner: vec![
Tag::Integer(Integer {
inner: pr.size as i64,
.. Default::default()
}),
Tag::OctetString(OctetString {
inner: pr.cookie,
.. Default::default()
}),
],
.. Default::default()
}).into_structure();
let mut buf = BytesMut::with_capacity(cookie_len + 16);
write::encode_into(&mut buf, cval).expect("encoded");
RawControl {
ctype: PAGED_RESULTS_OID.to_owned(),
crit: false,
val: Some(Vec::from(&buf[..])),
}
} | identifier_body |
paged_results.rs | use super::{ControlParser, MakeCritical, RawControl};
use bytes::BytesMut;
use lber::common::TagClass;
use lber::IResult;
use lber::parse::{parse_uint, parse_tag};
use lber::structures::{ASNTag, Integer, OctetString, Sequence, Tag};
use lber::universal::Types;
use lber::write;
/// Paged Results control ([RFC 2696](https://tools.ietf.org/html/rfc2696)).
///
/// This struct can be used both for requests and responses, although `size`
/// means different things in each case.
#[derive(Clone, Debug)]
pub struct PagedResults {
/// For requests, desired page size. For responses, a server's estimate
/// of the result set size, if non-zero.
pub size: i32,
/// Paging cookie.
pub cookie: Vec<u8>,
}
pub const PAGED_RESULTS_OID: &'static str = "1.2.840.113556.1.4.319";
| impl From<PagedResults> for RawControl {
fn from(pr: PagedResults) -> RawControl {
let cookie_len = pr.cookie.len();
let cval = Tag::Sequence(Sequence {
inner: vec![
Tag::Integer(Integer {
inner: pr.size as i64,
.. Default::default()
}),
Tag::OctetString(OctetString {
inner: pr.cookie,
.. Default::default()
}),
],
.. Default::default()
}).into_structure();
let mut buf = BytesMut::with_capacity(cookie_len + 16);
write::encode_into(&mut buf, cval).expect("encoded");
RawControl {
ctype: PAGED_RESULTS_OID.to_owned(),
crit: false,
val: Some(Vec::from(&buf[..])),
}
}
}
impl ControlParser for PagedResults {
fn parse(val: &[u8]) -> PagedResults {
let mut pr_comps = match parse_tag(val) {
IResult::Done(_, tag) => tag,
_ => panic!("failed to parse paged results value components"),
}.expect_constructed().expect("paged results components").into_iter();
let size = match parse_uint(pr_comps.next().expect("element")
.match_class(TagClass::Universal)
.and_then(|t| t.match_id(Types::Integer as u64))
.and_then(|t| t.expect_primitive()).expect("paged results size")
.as_slice()) {
IResult::Done(_, size) => size as i32,
_ => panic!("failed to parse size"),
};
let cookie = pr_comps.next().expect("element").expect_primitive().expect("octet string");
PagedResults { size: size, cookie: cookie }
}
} | impl MakeCritical for PagedResults { }
| random_line_split |
paged_results.rs | use super::{ControlParser, MakeCritical, RawControl};
use bytes::BytesMut;
use lber::common::TagClass;
use lber::IResult;
use lber::parse::{parse_uint, parse_tag};
use lber::structures::{ASNTag, Integer, OctetString, Sequence, Tag};
use lber::universal::Types;
use lber::write;
/// Paged Results control ([RFC 2696](https://tools.ietf.org/html/rfc2696)).
///
/// This struct can be used both for requests and responses, although `size`
/// means different things in each case.
#[derive(Clone, Debug)]
pub struct | {
/// For requests, desired page size. For responses, a server's estimate
/// of the result set size, if non-zero.
pub size: i32,
/// Paging cookie.
pub cookie: Vec<u8>,
}
pub const PAGED_RESULTS_OID: &'static str = "1.2.840.113556.1.4.319";
impl MakeCritical for PagedResults { }
impl From<PagedResults> for RawControl {
fn from(pr: PagedResults) -> RawControl {
let cookie_len = pr.cookie.len();
let cval = Tag::Sequence(Sequence {
inner: vec![
Tag::Integer(Integer {
inner: pr.size as i64,
.. Default::default()
}),
Tag::OctetString(OctetString {
inner: pr.cookie,
.. Default::default()
}),
],
.. Default::default()
}).into_structure();
let mut buf = BytesMut::with_capacity(cookie_len + 16);
write::encode_into(&mut buf, cval).expect("encoded");
RawControl {
ctype: PAGED_RESULTS_OID.to_owned(),
crit: false,
val: Some(Vec::from(&buf[..])),
}
}
}
impl ControlParser for PagedResults {
fn parse(val: &[u8]) -> PagedResults {
let mut pr_comps = match parse_tag(val) {
IResult::Done(_, tag) => tag,
_ => panic!("failed to parse paged results value components"),
}.expect_constructed().expect("paged results components").into_iter();
let size = match parse_uint(pr_comps.next().expect("element")
.match_class(TagClass::Universal)
.and_then(|t| t.match_id(Types::Integer as u64))
.and_then(|t| t.expect_primitive()).expect("paged results size")
.as_slice()) {
IResult::Done(_, size) => size as i32,
_ => panic!("failed to parse size"),
};
let cookie = pr_comps.next().expect("element").expect_primitive().expect("octet string");
PagedResults { size: size, cookie: cookie }
}
}
| PagedResults | identifier_name |
auth.py | #!/usr/bin/env python
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-
#
# NetProfile: Authentication routines
# © Copyright 2013-2014 Alex 'Unik' Unigovsky
#
# This file is part of NetProfile.
# NetProfile is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public
# License as published by the Free Software Foundation, either
# version 3 of the License, or (at your option) any later
# version.
#
# NetProfile is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General
# Public License along with NetProfile. If not, see
# <http://www.gnu.org/licenses/>.
from __future__ import (
unicode_literals,
print_function,
absolute_import,
division
)
import hashlib
import random
import string
import time
from zope.interface import implementer
from pyramid.interfaces import IAuthenticationPolicy
from pyramid.security import (
Authenticated,
Everyone | self.policy = policy
@implementer(IAuthenticationPolicy)
class PluginAuthenticationPolicy(object):
def __init__(self, default, routes=None):
self._default = default
if routes is None:
routes = {}
self._routes = routes
def add_plugin(self, route, policy):
self._routes[route] = policy
def match(self, request):
if hasattr(request, 'auth_policy'):
return request.auth_policy
cur = None
cur_len = 0
for route, plug in self._routes.items():
r_len = len(route)
if r_len <= cur_len:
continue
path = request.path
if route == path[:r_len]:
if len(path) > r_len:
if path[r_len:r_len + 1] != '/':
continue
cur = plug
cur_len = r_len
if cur:
request.auth_policy = cur
else:
request.auth_policy = self._default
request.registry.notify(PluginPolicySelected(request, request.auth_policy))
return request.auth_policy
def authenticated_userid(self, request):
return self.match(request).authenticated_userid(request)
def unauthenticated_userid(self, request):
return self.match(request).unauthenticated_userid(request)
def effective_principals(self, request):
return self.match(request).effective_principals(request)
def remember(self, request, principal, **kw):
return self.match(request).remember(request, principal, **kw)
def forget(self, request):
return self.match(request).forget(request)
_TOKEN_FILTER_MAP = (
[chr(n) for n in range(32)] +
[chr(127), '\\', '"']
)
_TOKEN_FILTER_MAP = dict.fromkeys(_TOKEN_FILTER_MAP, None)
def _filter_token(tok):
return str(tok).translate(_TOKEN_FILTER_MAP)
def _format_kvpairs(**kwargs):
return ', '.join('{0!s}="{1}"'.format(k, _filter_token(v)) for (k, v) in kwargs.items())
def _generate_nonce(ts, secret, salt=None, chars=string.hexdigits.upper()):
# TODO: Add IP-address to nonce
if not salt:
try:
rng = random.SystemRandom()
except NotImplementedError:
rng = random
salt = ''.join(rng.choice(chars) for i in range(16))
ctx = hashlib.md5(('%s:%s:%s' % (ts, salt, secret)).encode())
return ('%s:%s:%s' % (ts, salt, ctx.hexdigest()))
def _is_valid_nonce(nonce, secret):
comp = nonce.split(':')
if len(comp) != 3:
return False
calc_nonce = _generate_nonce(comp[0], secret, comp[1])
if nonce == calc_nonce:
return True
return False
def _generate_digest_challenge(ts, secret, realm, opaque, stale=False):
nonce = _generate_nonce(ts, secret)
return 'Digest %s' % (_format_kvpairs(
realm=realm,
qop='auth',
nonce=nonce,
opaque=opaque,
algorithm='MD5',
stale='true' if stale else 'false'
),)
def _add_www_authenticate(request, secret, realm):
resp = request.response
if not resp.www_authenticate:
resp.www_authenticate = _generate_digest_challenge(
round(time.time()),
secret, realm, 'NPDIGEST'
)
def _parse_authorization(request, secret, realm):
authz = request.authorization
if (not authz) or (len(authz) != 2) or (authz[0] != 'Digest'):
_add_www_authenticate(request, secret, realm)
return None
params = authz[1]
if 'algorithm' not in params:
params['algorithm'] = 'MD5'
for required in ('username', 'realm', 'nonce', 'uri', 'response', 'cnonce', 'nc', 'opaque'):
if (required not in params) or ((required == 'opaque') and (params['opaque'] != 'NPDIGEST')):
_add_www_authenticate(request, secret, realm)
return None
return params
@implementer(IAuthenticationPolicy)
class DigestAuthenticationPolicy(object):
def __init__(self, secret, callback, realm='Realm'):
self.secret = secret
self.callback = callback
self.realm = realm
def authenticated_userid(self, request):
params = _parse_authorization(request, self.secret, self.realm)
if params is None:
return None
if not _is_valid_nonce(params['nonce'], self.secret):
_add_www_authenticate(request, self.secret, self.realm)
return None
userid = params['username']
if self.callback(params, request) is not None:
return 'u:%s' % userid
_add_www_authenticate(request, self.secret, self.realm)
def unauthenticated_userid(self, request):
params = _parse_authorization(request, self.secret, self.realm)
if params is None:
return None
if not _is_valid_nonce(params['nonce'], self.secret):
_add_www_authenticate(request, self.secret, self.realm)
return None
return 'u:%s' % params['username']
def effective_principals(self, request):
creds = [Everyone]
params = _parse_authorization(request, self.secret, self.realm)
if params is None:
return creds
if not _is_valid_nonce(params['nonce'], self.secret):
_add_www_authenticate(request, self.secret, self.realm)
return creds
groups = self.callback(params, request)
if groups is None:
return creds
creds.append(Authenticated)
creds.append('u:%s' % params['username'])
creds.extend(groups)
return creds
def remember(self, request, principal, *kw):
return []
def forget(self, request):
return [('WWW-Authenticate', _generate_digest_challenge(
round(time.time()),
self.secret,
self.realm,
'NPDIGEST'
))] | )
class PluginPolicySelected(object):
def __init__(self, request, policy):
self.request = request | random_line_split |
auth.py | #!/usr/bin/env python
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-
#
# NetProfile: Authentication routines
# © Copyright 2013-2014 Alex 'Unik' Unigovsky
#
# This file is part of NetProfile.
# NetProfile is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public
# License as published by the Free Software Foundation, either
# version 3 of the License, or (at your option) any later
# version.
#
# NetProfile is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General
# Public License along with NetProfile. If not, see
# <http://www.gnu.org/licenses/>.
from __future__ import (
unicode_literals,
print_function,
absolute_import,
division
)
import hashlib
import random
import string
import time
from zope.interface import implementer
from pyramid.interfaces import IAuthenticationPolicy
from pyramid.security import (
Authenticated,
Everyone
)
class PluginPolicySelected(object):
def __init__(self, request, policy):
self.request = request
self.policy = policy
@implementer(IAuthenticationPolicy)
class PluginAuthenticationPolicy(object):
def __init__(self, default, routes=None):
self._default = default
if routes is None:
routes = {}
self._routes = routes
def add_plugin(self, route, policy):
self._routes[route] = policy
def match(self, request):
if hasattr(request, 'auth_policy'):
return request.auth_policy
cur = None
cur_len = 0
for route, plug in self._routes.items():
r_len = len(route)
if r_len <= cur_len:
continue
path = request.path
if route == path[:r_len]:
if len(path) > r_len:
if path[r_len:r_len + 1] != '/':
continue
cur = plug
cur_len = r_len
if cur:
request.auth_policy = cur
else:
request.auth_policy = self._default
request.registry.notify(PluginPolicySelected(request, request.auth_policy))
return request.auth_policy
def authenticated_userid(self, request):
return self.match(request).authenticated_userid(request)
def unauthenticated_userid(self, request):
return self.match(request).unauthenticated_userid(request)
def effective_principals(self, request):
return self.match(request).effective_principals(request)
def remember(self, request, principal, **kw):
return self.match(request).remember(request, principal, **kw)
def forget(self, request):
return self.match(request).forget(request)
_TOKEN_FILTER_MAP = (
[chr(n) for n in range(32)] +
[chr(127), '\\', '"']
)
_TOKEN_FILTER_MAP = dict.fromkeys(_TOKEN_FILTER_MAP, None)
def _filter_token(tok):
return str(tok).translate(_TOKEN_FILTER_MAP)
def _format_kvpairs(**kwargs):
return ', '.join('{0!s}="{1}"'.format(k, _filter_token(v)) for (k, v) in kwargs.items())
def _generate_nonce(ts, secret, salt=None, chars=string.hexdigits.upper()):
# TODO: Add IP-address to nonce
if not salt:
try:
rng = random.SystemRandom()
except NotImplementedError:
rng = random
salt = ''.join(rng.choice(chars) for i in range(16))
ctx = hashlib.md5(('%s:%s:%s' % (ts, salt, secret)).encode())
return ('%s:%s:%s' % (ts, salt, ctx.hexdigest()))
def _is_valid_nonce(nonce, secret):
comp = nonce.split(':')
if len(comp) != 3:
return False
calc_nonce = _generate_nonce(comp[0], secret, comp[1])
if nonce == calc_nonce:
return True
return False
def _generate_digest_challenge(ts, secret, realm, opaque, stale=False):
nonce = _generate_nonce(ts, secret)
return 'Digest %s' % (_format_kvpairs(
realm=realm,
qop='auth',
nonce=nonce,
opaque=opaque,
algorithm='MD5',
stale='true' if stale else 'false'
),)
def _add_www_authenticate(request, secret, realm):
resp = request.response
if not resp.www_authenticate:
resp.www_authenticate = _generate_digest_challenge(
round(time.time()),
secret, realm, 'NPDIGEST'
)
def _parse_authorization(request, secret, realm):
a |
@implementer(IAuthenticationPolicy)
class DigestAuthenticationPolicy(object):
def __init__(self, secret, callback, realm='Realm'):
self.secret = secret
self.callback = callback
self.realm = realm
def authenticated_userid(self, request):
params = _parse_authorization(request, self.secret, self.realm)
if params is None:
return None
if not _is_valid_nonce(params['nonce'], self.secret):
_add_www_authenticate(request, self.secret, self.realm)
return None
userid = params['username']
if self.callback(params, request) is not None:
return 'u:%s' % userid
_add_www_authenticate(request, self.secret, self.realm)
def unauthenticated_userid(self, request):
params = _parse_authorization(request, self.secret, self.realm)
if params is None:
return None
if not _is_valid_nonce(params['nonce'], self.secret):
_add_www_authenticate(request, self.secret, self.realm)
return None
return 'u:%s' % params['username']
def effective_principals(self, request):
creds = [Everyone]
params = _parse_authorization(request, self.secret, self.realm)
if params is None:
return creds
if not _is_valid_nonce(params['nonce'], self.secret):
_add_www_authenticate(request, self.secret, self.realm)
return creds
groups = self.callback(params, request)
if groups is None:
return creds
creds.append(Authenticated)
creds.append('u:%s' % params['username'])
creds.extend(groups)
return creds
def remember(self, request, principal, *kw):
return []
def forget(self, request):
return [('WWW-Authenticate', _generate_digest_challenge(
round(time.time()),
self.secret,
self.realm,
'NPDIGEST'
))]
| uthz = request.authorization
if (not authz) or (len(authz) != 2) or (authz[0] != 'Digest'):
_add_www_authenticate(request, secret, realm)
return None
params = authz[1]
if 'algorithm' not in params:
params['algorithm'] = 'MD5'
for required in ('username', 'realm', 'nonce', 'uri', 'response', 'cnonce', 'nc', 'opaque'):
if (required not in params) or ((required == 'opaque') and (params['opaque'] != 'NPDIGEST')):
_add_www_authenticate(request, secret, realm)
return None
return params
| identifier_body |
auth.py | #!/usr/bin/env python
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-
#
# NetProfile: Authentication routines
# © Copyright 2013-2014 Alex 'Unik' Unigovsky
#
# This file is part of NetProfile.
# NetProfile is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public
# License as published by the Free Software Foundation, either
# version 3 of the License, or (at your option) any later
# version.
#
# NetProfile is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General
# Public License along with NetProfile. If not, see
# <http://www.gnu.org/licenses/>.
from __future__ import (
unicode_literals,
print_function,
absolute_import,
division
)
import hashlib
import random
import string
import time
from zope.interface import implementer
from pyramid.interfaces import IAuthenticationPolicy
from pyramid.security import (
Authenticated,
Everyone
)
class PluginPolicySelected(object):
def __init__(self, request, policy):
self.request = request
self.policy = policy
@implementer(IAuthenticationPolicy)
class PluginAuthenticationPolicy(object):
def __init__(self, default, routes=None):
self._default = default
if routes is None:
routes = {}
self._routes = routes
def add_plugin(self, route, policy):
self._routes[route] = policy
def match(self, request):
if hasattr(request, 'auth_policy'):
return request.auth_policy
cur = None
cur_len = 0
for route, plug in self._routes.items():
r_len = len(route)
if r_len <= cur_len:
continue
path = request.path
if route == path[:r_len]:
if len(path) > r_len:
if path[r_len:r_len + 1] != '/':
continue
cur = plug
cur_len = r_len
if cur:
request.auth_policy = cur
else:
request.auth_policy = self._default
request.registry.notify(PluginPolicySelected(request, request.auth_policy))
return request.auth_policy
def authenticated_userid(self, request):
return self.match(request).authenticated_userid(request)
def unauthenticated_userid(self, request):
return self.match(request).unauthenticated_userid(request)
def effective_principals(self, request):
return self.match(request).effective_principals(request)
def remember(self, request, principal, **kw):
return self.match(request).remember(request, principal, **kw)
def forget(self, request):
return self.match(request).forget(request)
_TOKEN_FILTER_MAP = (
[chr(n) for n in range(32)] +
[chr(127), '\\', '"']
)
_TOKEN_FILTER_MAP = dict.fromkeys(_TOKEN_FILTER_MAP, None)
def _filter_token(tok):
return str(tok).translate(_TOKEN_FILTER_MAP)
def _format_kvpairs(**kwargs):
return ', '.join('{0!s}="{1}"'.format(k, _filter_token(v)) for (k, v) in kwargs.items())
def _generate_nonce(ts, secret, salt=None, chars=string.hexdigits.upper()):
# TODO: Add IP-address to nonce
if not salt:
try:
rng = random.SystemRandom()
except NotImplementedError:
rng = random
salt = ''.join(rng.choice(chars) for i in range(16))
ctx = hashlib.md5(('%s:%s:%s' % (ts, salt, secret)).encode())
return ('%s:%s:%s' % (ts, salt, ctx.hexdigest()))
def _is_valid_nonce(nonce, secret):
comp = nonce.split(':')
if len(comp) != 3:
return False
calc_nonce = _generate_nonce(comp[0], secret, comp[1])
if nonce == calc_nonce:
return True
return False
def _generate_digest_challenge(ts, secret, realm, opaque, stale=False):
nonce = _generate_nonce(ts, secret)
return 'Digest %s' % (_format_kvpairs(
realm=realm,
qop='auth',
nonce=nonce,
opaque=opaque,
algorithm='MD5',
stale='true' if stale else 'false'
),)
def _add_www_authenticate(request, secret, realm):
resp = request.response
if not resp.www_authenticate:
resp.www_authenticate = _generate_digest_challenge(
round(time.time()),
secret, realm, 'NPDIGEST'
)
def _parse_authorization(request, secret, realm):
authz = request.authorization
if (not authz) or (len(authz) != 2) or (authz[0] != 'Digest'):
_add_www_authenticate(request, secret, realm)
return None
params = authz[1]
if 'algorithm' not in params:
params['algorithm'] = 'MD5'
for required in ('username', 'realm', 'nonce', 'uri', 'response', 'cnonce', 'nc', 'opaque'):
if (required not in params) or ((required == 'opaque') and (params['opaque'] != 'NPDIGEST')):
_add_www_authenticate(request, secret, realm)
return None
return params
@implementer(IAuthenticationPolicy)
class DigestAuthenticationPolicy(object):
def __init__(self, secret, callback, realm='Realm'):
self.secret = secret
self.callback = callback
self.realm = realm
def authenticated_userid(self, request):
params = _parse_authorization(request, self.secret, self.realm)
if params is None:
return None
if not _is_valid_nonce(params['nonce'], self.secret):
_add_www_authenticate(request, self.secret, self.realm)
return None
userid = params['username']
if self.callback(params, request) is not None:
return 'u:%s' % userid
_add_www_authenticate(request, self.secret, self.realm)
def unauthenticated_userid(self, request):
params = _parse_authorization(request, self.secret, self.realm)
if params is None:
r | if not _is_valid_nonce(params['nonce'], self.secret):
_add_www_authenticate(request, self.secret, self.realm)
return None
return 'u:%s' % params['username']
def effective_principals(self, request):
creds = [Everyone]
params = _parse_authorization(request, self.secret, self.realm)
if params is None:
return creds
if not _is_valid_nonce(params['nonce'], self.secret):
_add_www_authenticate(request, self.secret, self.realm)
return creds
groups = self.callback(params, request)
if groups is None:
return creds
creds.append(Authenticated)
creds.append('u:%s' % params['username'])
creds.extend(groups)
return creds
def remember(self, request, principal, *kw):
return []
def forget(self, request):
return [('WWW-Authenticate', _generate_digest_challenge(
round(time.time()),
self.secret,
self.realm,
'NPDIGEST'
))]
| eturn None
| conditional_block |
auth.py | #!/usr/bin/env python
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-
#
# NetProfile: Authentication routines
# © Copyright 2013-2014 Alex 'Unik' Unigovsky
#
# This file is part of NetProfile.
# NetProfile is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public
# License as published by the Free Software Foundation, either
# version 3 of the License, or (at your option) any later
# version.
#
# NetProfile is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General
# Public License along with NetProfile. If not, see
# <http://www.gnu.org/licenses/>.
from __future__ import (
unicode_literals,
print_function,
absolute_import,
division
)
import hashlib
import random
import string
import time
from zope.interface import implementer
from pyramid.interfaces import IAuthenticationPolicy
from pyramid.security import (
Authenticated,
Everyone
)
class PluginPolicySelected(object):
def __init__(self, request, policy):
self.request = request
self.policy = policy
@implementer(IAuthenticationPolicy)
class P | object):
def __init__(self, default, routes=None):
self._default = default
if routes is None:
routes = {}
self._routes = routes
def add_plugin(self, route, policy):
self._routes[route] = policy
def match(self, request):
if hasattr(request, 'auth_policy'):
return request.auth_policy
cur = None
cur_len = 0
for route, plug in self._routes.items():
r_len = len(route)
if r_len <= cur_len:
continue
path = request.path
if route == path[:r_len]:
if len(path) > r_len:
if path[r_len:r_len + 1] != '/':
continue
cur = plug
cur_len = r_len
if cur:
request.auth_policy = cur
else:
request.auth_policy = self._default
request.registry.notify(PluginPolicySelected(request, request.auth_policy))
return request.auth_policy
def authenticated_userid(self, request):
return self.match(request).authenticated_userid(request)
def unauthenticated_userid(self, request):
return self.match(request).unauthenticated_userid(request)
def effective_principals(self, request):
return self.match(request).effective_principals(request)
def remember(self, request, principal, **kw):
return self.match(request).remember(request, principal, **kw)
def forget(self, request):
return self.match(request).forget(request)
_TOKEN_FILTER_MAP = (
[chr(n) for n in range(32)] +
[chr(127), '\\', '"']
)
_TOKEN_FILTER_MAP = dict.fromkeys(_TOKEN_FILTER_MAP, None)
def _filter_token(tok):
return str(tok).translate(_TOKEN_FILTER_MAP)
def _format_kvpairs(**kwargs):
return ', '.join('{0!s}="{1}"'.format(k, _filter_token(v)) for (k, v) in kwargs.items())
def _generate_nonce(ts, secret, salt=None, chars=string.hexdigits.upper()):
# TODO: Add IP-address to nonce
if not salt:
try:
rng = random.SystemRandom()
except NotImplementedError:
rng = random
salt = ''.join(rng.choice(chars) for i in range(16))
ctx = hashlib.md5(('%s:%s:%s' % (ts, salt, secret)).encode())
return ('%s:%s:%s' % (ts, salt, ctx.hexdigest()))
def _is_valid_nonce(nonce, secret):
comp = nonce.split(':')
if len(comp) != 3:
return False
calc_nonce = _generate_nonce(comp[0], secret, comp[1])
if nonce == calc_nonce:
return True
return False
def _generate_digest_challenge(ts, secret, realm, opaque, stale=False):
nonce = _generate_nonce(ts, secret)
return 'Digest %s' % (_format_kvpairs(
realm=realm,
qop='auth',
nonce=nonce,
opaque=opaque,
algorithm='MD5',
stale='true' if stale else 'false'
),)
def _add_www_authenticate(request, secret, realm):
resp = request.response
if not resp.www_authenticate:
resp.www_authenticate = _generate_digest_challenge(
round(time.time()),
secret, realm, 'NPDIGEST'
)
def _parse_authorization(request, secret, realm):
authz = request.authorization
if (not authz) or (len(authz) != 2) or (authz[0] != 'Digest'):
_add_www_authenticate(request, secret, realm)
return None
params = authz[1]
if 'algorithm' not in params:
params['algorithm'] = 'MD5'
for required in ('username', 'realm', 'nonce', 'uri', 'response', 'cnonce', 'nc', 'opaque'):
if (required not in params) or ((required == 'opaque') and (params['opaque'] != 'NPDIGEST')):
_add_www_authenticate(request, secret, realm)
return None
return params
@implementer(IAuthenticationPolicy)
class DigestAuthenticationPolicy(object):
def __init__(self, secret, callback, realm='Realm'):
self.secret = secret
self.callback = callback
self.realm = realm
def authenticated_userid(self, request):
params = _parse_authorization(request, self.secret, self.realm)
if params is None:
return None
if not _is_valid_nonce(params['nonce'], self.secret):
_add_www_authenticate(request, self.secret, self.realm)
return None
userid = params['username']
if self.callback(params, request) is not None:
return 'u:%s' % userid
_add_www_authenticate(request, self.secret, self.realm)
def unauthenticated_userid(self, request):
params = _parse_authorization(request, self.secret, self.realm)
if params is None:
return None
if not _is_valid_nonce(params['nonce'], self.secret):
_add_www_authenticate(request, self.secret, self.realm)
return None
return 'u:%s' % params['username']
def effective_principals(self, request):
creds = [Everyone]
params = _parse_authorization(request, self.secret, self.realm)
if params is None:
return creds
if not _is_valid_nonce(params['nonce'], self.secret):
_add_www_authenticate(request, self.secret, self.realm)
return creds
groups = self.callback(params, request)
if groups is None:
return creds
creds.append(Authenticated)
creds.append('u:%s' % params['username'])
creds.extend(groups)
return creds
def remember(self, request, principal, *kw):
return []
def forget(self, request):
return [('WWW-Authenticate', _generate_digest_challenge(
round(time.time()),
self.secret,
self.realm,
'NPDIGEST'
))]
| luginAuthenticationPolicy( | identifier_name |
index.js |
//Modules
var async = require('async');
var tools = require('./tools.js');
var fs = require('fs');
var pathMod = require('path');
var Handlebars = require('handlebars');
var vCard = require('vcards-js');
var vcardparser = require('vcardparser');
var _ = require('lodash');
_.mixin( require('lodash-deep') );
//Global Variables
var templates = {};
//Private functions
(function loadTemplates(){
var files = fs.readdirSync(__dirname + '/templates');
files.forEach(function(templateDir){
templates[templateDir] = fs.readFileSync(__dirname + '/templates/' + templateDir, {encoding : 'utf8'});
templates[templateDir] = Handlebars.compile(templates[templateDir]);
});
})();
//Public functions
var Sync = function( config ){
this.config = config;
this.protocol
};
Sync.prototype.createAddressbook = function( path, info, callback ){
if(!path){
return callback({err : "Error: path required"});
}
var body = templates['newAddressbook'](info);
path = path + tools.uuid() + '/';
this.request('MKCOL', path, body, function (err, res) {
if (err || res.statusCode !== 201) {
callback({err : err, statusCode : res.statusCode});
return;
}
callback(null, path);
});
};
Sync.prototype.modifyAddressbook = function( path, info, callback ){
if(!path){
return callback({err : "Error: path required"});
}
var body = templates['modifyAddressbook'](info);
this.request('PROPPATCH', path, body, function (err, res) {
if (err) {
callback({err : err});
return;
}
callback(null, path);
});
};
Sync.prototype.createContact = function ( path, info, callback ) {
var body = tools.jsonToVCard( info );
path = pathMod.join( path, tools.uuid() + '.vcf' );
this.request( 'PUT', {
path : path,
headers : {
'If-None-Match' : '*',
'Content-Type': 'text/vcard; charset=utf-8'
}}, body, function (err, res) {
if (err || res.statusCode !== 201) {
callback({err : err, statusCode : res.statusCode});
return;
}
callback(null, path);
});
};
Sync.prototype.deleteAddressbook = function ( path, callback ) {
this.request('DELETE', path, '', function (err, res) {
callback(err);
});
};
Sync.prototype.deleteContact = function ( path, callback ) {
this.request('DELETE', path, '', function (err, res) {
callback(err);
});
};
Sync.prototype.getAddressbooks = function( calHome, callback ){
var body = templates['getAddressbooks']();
this.request( 'PROPFIND', { path : calHome, depth : 1 }, body, function( error, res ){
tools.parseXML( res.body, function ( err, data ){
if( err ){
return callback( err );
}
var addressbooks = _.map(data.response, function(internal){
var newObj = {};
newObj.href = internal.href;
newObj = _.extend(newObj, _.deepGet(internal, 'propstat[0].prop[0]'));
newObj = _.reduce(newObj, tools.normalizeAddressbookAttribute, {});
return newObj;
});
addressbooks = _.filter(addressbooks, function(item){
return item.resourcetype.indexOf('addressbook') !== -1;
});
callback(null, addressbooks);
});
});
};
Sync.prototype.getContact = function( path, callback ){
this.request( 'GET', path, '', function( error, res ){
if(error || res.statusCode !== 200){
return callback('UNABLE TO RETRIEVE CONTACT');
}
vcardparser.parseString( res.body, function(err, json) {
if(err) {
return callback(err);
}
//newObj['address-data'] = tools.VCardToJson( json );
callback( null, tools.VCardToJson( json ) );
});
});
};
Sync.prototype.login = function( callback ){
this.request( 'OPTIONS', '', '', function( error, res ){
if(error){
callback(true);
}
else {
callback(null, res.statusCode === 200);
}
});
};
Sync.prototype.getHome = function( callback ){
this.request( 'PROPFIND', '', templates['getHome'](), function( error, res ){
tools.parseXML( res.body, function( err, data ){
if( err ){
return callback( err );
}
callback(null, _.deepGet(data, 'response[0].propstat[0].prop[0].current-user-principal[0].href[0]'));
});
});
};
Sync.prototype.getAddressbookHome = function( home, callback ){
this.request( 'PROPFIND', home, templates['getAddressbookHome'](), function( err, res ){
tools.parseXML( res.body, function( err, data ){
if( err ){
return callback( err );
}
callback(null, _.deepGet(data, 'response[0].propstat[0].prop[0].addressbook-home-set[0].href[0]'));
});
});
};
Sync.prototype.getContacts = function ( filter, path, callback ) {
filter = filter || {};
var body = templates['getContacts'](filter);
body = body.replace(/^\s*$[\n\r]{1,}/gm, '');
this.request('REPORT', { path : path, depth : 1 }, body, function (err, res) {
if (err) {
callback(err);
return;
}
tools.parseXML( res.body, function ( err, data ) {
if (err) {
return callback(err);
}
if(!data || !data.response){
return callback(null, []);
}
async.map( data.response, function(internal, callback){
var newObj = {};
newObj.href = internal.href;
newObj = _.extend(newObj, _.deepGet(internal, 'propstat[0].prop[0]'));
newObj = _.reduce(newObj, tools.normalizeAddressbookAttribute, {});
vcardparser.parseString(newObj['address-data'], function(err, json) {
if(err) {
return callback(err);
}
newObj['address-data'] = tools.VCardToJson( json );
callback( null, newObj );
});
}, callback);
});
});
};
Sync.prototype.modifyContact = function ( path, info, callback ) {
var that = this;
that.request( 'GET', path, '', function( error, res ){
if(error || res.statusCode !== 200){
return callback('UNABLE TO RETRIEVE CONTACT');
}
var etag = res.headers.etag;
var body = tools.jsonToVCard( info );
that.request(
'PUT',
{
path : path,
headers : {
'If-Match' : etag,
'Content-Type': 'text/vcard; charset=utf-8'
}
},
body,
function (err, res) {
if (err || res.statusCode !== 204) {
return callback({err : err, statusCode : res.statusCode});
}
callback(null, path);
}
);
});
};
Sync.prototype.request = function( type, path, body, callback ){
var opts = {
host : this.config.host,
path : typeof path === 'string' ? path || '' : path.path || '',
method : type,
data : body,
port : this.config.port || 5232,
headers : {
'brief' : 't',
'accept-language' : 'es-es',
//'accept-encoding' : 'gzip, deflate',
'connection' : 'keep-alive',
'user-agent' : 'Inevio CalDAV Client',
'prefer' : 'return=minimal',
'Accept' : '*/*',
'Content-Type' : 'text/xml',
'Content-Length' : body.length,
'Depth' : path.depth || 0,
'Authorization' : 'Basic ' + new Buffer( this.config.credentials.user + ':' + this.config.credentials.password ).toString('base64')
}
};
if(path.headers){
opts.headers = _.extend(opts.headers, path.headers);
}
var self = this;
tools.request( opts, this.config.secure, function( err, res ){
if( err ){
return callback( err );
}else if( res.statusCode === 302 ){
self.request( type, res.headers.location, body, callback );
}else |
});
};
module.exports = Sync;
| {
callback( null, res );
} | conditional_block |
index.js | //Modules
var async = require('async');
var tools = require('./tools.js');
var fs = require('fs');
var pathMod = require('path');
var Handlebars = require('handlebars');
var vCard = require('vcards-js');
var vcardparser = require('vcardparser');
var _ = require('lodash');
_.mixin( require('lodash-deep') );
//Global Variables
var templates = {};
//Private functions
(function loadTemplates(){
var files = fs.readdirSync(__dirname + '/templates');
files.forEach(function(templateDir){
templates[templateDir] = fs.readFileSync(__dirname + '/templates/' + templateDir, {encoding : 'utf8'});
templates[templateDir] = Handlebars.compile(templates[templateDir]);
});
})();
//Public functions
var Sync = function( config ){
this.config = config;
this.protocol
};
Sync.prototype.createAddressbook = function( path, info, callback ){
if(!path){
return callback({err : "Error: path required"});
}
var body = templates['newAddressbook'](info);
path = path + tools.uuid() + '/';
this.request('MKCOL', path, body, function (err, res) {
if (err || res.statusCode !== 201) {
callback({err : err, statusCode : res.statusCode});
return;
}
callback(null, path);
});
};
Sync.prototype.modifyAddressbook = function( path, info, callback ){
if(!path){
return callback({err : "Error: path required"});
}
var body = templates['modifyAddressbook'](info);
this.request('PROPPATCH', path, body, function (err, res) {
if (err) {
callback({err : err});
return;
}
callback(null, path);
});
};
Sync.prototype.createContact = function ( path, info, callback ) {
var body = tools.jsonToVCard( info );
path = pathMod.join( path, tools.uuid() + '.vcf' );
this.request( 'PUT', {
path : path,
headers : {
'If-None-Match' : '*',
'Content-Type': 'text/vcard; charset=utf-8'
}}, body, function (err, res) {
if (err || res.statusCode !== 201) {
callback({err : err, statusCode : res.statusCode});
return;
}
callback(null, path);
});
};
Sync.prototype.deleteAddressbook = function ( path, callback ) {
this.request('DELETE', path, '', function (err, res) {
callback(err);
});
};
Sync.prototype.deleteContact = function ( path, callback ) {
this.request('DELETE', path, '', function (err, res) {
callback(err);
});
};
Sync.prototype.getAddressbooks = function( calHome, callback ){
var body = templates['getAddressbooks']();
this.request( 'PROPFIND', { path : calHome, depth : 1 }, body, function( error, res ){
tools.parseXML( res.body, function ( err, data ){
if( err ){
return callback( err );
}
var addressbooks = _.map(data.response, function(internal){
var newObj = {};
newObj.href = internal.href;
newObj = _.extend(newObj, _.deepGet(internal, 'propstat[0].prop[0]'));
newObj = _.reduce(newObj, tools.normalizeAddressbookAttribute, {});
return newObj;
});
addressbooks = _.filter(addressbooks, function(item){
return item.resourcetype.indexOf('addressbook') !== -1;
});
callback(null, addressbooks);
});
});
};
Sync.prototype.getContact = function( path, callback ){
this.request( 'GET', path, '', function( error, res ){
if(error || res.statusCode !== 200){
return callback('UNABLE TO RETRIEVE CONTACT');
}
vcardparser.parseString( res.body, function(err, json) {
if(err) {
return callback(err);
}
//newObj['address-data'] = tools.VCardToJson( json );
callback( null, tools.VCardToJson( json ) );
});
});
};
Sync.prototype.login = function( callback ){
this.request( 'OPTIONS', '', '', function( error, res ){
if(error){
callback(true);
}
else {
callback(null, res.statusCode === 200);
}
});
};
Sync.prototype.getHome = function( callback ){
this.request( 'PROPFIND', '', templates['getHome'](), function( error, res ){
tools.parseXML( res.body, function( err, data ){
if( err ){
return callback( err );
}
callback(null, _.deepGet(data, 'response[0].propstat[0].prop[0].current-user-principal[0].href[0]'));
});
});
};
Sync.prototype.getAddressbookHome = function( home, callback ){
this.request( 'PROPFIND', home, templates['getAddressbookHome'](), function( err, res ){
tools.parseXML( res.body, function( err, data ){
| if( err ){
return callback( err );
}
callback(null, _.deepGet(data, 'response[0].propstat[0].prop[0].addressbook-home-set[0].href[0]'));
});
});
};
Sync.prototype.getContacts = function ( filter, path, callback ) {
filter = filter || {};
var body = templates['getContacts'](filter);
body = body.replace(/^\s*$[\n\r]{1,}/gm, '');
this.request('REPORT', { path : path, depth : 1 }, body, function (err, res) {
if (err) {
callback(err);
return;
}
tools.parseXML( res.body, function ( err, data ) {
if (err) {
return callback(err);
}
if(!data || !data.response){
return callback(null, []);
}
async.map( data.response, function(internal, callback){
var newObj = {};
newObj.href = internal.href;
newObj = _.extend(newObj, _.deepGet(internal, 'propstat[0].prop[0]'));
newObj = _.reduce(newObj, tools.normalizeAddressbookAttribute, {});
vcardparser.parseString(newObj['address-data'], function(err, json) {
if(err) {
return callback(err);
}
newObj['address-data'] = tools.VCardToJson( json );
callback( null, newObj );
});
}, callback);
});
});
};
Sync.prototype.modifyContact = function ( path, info, callback ) {
var that = this;
that.request( 'GET', path, '', function( error, res ){
if(error || res.statusCode !== 200){
return callback('UNABLE TO RETRIEVE CONTACT');
}
var etag = res.headers.etag;
var body = tools.jsonToVCard( info );
that.request(
'PUT',
{
path : path,
headers : {
'If-Match' : etag,
'Content-Type': 'text/vcard; charset=utf-8'
}
},
body,
function (err, res) {
if (err || res.statusCode !== 204) {
return callback({err : err, statusCode : res.statusCode});
}
callback(null, path);
}
);
});
};
Sync.prototype.request = function( type, path, body, callback ){
var opts = {
host : this.config.host,
path : typeof path === 'string' ? path || '' : path.path || '',
method : type,
data : body,
port : this.config.port || 5232,
headers : {
'brief' : 't',
'accept-language' : 'es-es',
//'accept-encoding' : 'gzip, deflate',
'connection' : 'keep-alive',
'user-agent' : 'Inevio CalDAV Client',
'prefer' : 'return=minimal',
'Accept' : '*/*',
'Content-Type' : 'text/xml',
'Content-Length' : body.length,
'Depth' : path.depth || 0,
'Authorization' : 'Basic ' + new Buffer( this.config.credentials.user + ':' + this.config.credentials.password ).toString('base64')
}
};
if(path.headers){
opts.headers = _.extend(opts.headers, path.headers);
}
var self = this;
tools.request( opts, this.config.secure, function( err, res ){
if( err ){
return callback( err );
}else if( res.statusCode === 302 ){
self.request( type, res.headers.location, body, callback );
}else{
callback( null, res );
}
});
};
module.exports = Sync; | random_line_split | |
stages_mergesort.js | // Test query stage merge sorting.
t = db.stages_mergesort;
t.drop();
var collname = "stages_mergesort";
var N = 10;
for (var i = 0; i < N; ++i) {
t.insert({foo: 1, bar: N - i - 1});
t.insert({baz: 1, bar: i});
}
t.ensureIndex({foo: 1, bar: 1});
t.ensureIndex({baz: 1, bar: 1});
// foo == 1
// We would (internally) use "": MinKey and "": MaxKey for the bar index bounds.
ixscan1 = {
ixscan: {
args: {
keyPattern: {foo: 1, bar: 1},
startKey: {foo: 1, bar: 0},
endKey: {foo: 1, bar: 100000},
startKeyInclusive: true,
endKeyInclusive: true,
direction: 1
}
}
};
// baz == 1
ixscan2 = {
ixscan: {
args: {
keyPattern: {baz: 1, bar: 1},
startKey: {baz: 1, bar: 0},
endKey: {baz: 1, bar: 100000},
startKeyInclusive: true,
endKeyInclusive: true,
direction: 1
} | }
};
mergesort = {
mergeSort: {args: {nodes: [ixscan1, ixscan2], pattern: {bar: 1}}}
};
res = db.runCommand({stageDebug: {plan: mergesort, collection: collname}});
assert.eq(res.ok, 1);
assert.eq(res.results.length, 2 * N);
assert.eq(res.results[0].bar, 0);
assert.eq(res.results[2 * N - 1].bar, N - 1); | random_line_split | |
stages_mergesort.js | // Test query stage merge sorting.
t = db.stages_mergesort;
t.drop();
var collname = "stages_mergesort";
var N = 10;
for (var i = 0; i < N; ++i) |
t.ensureIndex({foo: 1, bar: 1});
t.ensureIndex({baz: 1, bar: 1});
// foo == 1
// We would (internally) use "": MinKey and "": MaxKey for the bar index bounds.
ixscan1 = {
ixscan: {
args: {
keyPattern: {foo: 1, bar: 1},
startKey: {foo: 1, bar: 0},
endKey: {foo: 1, bar: 100000},
startKeyInclusive: true,
endKeyInclusive: true,
direction: 1
}
}
};
// baz == 1
ixscan2 = {
ixscan: {
args: {
keyPattern: {baz: 1, bar: 1},
startKey: {baz: 1, bar: 0},
endKey: {baz: 1, bar: 100000},
startKeyInclusive: true,
endKeyInclusive: true,
direction: 1
}
}
};
mergesort = {
mergeSort: {args: {nodes: [ixscan1, ixscan2], pattern: {bar: 1}}}
};
res = db.runCommand({stageDebug: {plan: mergesort, collection: collname}});
assert.eq(res.ok, 1);
assert.eq(res.results.length, 2 * N);
assert.eq(res.results[0].bar, 0);
assert.eq(res.results[2 * N - 1].bar, N - 1);
| {
t.insert({foo: 1, bar: N - i - 1});
t.insert({baz: 1, bar: i});
} | conditional_block |
bandcamp.py | # Copyright (C) 2015 Ariel George
#
# 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; version 2.
#
# 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.
"""Adds bandcamp album search support to the autotagger. Requires the
BeautifulSoup library.
"""
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import beets.ui
from beets.autotag.hooks import AlbumInfo, TrackInfo, Distance
from beets import plugins
from beetsplug import fetchart
import beets
import requests
from bs4 import BeautifulSoup
import isodate
import six
USER_AGENT = 'beets/{0} +http://beets.radbox.org/'.format(beets.__version__)
BANDCAMP_SEARCH = 'http://bandcamp.com/search?q={query}&page={page}'
BANDCAMP_ALBUM = 'album'
BANDCAMP_ARTIST = 'band'
BANDCAMP_TRACK = 'track'
ARTIST_TITLE_DELIMITER = ' - '
class BandcampPlugin(plugins.BeetsPlugin):
def __init__(self):
super(BandcampPlugin, self).__init__()
self.config.add({
'source_weight': 0.5,
'min_candidates': 5,
'lyrics': False,
'art': False,
'split_artist_title': False
})
self.import_stages = [self.imported]
self.register_listener('pluginload', self.loaded)
def loaded(self):
# Add our own artsource to the fetchart plugin.
# FIXME: This is ugly, but i didn't find another way to extend fetchart
# without declaring a new plugin.
if self.config['art']:
for plugin in plugins.find_plugins():
if isinstance(plugin, fetchart.FetchArtPlugin):
plugin.sources = [BandcampAlbumArt(plugin._log, self.config)] + plugin.sources
fetchart.ART_SOURCES['bandcamp'] = BandcampAlbumArt
fetchart.SOURCE_NAMES[BandcampAlbumArt] = 'bandcamp'
break
def album_distance(self, items, album_info, mapping):
"""Returns the album distance.
"""
dist = Distance()
if hasattr(album_info, 'data_source') and album_info.data_source == 'bandcamp':
dist.add('source', self.config['source_weight'].as_number())
return dist
def candidates(self, items, artist, album, va_likely, extra_tags=None):
"""Returns a list of AlbumInfo objects for bandcamp search results
matching an album and artist (if not various).
"""
return self.get_albums(album)
def album_for_id(self, album_id):
"""Fetches an album by its bandcamp ID and returns an AlbumInfo object
or None if the album is not found.
"""
# We use album url as id, so we just need to fetch and parse the
# album page.
url = album_id
return self.get_album_info(url)
def item_candidates(self, item, artist, album):
"""Returns a list of TrackInfo objects from a bandcamp search matching
a singleton.
"""
if item.title:
return self.get_tracks(item.title)
if item.album:
return self.get_tracks(item.album)
if item.artist:
return self.get_tracks(item.artist)
return []
def track_for_id(self, track_id):
"""Fetches a track by its bandcamp ID and returns a TrackInfo object
or None if the track is not found.
"""
url = track_id
return self.get_track_info(url)
def imported(self, session, task):
"""Import hook for fetching lyrics from bandcamp automatically.
"""
if self.config['lyrics']:
for item in task.imported_items():
# Only fetch lyrics for items from bandcamp
if hasattr(item, 'data_source') and item.data_source == 'bandcamp':
self.add_lyrics(item, True)
def get_albums(self, query):
"""Returns a list of AlbumInfo objects for a bandcamp search query.
"""
albums = []
for url in self._search(query, BANDCAMP_ALBUM):
album = self.get_album_info(url)
if album is not None:
albums.append(album)
return albums
def get_album_info(self, url):
"""Returns an AlbumInfo object for a bandcamp album page.
"""
try:
html = self._get(url)
name_section = html.find(id='name-section')
album = name_section.find(attrs={'itemprop': 'name'}).text.strip()
# Even though there is an item_id in some urls in bandcamp, it's not
# visible on the page and you can't search by the id, so we need to use
# the url as id.
album_id = url
artist = name_section.find(attrs={'itemprop': 'byArtist'}) .text.strip()
release = html.find('meta', attrs={'itemprop': 'datePublished'})['content']
release = isodate.parse_date(release)
artist_url = url.split('/album/')[0]
tracks = []
for row in html.find(id='track_table').find_all(attrs={'itemprop': 'tracks'}):
track = self._parse_album_track(row)
track.track_id = '{0}{1}'.format(artist_url, track.track_id)
tracks.append(track)
return AlbumInfo(album, album_id, artist, artist_url, tracks,
year=release.year, month=release.month,
day=release.day, country='XW', media='Digital Media',
data_source='bandcamp', data_url=url)
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while fetching album {0!r}: "
"{1}".format(url, e))
except (TypeError, AttributeError) as e:
self._log.debug("Unexpected html while scraping album {0!r}: {1}".format(url, e))
except BandcampException as e:
self._log.debug('Error: {0}'.format(e))
def get_tracks(self, query):
"""Returns a list of TrackInfo objects for a bandcamp search query.
"""
track_urls = self._search(query, BANDCAMP_TRACK)
return [self.get_track_info(url) for url in track_urls]
def get_track_info(self, url):
"""Returns a TrackInfo object for a bandcamp track page.
"""
try:
html = self._get(url)
name_section = html.find(id='name-section')
title = name_section.find(attrs={'itemprop': 'name'}).text.strip()
artist_url = url.split('/track/')[0]
artist = name_section.find(attrs={'itemprop': 'byArtist'}).text.strip()
if self.config['split_artist_title']:
artist_from_title, title = self._split_artist_title(title)
if artist_from_title is not None:
artist = artist_from_title
try:
duration = html.find('meta', attrs={'itemprop': 'duration'})['content']
track_length = float(duration)
if track_length == 0:
track_length = None
except TypeError:
track_length = None
return TrackInfo(title, url, length=track_length, artist=artist,
artist_id=artist_url, data_source='bandcamp',
media='Digital Media', data_url=url)
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while fetching track {0!r}: "
"{1}".format(url, e))
def add_lyrics(self, item, write = False):
"""Fetch and store lyrics for a single item. If ``write``, then the
lyrics will also be written to the file itself."""
# Skip if the item already has lyrics.
if item.lyrics:
self._log.info('lyrics already present: {0}', item)
return
lyrics = self.get_item_lyrics(item)
if lyrics:
self._log.info('fetched lyrics: {0}', item)
else:
self._log.info('lyrics not found: {0}', item)
return
item.lyrics = lyrics
if write:
item.try_write()
item.store()
def get_item_lyrics(self, item):
"""Get the lyrics for item from bandcamp.
"""
try:
# The track id is the bandcamp url when item.data_source is bandcamp.
html = self._get(item.mb_trackid)
lyrics = html.find(attrs={'class': 'lyricsText'})
if lyrics:
return lyrics.text
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while fetching lyrics for track {0!r}: "
"{1}".format(item.mb_trackid, e))
return None
| def _search(self, query, search_type=BANDCAMP_ALBUM, page=1):
"""Returns a list of bandcamp urls for items of type search_type
matching the query.
"""
if search_type not in [BANDCAMP_ARTIST, BANDCAMP_ALBUM, BANDCAMP_TRACK]:
self._log.debug('Invalid type for search: {0}'.format(search_type))
return None
try:
urls = []
# Search bandcamp until min_candidates results have been found or
# we hit the last page in the results.
while len(urls) < self.config['min_candidates'].as_number():
self._log.debug('Searching {}, page {}'.format(search_type, page))
results = self._get(BANDCAMP_SEARCH.format(query=query, page=page))
clazz = 'searchresult {0}'.format(search_type)
for result in results.find_all('li', attrs={'class': clazz}):
a = result.find(attrs={'class': 'heading'}).a
if a is not None:
urls.append(a['href'].split('?')[0])
# Stop searching if we are on the last page.
if not results.find('a', attrs={'class': 'next'}):
break
page += 1
return urls
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while searching page {0} for {1!r}: "
"{2}".format(page, query, e))
return []
def _get(self, url):
"""Returns a BeautifulSoup object with the contents of url.
"""
headers = {'User-Agent': USER_AGENT}
r = requests.get(url, headers=headers)
r.raise_for_status()
return BeautifulSoup(r.text, 'html.parser')
def _parse_album_track(self, track_html):
"""Returns a TrackInfo derived from the html describing a track in a
bandcamp album page.
"""
track_num = track_html['rel'].split('=')[1]
track_num = int(track_num)
title_html = track_html.find(attrs={'class': 'title-col'})
title = title_html.find(attrs={'itemprop': 'name'}).text.strip()
artist = None
if self.config['split_artist_title']:
artist, title = self._split_artist_title(title)
track_url = title_html.find(attrs={'itemprop': 'url'})
if track_url is None:
raise BandcampException('No track url (id) for track {0} - {1}'.format(track_num, title))
track_id = track_url['href']
try:
duration = title_html.find('meta', attrs={'itemprop': 'duration'})['content']
duration = duration.replace('P', 'PT')
track_length = isodate.parse_duration(duration).total_seconds()
except TypeError:
track_length = None
return TrackInfo(title, track_id, index=track_num, length=track_length, artist=artist)
def _split_artist_title(self, title):
"""Returns artist and title by splitting title on ARTIST_TITLE_DELIMITER.
"""
parts = title.split(ARTIST_TITLE_DELIMITER)
if len(parts) == 1:
return None, title
return parts[0], ARTIST_TITLE_DELIMITER.join(parts[1:])
class BandcampAlbumArt(fetchart.RemoteArtSource):
NAME = u"Bandcamp"
def get(self, album, plugin, paths):
"""Return the url for the cover from the bandcamp album page.
This only returns cover art urls for bandcamp albums (by id).
"""
if isinstance(album.mb_albumid, six.string_types) and 'bandcamp' in album.mb_albumid:
try:
headers = {'User-Agent': USER_AGENT}
r = requests.get(album.mb_albumid, headers=headers)
r.raise_for_status()
album_html = BeautifulSoup(r.text, 'html.parser').find(id='tralbumArt')
image_url = album_html.find('a', attrs={'class': 'popupImage'})['href']
yield self._candidate(url=image_url,
match=fetchart.Candidate.MATCH_EXACT)
except requests.exceptions.RequestException as e:
self._log.debug("Communication error getting art for {0}: {1}"
.format(album, e))
except ValueError:
pass
class BandcampException(Exception):
pass | random_line_split | |
bandcamp.py | # Copyright (C) 2015 Ariel George
#
# 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; version 2.
#
# 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.
"""Adds bandcamp album search support to the autotagger. Requires the
BeautifulSoup library.
"""
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import beets.ui
from beets.autotag.hooks import AlbumInfo, TrackInfo, Distance
from beets import plugins
from beetsplug import fetchart
import beets
import requests
from bs4 import BeautifulSoup
import isodate
import six
USER_AGENT = 'beets/{0} +http://beets.radbox.org/'.format(beets.__version__)
BANDCAMP_SEARCH = 'http://bandcamp.com/search?q={query}&page={page}'
BANDCAMP_ALBUM = 'album'
BANDCAMP_ARTIST = 'band'
BANDCAMP_TRACK = 'track'
ARTIST_TITLE_DELIMITER = ' - '
class BandcampPlugin(plugins.BeetsPlugin):
def __init__(self):
super(BandcampPlugin, self).__init__()
self.config.add({
'source_weight': 0.5,
'min_candidates': 5,
'lyrics': False,
'art': False,
'split_artist_title': False
})
self.import_stages = [self.imported]
self.register_listener('pluginload', self.loaded)
def loaded(self):
# Add our own artsource to the fetchart plugin.
# FIXME: This is ugly, but i didn't find another way to extend fetchart
# without declaring a new plugin.
if self.config['art']:
for plugin in plugins.find_plugins():
if isinstance(plugin, fetchart.FetchArtPlugin):
plugin.sources = [BandcampAlbumArt(plugin._log, self.config)] + plugin.sources
fetchart.ART_SOURCES['bandcamp'] = BandcampAlbumArt
fetchart.SOURCE_NAMES[BandcampAlbumArt] = 'bandcamp'
break
def album_distance(self, items, album_info, mapping):
"""Returns the album distance.
"""
dist = Distance()
if hasattr(album_info, 'data_source') and album_info.data_source == 'bandcamp':
dist.add('source', self.config['source_weight'].as_number())
return dist
def candidates(self, items, artist, album, va_likely, extra_tags=None):
"""Returns a list of AlbumInfo objects for bandcamp search results
matching an album and artist (if not various).
"""
return self.get_albums(album)
def album_for_id(self, album_id):
"""Fetches an album by its bandcamp ID and returns an AlbumInfo object
or None if the album is not found.
"""
# We use album url as id, so we just need to fetch and parse the
# album page.
url = album_id
return self.get_album_info(url)
def item_candidates(self, item, artist, album):
"""Returns a list of TrackInfo objects from a bandcamp search matching
a singleton.
"""
if item.title:
return self.get_tracks(item.title)
if item.album:
return self.get_tracks(item.album)
if item.artist:
return self.get_tracks(item.artist)
return []
def track_for_id(self, track_id):
"""Fetches a track by its bandcamp ID and returns a TrackInfo object
or None if the track is not found.
"""
url = track_id
return self.get_track_info(url)
def imported(self, session, task):
"""Import hook for fetching lyrics from bandcamp automatically.
"""
if self.config['lyrics']:
for item in task.imported_items():
# Only fetch lyrics for items from bandcamp
if hasattr(item, 'data_source') and item.data_source == 'bandcamp':
self.add_lyrics(item, True)
def get_albums(self, query):
"""Returns a list of AlbumInfo objects for a bandcamp search query.
"""
albums = []
for url in self._search(query, BANDCAMP_ALBUM):
album = self.get_album_info(url)
if album is not None:
albums.append(album)
return albums
def get_album_info(self, url):
"""Returns an AlbumInfo object for a bandcamp album page.
"""
try:
html = self._get(url)
name_section = html.find(id='name-section')
album = name_section.find(attrs={'itemprop': 'name'}).text.strip()
# Even though there is an item_id in some urls in bandcamp, it's not
# visible on the page and you can't search by the id, so we need to use
# the url as id.
album_id = url
artist = name_section.find(attrs={'itemprop': 'byArtist'}) .text.strip()
release = html.find('meta', attrs={'itemprop': 'datePublished'})['content']
release = isodate.parse_date(release)
artist_url = url.split('/album/')[0]
tracks = []
for row in html.find(id='track_table').find_all(attrs={'itemprop': 'tracks'}):
track = self._parse_album_track(row)
track.track_id = '{0}{1}'.format(artist_url, track.track_id)
tracks.append(track)
return AlbumInfo(album, album_id, artist, artist_url, tracks,
year=release.year, month=release.month,
day=release.day, country='XW', media='Digital Media',
data_source='bandcamp', data_url=url)
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while fetching album {0!r}: "
"{1}".format(url, e))
except (TypeError, AttributeError) as e:
self._log.debug("Unexpected html while scraping album {0!r}: {1}".format(url, e))
except BandcampException as e:
self._log.debug('Error: {0}'.format(e))
def get_tracks(self, query):
"""Returns a list of TrackInfo objects for a bandcamp search query.
"""
track_urls = self._search(query, BANDCAMP_TRACK)
return [self.get_track_info(url) for url in track_urls]
def get_track_info(self, url):
"""Returns a TrackInfo object for a bandcamp track page.
"""
try:
html = self._get(url)
name_section = html.find(id='name-section')
title = name_section.find(attrs={'itemprop': 'name'}).text.strip()
artist_url = url.split('/track/')[0]
artist = name_section.find(attrs={'itemprop': 'byArtist'}).text.strip()
if self.config['split_artist_title']:
artist_from_title, title = self._split_artist_title(title)
if artist_from_title is not None:
artist = artist_from_title
try:
duration = html.find('meta', attrs={'itemprop': 'duration'})['content']
track_length = float(duration)
if track_length == 0:
track_length = None
except TypeError:
track_length = None
return TrackInfo(title, url, length=track_length, artist=artist,
artist_id=artist_url, data_source='bandcamp',
media='Digital Media', data_url=url)
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while fetching track {0!r}: "
"{1}".format(url, e))
def add_lyrics(self, item, write = False):
"""Fetch and store lyrics for a single item. If ``write``, then the
lyrics will also be written to the file itself."""
# Skip if the item already has lyrics.
if item.lyrics:
self._log.info('lyrics already present: {0}', item)
return
lyrics = self.get_item_lyrics(item)
if lyrics:
self._log.info('fetched lyrics: {0}', item)
else:
self._log.info('lyrics not found: {0}', item)
return
item.lyrics = lyrics
if write:
item.try_write()
item.store()
def get_item_lyrics(self, item):
"""Get the lyrics for item from bandcamp.
"""
try:
# The track id is the bandcamp url when item.data_source is bandcamp.
html = self._get(item.mb_trackid)
lyrics = html.find(attrs={'class': 'lyricsText'})
if lyrics:
return lyrics.text
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while fetching lyrics for track {0!r}: "
"{1}".format(item.mb_trackid, e))
return None
def _search(self, query, search_type=BANDCAMP_ALBUM, page=1):
"""Returns a list of bandcamp urls for items of type search_type
matching the query.
"""
if search_type not in [BANDCAMP_ARTIST, BANDCAMP_ALBUM, BANDCAMP_TRACK]:
self._log.debug('Invalid type for search: {0}'.format(search_type))
return None
try:
urls = []
# Search bandcamp until min_candidates results have been found or
# we hit the last page in the results.
while len(urls) < self.config['min_candidates'].as_number():
self._log.debug('Searching {}, page {}'.format(search_type, page))
results = self._get(BANDCAMP_SEARCH.format(query=query, page=page))
clazz = 'searchresult {0}'.format(search_type)
for result in results.find_all('li', attrs={'class': clazz}):
a = result.find(attrs={'class': 'heading'}).a
if a is not None:
urls.append(a['href'].split('?')[0])
# Stop searching if we are on the last page.
if not results.find('a', attrs={'class': 'next'}):
break
page += 1
return urls
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while searching page {0} for {1!r}: "
"{2}".format(page, query, e))
return []
def _get(self, url):
"""Returns a BeautifulSoup object with the contents of url.
"""
headers = {'User-Agent': USER_AGENT}
r = requests.get(url, headers=headers)
r.raise_for_status()
return BeautifulSoup(r.text, 'html.parser')
def _parse_album_track(self, track_html):
"""Returns a TrackInfo derived from the html describing a track in a
bandcamp album page.
"""
track_num = track_html['rel'].split('=')[1]
track_num = int(track_num)
title_html = track_html.find(attrs={'class': 'title-col'})
title = title_html.find(attrs={'itemprop': 'name'}).text.strip()
artist = None
if self.config['split_artist_title']:
artist, title = self._split_artist_title(title)
track_url = title_html.find(attrs={'itemprop': 'url'})
if track_url is None:
raise BandcampException('No track url (id) for track {0} - {1}'.format(track_num, title))
track_id = track_url['href']
try:
duration = title_html.find('meta', attrs={'itemprop': 'duration'})['content']
duration = duration.replace('P', 'PT')
track_length = isodate.parse_duration(duration).total_seconds()
except TypeError:
track_length = None
return TrackInfo(title, track_id, index=track_num, length=track_length, artist=artist)
def | (self, title):
"""Returns artist and title by splitting title on ARTIST_TITLE_DELIMITER.
"""
parts = title.split(ARTIST_TITLE_DELIMITER)
if len(parts) == 1:
return None, title
return parts[0], ARTIST_TITLE_DELIMITER.join(parts[1:])
class BandcampAlbumArt(fetchart.RemoteArtSource):
NAME = u"Bandcamp"
def get(self, album, plugin, paths):
"""Return the url for the cover from the bandcamp album page.
This only returns cover art urls for bandcamp albums (by id).
"""
if isinstance(album.mb_albumid, six.string_types) and 'bandcamp' in album.mb_albumid:
try:
headers = {'User-Agent': USER_AGENT}
r = requests.get(album.mb_albumid, headers=headers)
r.raise_for_status()
album_html = BeautifulSoup(r.text, 'html.parser').find(id='tralbumArt')
image_url = album_html.find('a', attrs={'class': 'popupImage'})['href']
yield self._candidate(url=image_url,
match=fetchart.Candidate.MATCH_EXACT)
except requests.exceptions.RequestException as e:
self._log.debug("Communication error getting art for {0}: {1}"
.format(album, e))
except ValueError:
pass
class BandcampException(Exception):
pass
| _split_artist_title | identifier_name |
bandcamp.py | # Copyright (C) 2015 Ariel George
#
# 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; version 2.
#
# 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.
"""Adds bandcamp album search support to the autotagger. Requires the
BeautifulSoup library.
"""
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import beets.ui
from beets.autotag.hooks import AlbumInfo, TrackInfo, Distance
from beets import plugins
from beetsplug import fetchart
import beets
import requests
from bs4 import BeautifulSoup
import isodate
import six
USER_AGENT = 'beets/{0} +http://beets.radbox.org/'.format(beets.__version__)
BANDCAMP_SEARCH = 'http://bandcamp.com/search?q={query}&page={page}'
BANDCAMP_ALBUM = 'album'
BANDCAMP_ARTIST = 'band'
BANDCAMP_TRACK = 'track'
ARTIST_TITLE_DELIMITER = ' - '
class BandcampPlugin(plugins.BeetsPlugin):
def __init__(self):
super(BandcampPlugin, self).__init__()
self.config.add({
'source_weight': 0.5,
'min_candidates': 5,
'lyrics': False,
'art': False,
'split_artist_title': False
})
self.import_stages = [self.imported]
self.register_listener('pluginload', self.loaded)
def loaded(self):
# Add our own artsource to the fetchart plugin.
# FIXME: This is ugly, but i didn't find another way to extend fetchart
# without declaring a new plugin.
if self.config['art']:
for plugin in plugins.find_plugins():
if isinstance(plugin, fetchart.FetchArtPlugin):
plugin.sources = [BandcampAlbumArt(plugin._log, self.config)] + plugin.sources
fetchart.ART_SOURCES['bandcamp'] = BandcampAlbumArt
fetchart.SOURCE_NAMES[BandcampAlbumArt] = 'bandcamp'
break
def album_distance(self, items, album_info, mapping):
"""Returns the album distance.
"""
dist = Distance()
if hasattr(album_info, 'data_source') and album_info.data_source == 'bandcamp':
dist.add('source', self.config['source_weight'].as_number())
return dist
def candidates(self, items, artist, album, va_likely, extra_tags=None):
"""Returns a list of AlbumInfo objects for bandcamp search results
matching an album and artist (if not various).
"""
return self.get_albums(album)
def album_for_id(self, album_id):
"""Fetches an album by its bandcamp ID and returns an AlbumInfo object
or None if the album is not found.
"""
# We use album url as id, so we just need to fetch and parse the
# album page.
url = album_id
return self.get_album_info(url)
def item_candidates(self, item, artist, album):
"""Returns a list of TrackInfo objects from a bandcamp search matching
a singleton.
"""
if item.title:
return self.get_tracks(item.title)
if item.album:
return self.get_tracks(item.album)
if item.artist:
return self.get_tracks(item.artist)
return []
def track_for_id(self, track_id):
"""Fetches a track by its bandcamp ID and returns a TrackInfo object
or None if the track is not found.
"""
url = track_id
return self.get_track_info(url)
def imported(self, session, task):
"""Import hook for fetching lyrics from bandcamp automatically.
"""
if self.config['lyrics']:
for item in task.imported_items():
# Only fetch lyrics for items from bandcamp
if hasattr(item, 'data_source') and item.data_source == 'bandcamp':
self.add_lyrics(item, True)
def get_albums(self, query):
"""Returns a list of AlbumInfo objects for a bandcamp search query.
"""
albums = []
for url in self._search(query, BANDCAMP_ALBUM):
album = self.get_album_info(url)
if album is not None:
albums.append(album)
return albums
def get_album_info(self, url):
"""Returns an AlbumInfo object for a bandcamp album page.
"""
try:
html = self._get(url)
name_section = html.find(id='name-section')
album = name_section.find(attrs={'itemprop': 'name'}).text.strip()
# Even though there is an item_id in some urls in bandcamp, it's not
# visible on the page and you can't search by the id, so we need to use
# the url as id.
album_id = url
artist = name_section.find(attrs={'itemprop': 'byArtist'}) .text.strip()
release = html.find('meta', attrs={'itemprop': 'datePublished'})['content']
release = isodate.parse_date(release)
artist_url = url.split('/album/')[0]
tracks = []
for row in html.find(id='track_table').find_all(attrs={'itemprop': 'tracks'}):
track = self._parse_album_track(row)
track.track_id = '{0}{1}'.format(artist_url, track.track_id)
tracks.append(track)
return AlbumInfo(album, album_id, artist, artist_url, tracks,
year=release.year, month=release.month,
day=release.day, country='XW', media='Digital Media',
data_source='bandcamp', data_url=url)
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while fetching album {0!r}: "
"{1}".format(url, e))
except (TypeError, AttributeError) as e:
self._log.debug("Unexpected html while scraping album {0!r}: {1}".format(url, e))
except BandcampException as e:
self._log.debug('Error: {0}'.format(e))
def get_tracks(self, query):
"""Returns a list of TrackInfo objects for a bandcamp search query.
"""
track_urls = self._search(query, BANDCAMP_TRACK)
return [self.get_track_info(url) for url in track_urls]
def get_track_info(self, url):
"""Returns a TrackInfo object for a bandcamp track page.
"""
try:
html = self._get(url)
name_section = html.find(id='name-section')
title = name_section.find(attrs={'itemprop': 'name'}).text.strip()
artist_url = url.split('/track/')[0]
artist = name_section.find(attrs={'itemprop': 'byArtist'}).text.strip()
if self.config['split_artist_title']:
artist_from_title, title = self._split_artist_title(title)
if artist_from_title is not None:
artist = artist_from_title
try:
duration = html.find('meta', attrs={'itemprop': 'duration'})['content']
track_length = float(duration)
if track_length == 0:
track_length = None
except TypeError:
track_length = None
return TrackInfo(title, url, length=track_length, artist=artist,
artist_id=artist_url, data_source='bandcamp',
media='Digital Media', data_url=url)
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while fetching track {0!r}: "
"{1}".format(url, e))
def add_lyrics(self, item, write = False):
"""Fetch and store lyrics for a single item. If ``write``, then the
lyrics will also be written to the file itself."""
# Skip if the item already has lyrics.
if item.lyrics:
self._log.info('lyrics already present: {0}', item)
return
lyrics = self.get_item_lyrics(item)
if lyrics:
self._log.info('fetched lyrics: {0}', item)
else:
self._log.info('lyrics not found: {0}', item)
return
item.lyrics = lyrics
if write:
item.try_write()
item.store()
def get_item_lyrics(self, item):
"""Get the lyrics for item from bandcamp.
"""
try:
# The track id is the bandcamp url when item.data_source is bandcamp.
html = self._get(item.mb_trackid)
lyrics = html.find(attrs={'class': 'lyricsText'})
if lyrics:
return lyrics.text
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while fetching lyrics for track {0!r}: "
"{1}".format(item.mb_trackid, e))
return None
def _search(self, query, search_type=BANDCAMP_ALBUM, page=1):
"""Returns a list of bandcamp urls for items of type search_type
matching the query.
"""
if search_type not in [BANDCAMP_ARTIST, BANDCAMP_ALBUM, BANDCAMP_TRACK]:
self._log.debug('Invalid type for search: {0}'.format(search_type))
return None
try:
urls = []
# Search bandcamp until min_candidates results have been found or
# we hit the last page in the results.
while len(urls) < self.config['min_candidates'].as_number():
self._log.debug('Searching {}, page {}'.format(search_type, page))
results = self._get(BANDCAMP_SEARCH.format(query=query, page=page))
clazz = 'searchresult {0}'.format(search_type)
for result in results.find_all('li', attrs={'class': clazz}):
a = result.find(attrs={'class': 'heading'}).a
if a is not None:
urls.append(a['href'].split('?')[0])
# Stop searching if we are on the last page.
if not results.find('a', attrs={'class': 'next'}):
break
page += 1
return urls
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while searching page {0} for {1!r}: "
"{2}".format(page, query, e))
return []
def _get(self, url):
"""Returns a BeautifulSoup object with the contents of url.
"""
headers = {'User-Agent': USER_AGENT}
r = requests.get(url, headers=headers)
r.raise_for_status()
return BeautifulSoup(r.text, 'html.parser')
def _parse_album_track(self, track_html):
"""Returns a TrackInfo derived from the html describing a track in a
bandcamp album page.
"""
track_num = track_html['rel'].split('=')[1]
track_num = int(track_num)
title_html = track_html.find(attrs={'class': 'title-col'})
title = title_html.find(attrs={'itemprop': 'name'}).text.strip()
artist = None
if self.config['split_artist_title']:
artist, title = self._split_artist_title(title)
track_url = title_html.find(attrs={'itemprop': 'url'})
if track_url is None:
|
track_id = track_url['href']
try:
duration = title_html.find('meta', attrs={'itemprop': 'duration'})['content']
duration = duration.replace('P', 'PT')
track_length = isodate.parse_duration(duration).total_seconds()
except TypeError:
track_length = None
return TrackInfo(title, track_id, index=track_num, length=track_length, artist=artist)
def _split_artist_title(self, title):
"""Returns artist and title by splitting title on ARTIST_TITLE_DELIMITER.
"""
parts = title.split(ARTIST_TITLE_DELIMITER)
if len(parts) == 1:
return None, title
return parts[0], ARTIST_TITLE_DELIMITER.join(parts[1:])
class BandcampAlbumArt(fetchart.RemoteArtSource):
NAME = u"Bandcamp"
def get(self, album, plugin, paths):
"""Return the url for the cover from the bandcamp album page.
This only returns cover art urls for bandcamp albums (by id).
"""
if isinstance(album.mb_albumid, six.string_types) and 'bandcamp' in album.mb_albumid:
try:
headers = {'User-Agent': USER_AGENT}
r = requests.get(album.mb_albumid, headers=headers)
r.raise_for_status()
album_html = BeautifulSoup(r.text, 'html.parser').find(id='tralbumArt')
image_url = album_html.find('a', attrs={'class': 'popupImage'})['href']
yield self._candidate(url=image_url,
match=fetchart.Candidate.MATCH_EXACT)
except requests.exceptions.RequestException as e:
self._log.debug("Communication error getting art for {0}: {1}"
.format(album, e))
except ValueError:
pass
class BandcampException(Exception):
pass
| raise BandcampException('No track url (id) for track {0} - {1}'.format(track_num, title)) | conditional_block |
bandcamp.py | # Copyright (C) 2015 Ariel George
#
# 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; version 2.
#
# 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.
"""Adds bandcamp album search support to the autotagger. Requires the
BeautifulSoup library.
"""
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import beets.ui
from beets.autotag.hooks import AlbumInfo, TrackInfo, Distance
from beets import plugins
from beetsplug import fetchart
import beets
import requests
from bs4 import BeautifulSoup
import isodate
import six
USER_AGENT = 'beets/{0} +http://beets.radbox.org/'.format(beets.__version__)
BANDCAMP_SEARCH = 'http://bandcamp.com/search?q={query}&page={page}'
BANDCAMP_ALBUM = 'album'
BANDCAMP_ARTIST = 'band'
BANDCAMP_TRACK = 'track'
ARTIST_TITLE_DELIMITER = ' - '
class BandcampPlugin(plugins.BeetsPlugin):
def __init__(self):
super(BandcampPlugin, self).__init__()
self.config.add({
'source_weight': 0.5,
'min_candidates': 5,
'lyrics': False,
'art': False,
'split_artist_title': False
})
self.import_stages = [self.imported]
self.register_listener('pluginload', self.loaded)
def loaded(self):
# Add our own artsource to the fetchart plugin.
# FIXME: This is ugly, but i didn't find another way to extend fetchart
# without declaring a new plugin.
if self.config['art']:
for plugin in plugins.find_plugins():
if isinstance(plugin, fetchart.FetchArtPlugin):
plugin.sources = [BandcampAlbumArt(plugin._log, self.config)] + plugin.sources
fetchart.ART_SOURCES['bandcamp'] = BandcampAlbumArt
fetchart.SOURCE_NAMES[BandcampAlbumArt] = 'bandcamp'
break
def album_distance(self, items, album_info, mapping):
"""Returns the album distance.
"""
dist = Distance()
if hasattr(album_info, 'data_source') and album_info.data_source == 'bandcamp':
dist.add('source', self.config['source_weight'].as_number())
return dist
def candidates(self, items, artist, album, va_likely, extra_tags=None):
"""Returns a list of AlbumInfo objects for bandcamp search results
matching an album and artist (if not various).
"""
return self.get_albums(album)
def album_for_id(self, album_id):
"""Fetches an album by its bandcamp ID and returns an AlbumInfo object
or None if the album is not found.
"""
# We use album url as id, so we just need to fetch and parse the
# album page.
url = album_id
return self.get_album_info(url)
def item_candidates(self, item, artist, album):
"""Returns a list of TrackInfo objects from a bandcamp search matching
a singleton.
"""
if item.title:
return self.get_tracks(item.title)
if item.album:
return self.get_tracks(item.album)
if item.artist:
return self.get_tracks(item.artist)
return []
def track_for_id(self, track_id):
"""Fetches a track by its bandcamp ID and returns a TrackInfo object
or None if the track is not found.
"""
url = track_id
return self.get_track_info(url)
def imported(self, session, task):
"""Import hook for fetching lyrics from bandcamp automatically.
"""
if self.config['lyrics']:
for item in task.imported_items():
# Only fetch lyrics for items from bandcamp
if hasattr(item, 'data_source') and item.data_source == 'bandcamp':
self.add_lyrics(item, True)
def get_albums(self, query):
"""Returns a list of AlbumInfo objects for a bandcamp search query.
"""
albums = []
for url in self._search(query, BANDCAMP_ALBUM):
album = self.get_album_info(url)
if album is not None:
albums.append(album)
return albums
def get_album_info(self, url):
"""Returns an AlbumInfo object for a bandcamp album page.
"""
try:
html = self._get(url)
name_section = html.find(id='name-section')
album = name_section.find(attrs={'itemprop': 'name'}).text.strip()
# Even though there is an item_id in some urls in bandcamp, it's not
# visible on the page and you can't search by the id, so we need to use
# the url as id.
album_id = url
artist = name_section.find(attrs={'itemprop': 'byArtist'}) .text.strip()
release = html.find('meta', attrs={'itemprop': 'datePublished'})['content']
release = isodate.parse_date(release)
artist_url = url.split('/album/')[0]
tracks = []
for row in html.find(id='track_table').find_all(attrs={'itemprop': 'tracks'}):
track = self._parse_album_track(row)
track.track_id = '{0}{1}'.format(artist_url, track.track_id)
tracks.append(track)
return AlbumInfo(album, album_id, artist, artist_url, tracks,
year=release.year, month=release.month,
day=release.day, country='XW', media='Digital Media',
data_source='bandcamp', data_url=url)
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while fetching album {0!r}: "
"{1}".format(url, e))
except (TypeError, AttributeError) as e:
self._log.debug("Unexpected html while scraping album {0!r}: {1}".format(url, e))
except BandcampException as e:
self._log.debug('Error: {0}'.format(e))
def get_tracks(self, query):
"""Returns a list of TrackInfo objects for a bandcamp search query.
"""
track_urls = self._search(query, BANDCAMP_TRACK)
return [self.get_track_info(url) for url in track_urls]
def get_track_info(self, url):
"""Returns a TrackInfo object for a bandcamp track page.
"""
try:
html = self._get(url)
name_section = html.find(id='name-section')
title = name_section.find(attrs={'itemprop': 'name'}).text.strip()
artist_url = url.split('/track/')[0]
artist = name_section.find(attrs={'itemprop': 'byArtist'}).text.strip()
if self.config['split_artist_title']:
artist_from_title, title = self._split_artist_title(title)
if artist_from_title is not None:
artist = artist_from_title
try:
duration = html.find('meta', attrs={'itemprop': 'duration'})['content']
track_length = float(duration)
if track_length == 0:
track_length = None
except TypeError:
track_length = None
return TrackInfo(title, url, length=track_length, artist=artist,
artist_id=artist_url, data_source='bandcamp',
media='Digital Media', data_url=url)
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while fetching track {0!r}: "
"{1}".format(url, e))
def add_lyrics(self, item, write = False):
"""Fetch and store lyrics for a single item. If ``write``, then the
lyrics will also be written to the file itself."""
# Skip if the item already has lyrics.
if item.lyrics:
self._log.info('lyrics already present: {0}', item)
return
lyrics = self.get_item_lyrics(item)
if lyrics:
self._log.info('fetched lyrics: {0}', item)
else:
self._log.info('lyrics not found: {0}', item)
return
item.lyrics = lyrics
if write:
item.try_write()
item.store()
def get_item_lyrics(self, item):
"""Get the lyrics for item from bandcamp.
"""
try:
# The track id is the bandcamp url when item.data_source is bandcamp.
html = self._get(item.mb_trackid)
lyrics = html.find(attrs={'class': 'lyricsText'})
if lyrics:
return lyrics.text
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while fetching lyrics for track {0!r}: "
"{1}".format(item.mb_trackid, e))
return None
def _search(self, query, search_type=BANDCAMP_ALBUM, page=1):
"""Returns a list of bandcamp urls for items of type search_type
matching the query.
"""
if search_type not in [BANDCAMP_ARTIST, BANDCAMP_ALBUM, BANDCAMP_TRACK]:
self._log.debug('Invalid type for search: {0}'.format(search_type))
return None
try:
urls = []
# Search bandcamp until min_candidates results have been found or
# we hit the last page in the results.
while len(urls) < self.config['min_candidates'].as_number():
self._log.debug('Searching {}, page {}'.format(search_type, page))
results = self._get(BANDCAMP_SEARCH.format(query=query, page=page))
clazz = 'searchresult {0}'.format(search_type)
for result in results.find_all('li', attrs={'class': clazz}):
a = result.find(attrs={'class': 'heading'}).a
if a is not None:
urls.append(a['href'].split('?')[0])
# Stop searching if we are on the last page.
if not results.find('a', attrs={'class': 'next'}):
break
page += 1
return urls
except requests.exceptions.RequestException as e:
self._log.debug("Communication error while searching page {0} for {1!r}: "
"{2}".format(page, query, e))
return []
def _get(self, url):
"""Returns a BeautifulSoup object with the contents of url.
"""
headers = {'User-Agent': USER_AGENT}
r = requests.get(url, headers=headers)
r.raise_for_status()
return BeautifulSoup(r.text, 'html.parser')
def _parse_album_track(self, track_html):
|
def _split_artist_title(self, title):
"""Returns artist and title by splitting title on ARTIST_TITLE_DELIMITER.
"""
parts = title.split(ARTIST_TITLE_DELIMITER)
if len(parts) == 1:
return None, title
return parts[0], ARTIST_TITLE_DELIMITER.join(parts[1:])
class BandcampAlbumArt(fetchart.RemoteArtSource):
NAME = u"Bandcamp"
def get(self, album, plugin, paths):
"""Return the url for the cover from the bandcamp album page.
This only returns cover art urls for bandcamp albums (by id).
"""
if isinstance(album.mb_albumid, six.string_types) and 'bandcamp' in album.mb_albumid:
try:
headers = {'User-Agent': USER_AGENT}
r = requests.get(album.mb_albumid, headers=headers)
r.raise_for_status()
album_html = BeautifulSoup(r.text, 'html.parser').find(id='tralbumArt')
image_url = album_html.find('a', attrs={'class': 'popupImage'})['href']
yield self._candidate(url=image_url,
match=fetchart.Candidate.MATCH_EXACT)
except requests.exceptions.RequestException as e:
self._log.debug("Communication error getting art for {0}: {1}"
.format(album, e))
except ValueError:
pass
class BandcampException(Exception):
pass
| """Returns a TrackInfo derived from the html describing a track in a
bandcamp album page.
"""
track_num = track_html['rel'].split('=')[1]
track_num = int(track_num)
title_html = track_html.find(attrs={'class': 'title-col'})
title = title_html.find(attrs={'itemprop': 'name'}).text.strip()
artist = None
if self.config['split_artist_title']:
artist, title = self._split_artist_title(title)
track_url = title_html.find(attrs={'itemprop': 'url'})
if track_url is None:
raise BandcampException('No track url (id) for track {0} - {1}'.format(track_num, title))
track_id = track_url['href']
try:
duration = title_html.find('meta', attrs={'itemprop': 'duration'})['content']
duration = duration.replace('P', 'PT')
track_length = isodate.parse_duration(duration).total_seconds()
except TypeError:
track_length = None
return TrackInfo(title, track_id, index=track_num, length=track_length, artist=artist) | identifier_body |
state.ts | import textCursor from "./textCursor"
import view from "./view"
import intents from "./intents"
import actions from "./actions"
const state: any = {}
export default state
state.representation = (model: any) => {
// compute "view model" for state representation: a flat array of sprites
const orderedSprites = model.scene.map((id: string) => {
const sprite = Object.assign({}, model.sprites[id]) | }
if (model.selectedSpriteId === id) {
sprite.isSelected = true
}
if (model.sizeInfo.isSizing && model.sizeInfo.id === id) {
sprite.isGripping = model.sizeInfo.corner
}
return sprite
})
view.display(view.main(orderedSprites))
}
state.nextAction = (model: any) => {
// render blasts the whole dom, so reset previous text cursor
textCursor.restore()
}
state.render = (model: any) => {
state.representation(model)
state.nextAction(model)
} | if (model.highlightedSpriteId === id) {
sprite.isHighlighted = true | random_line_split |
state.ts | import textCursor from "./textCursor"
import view from "./view"
import intents from "./intents"
import actions from "./actions"
const state: any = {}
export default state
state.representation = (model: any) => {
// compute "view model" for state representation: a flat array of sprites
const orderedSprites = model.scene.map((id: string) => {
const sprite = Object.assign({}, model.sprites[id])
if (model.highlightedSpriteId === id) |
if (model.selectedSpriteId === id) {
sprite.isSelected = true
}
if (model.sizeInfo.isSizing && model.sizeInfo.id === id) {
sprite.isGripping = model.sizeInfo.corner
}
return sprite
})
view.display(view.main(orderedSprites))
}
state.nextAction = (model: any) => {
// render blasts the whole dom, so reset previous text cursor
textCursor.restore()
}
state.render = (model: any) => {
state.representation(model)
state.nextAction(model)
}
| {
sprite.isHighlighted = true
} | conditional_block |
mvcarray-utils.ts | import { fromEventPattern, Observable } from 'rxjs';
export function createMVCEventObservable<T>(array: google.maps.MVCArray<T>): Observable<MVCEvent<T>>{
const eventNames = ['insert_at', 'remove_at', 'set_at'];
return fromEventPattern(
handler => eventNames.map(eventName => array.addListener(eventName,
(index: number, previous?: T) => handler.apply(array, [ {newArr: array.getArray(), eventName, index, previous} as MVCEvent<T>]))),
(_handler, evListeners: google.maps.MapsEventListener[]) => evListeners.forEach(evListener => evListener.remove()));
}
export type MvcEventType = 'insert_at' | 'remove_at' | 'set_at';
export interface MVCEvent<T> {
newArr: T[];
eventName: MvcEventType;
index: number;
previous?: T;
}
export class MvcArrayMock<T> implements google.maps.MVCArray<T> {
private vals: T[] = [];
private listeners: {
'remove_at': ((i: number, r: T) => void)[];
'insert_at': ((i: number) => void)[];
'set_at': ((i: number, val: T) => void)[];
} = {
remove_at: [],
insert_at: [],
set_at: [],
};
clear(): void {
for (let i = this.vals.length - 1; i >= 0; i--) |
}
getArray(): T[] {
return [...this.vals];
}
getAt(i: number): T {
return this.vals[i];
}
getLength(): number {
return this.vals.length;
}
insertAt(i: number, elem: T): void {
this.vals.splice(i, 0, elem);
this.listeners.insert_at.forEach(listener => listener(i));
}
pop(): T {
const deleted = this.vals.pop();
this.listeners.remove_at.forEach(listener => listener(this.vals.length, deleted));
return deleted;
}
push(elem: T): number {
this.vals.push(elem);
this.listeners.insert_at.forEach(listener => listener(this.vals.length - 1));
return this.vals.length;
}
removeAt(i: number): T {
const deleted = this.vals.splice(i, 1)[0];
this.listeners.remove_at.forEach(listener => listener(i, deleted));
return deleted;
}
setAt(i: number, elem: T): void {
const deleted = this.vals[i];
this.vals[i] = elem;
this.listeners.set_at.forEach(listener => listener(i, deleted));
}
forEach(callback: (elem: T, i: number) => void): void {
this.vals.forEach(callback);
}
addListener(eventName: 'remove_at' | 'insert_at' | 'set_at', handler: (...args: any[]) => void): google.maps.MapsEventListener {
const listenerArr = this.listeners[eventName];
listenerArr.push(handler);
return {
remove: () => {
listenerArr.splice(listenerArr.indexOf(handler), 1);
},
};
}
bindTo(): never { throw new Error('Not implemented'); }
changed(): never { throw new Error('Not implemented'); }
get(): never { throw new Error('Not implemented'); }
notify(): never { throw new Error('Not implemented'); }
set(): never { throw new Error('Not implemented'); }
setValues(): never { throw new Error('Not implemented'); }
unbind(): never { throw new Error('Not implemented'); }
unbindAll(): never { throw new Error('Not implemented'); }
}
| {
this.removeAt(i);
} | conditional_block |
mvcarray-utils.ts | import { fromEventPattern, Observable } from 'rxjs';
export function createMVCEventObservable<T>(array: google.maps.MVCArray<T>): Observable<MVCEvent<T>>{
const eventNames = ['insert_at', 'remove_at', 'set_at'];
return fromEventPattern(
handler => eventNames.map(eventName => array.addListener(eventName,
(index: number, previous?: T) => handler.apply(array, [ {newArr: array.getArray(), eventName, index, previous} as MVCEvent<T>]))),
(_handler, evListeners: google.maps.MapsEventListener[]) => evListeners.forEach(evListener => evListener.remove()));
}
export type MvcEventType = 'insert_at' | 'remove_at' | 'set_at';
export interface MVCEvent<T> {
newArr: T[];
eventName: MvcEventType;
index: number;
previous?: T;
}
export class MvcArrayMock<T> implements google.maps.MVCArray<T> {
private vals: T[] = [];
private listeners: {
'remove_at': ((i: number, r: T) => void)[];
'insert_at': ((i: number) => void)[];
'set_at': ((i: number, val: T) => void)[];
} = {
remove_at: [],
insert_at: [],
set_at: [],
};
clear(): void {
for (let i = this.vals.length - 1; i >= 0; i--) {
this.removeAt(i);
}
}
getArray(): T[] {
return [...this.vals];
}
getAt(i: number): T {
return this.vals[i];
}
getLength(): number {
return this.vals.length;
}
insertAt(i: number, elem: T): void |
pop(): T {
const deleted = this.vals.pop();
this.listeners.remove_at.forEach(listener => listener(this.vals.length, deleted));
return deleted;
}
push(elem: T): number {
this.vals.push(elem);
this.listeners.insert_at.forEach(listener => listener(this.vals.length - 1));
return this.vals.length;
}
removeAt(i: number): T {
const deleted = this.vals.splice(i, 1)[0];
this.listeners.remove_at.forEach(listener => listener(i, deleted));
return deleted;
}
setAt(i: number, elem: T): void {
const deleted = this.vals[i];
this.vals[i] = elem;
this.listeners.set_at.forEach(listener => listener(i, deleted));
}
forEach(callback: (elem: T, i: number) => void): void {
this.vals.forEach(callback);
}
addListener(eventName: 'remove_at' | 'insert_at' | 'set_at', handler: (...args: any[]) => void): google.maps.MapsEventListener {
const listenerArr = this.listeners[eventName];
listenerArr.push(handler);
return {
remove: () => {
listenerArr.splice(listenerArr.indexOf(handler), 1);
},
};
}
bindTo(): never { throw new Error('Not implemented'); }
changed(): never { throw new Error('Not implemented'); }
get(): never { throw new Error('Not implemented'); }
notify(): never { throw new Error('Not implemented'); }
set(): never { throw new Error('Not implemented'); }
setValues(): never { throw new Error('Not implemented'); }
unbind(): never { throw new Error('Not implemented'); }
unbindAll(): never { throw new Error('Not implemented'); }
}
| {
this.vals.splice(i, 0, elem);
this.listeners.insert_at.forEach(listener => listener(i));
} | identifier_body |
mvcarray-utils.ts | import { fromEventPattern, Observable } from 'rxjs';
export function createMVCEventObservable<T>(array: google.maps.MVCArray<T>): Observable<MVCEvent<T>>{
const eventNames = ['insert_at', 'remove_at', 'set_at'];
return fromEventPattern(
handler => eventNames.map(eventName => array.addListener(eventName,
(index: number, previous?: T) => handler.apply(array, [ {newArr: array.getArray(), eventName, index, previous} as MVCEvent<T>]))),
(_handler, evListeners: google.maps.MapsEventListener[]) => evListeners.forEach(evListener => evListener.remove()));
}
export type MvcEventType = 'insert_at' | 'remove_at' | 'set_at';
export interface MVCEvent<T> {
newArr: T[];
eventName: MvcEventType;
index: number;
previous?: T;
}
export class MvcArrayMock<T> implements google.maps.MVCArray<T> {
private vals: T[] = [];
private listeners: {
'remove_at': ((i: number, r: T) => void)[];
'insert_at': ((i: number) => void)[];
'set_at': ((i: number, val: T) => void)[];
} = {
remove_at: [],
insert_at: [],
set_at: [],
};
clear(): void {
for (let i = this.vals.length - 1; i >= 0; i--) {
this.removeAt(i);
}
}
getArray(): T[] {
return [...this.vals];
}
getAt(i: number): T {
return this.vals[i];
}
getLength(): number {
return this.vals.length;
}
insertAt(i: number, elem: T): void {
this.vals.splice(i, 0, elem);
this.listeners.insert_at.forEach(listener => listener(i));
}
pop(): T {
const deleted = this.vals.pop();
this.listeners.remove_at.forEach(listener => listener(this.vals.length, deleted));
return deleted;
}
push(elem: T): number {
this.vals.push(elem);
this.listeners.insert_at.forEach(listener => listener(this.vals.length - 1));
return this.vals.length;
}
removeAt(i: number): T {
const deleted = this.vals.splice(i, 1)[0];
this.listeners.remove_at.forEach(listener => listener(i, deleted));
return deleted;
}
setAt(i: number, elem: T): void {
const deleted = this.vals[i];
this.vals[i] = elem;
this.listeners.set_at.forEach(listener => listener(i, deleted));
}
forEach(callback: (elem: T, i: number) => void): void {
this.vals.forEach(callback);
}
addListener(eventName: 'remove_at' | 'insert_at' | 'set_at', handler: (...args: any[]) => void): google.maps.MapsEventListener {
const listenerArr = this.listeners[eventName];
listenerArr.push(handler);
return {
remove: () => {
listenerArr.splice(listenerArr.indexOf(handler), 1);
},
};
}
| (): never { throw new Error('Not implemented'); }
changed(): never { throw new Error('Not implemented'); }
get(): never { throw new Error('Not implemented'); }
notify(): never { throw new Error('Not implemented'); }
set(): never { throw new Error('Not implemented'); }
setValues(): never { throw new Error('Not implemented'); }
unbind(): never { throw new Error('Not implemented'); }
unbindAll(): never { throw new Error('Not implemented'); }
}
| bindTo | identifier_name |
mvcarray-utils.ts | import { fromEventPattern, Observable } from 'rxjs';
export function createMVCEventObservable<T>(array: google.maps.MVCArray<T>): Observable<MVCEvent<T>>{
const eventNames = ['insert_at', 'remove_at', 'set_at'];
return fromEventPattern(
handler => eventNames.map(eventName => array.addListener(eventName,
(index: number, previous?: T) => handler.apply(array, [ {newArr: array.getArray(), eventName, index, previous} as MVCEvent<T>]))),
(_handler, evListeners: google.maps.MapsEventListener[]) => evListeners.forEach(evListener => evListener.remove()));
}
export type MvcEventType = 'insert_at' | 'remove_at' | 'set_at';
export interface MVCEvent<T> { | }
export class MvcArrayMock<T> implements google.maps.MVCArray<T> {
private vals: T[] = [];
private listeners: {
'remove_at': ((i: number, r: T) => void)[];
'insert_at': ((i: number) => void)[];
'set_at': ((i: number, val: T) => void)[];
} = {
remove_at: [],
insert_at: [],
set_at: [],
};
clear(): void {
for (let i = this.vals.length - 1; i >= 0; i--) {
this.removeAt(i);
}
}
getArray(): T[] {
return [...this.vals];
}
getAt(i: number): T {
return this.vals[i];
}
getLength(): number {
return this.vals.length;
}
insertAt(i: number, elem: T): void {
this.vals.splice(i, 0, elem);
this.listeners.insert_at.forEach(listener => listener(i));
}
pop(): T {
const deleted = this.vals.pop();
this.listeners.remove_at.forEach(listener => listener(this.vals.length, deleted));
return deleted;
}
push(elem: T): number {
this.vals.push(elem);
this.listeners.insert_at.forEach(listener => listener(this.vals.length - 1));
return this.vals.length;
}
removeAt(i: number): T {
const deleted = this.vals.splice(i, 1)[0];
this.listeners.remove_at.forEach(listener => listener(i, deleted));
return deleted;
}
setAt(i: number, elem: T): void {
const deleted = this.vals[i];
this.vals[i] = elem;
this.listeners.set_at.forEach(listener => listener(i, deleted));
}
forEach(callback: (elem: T, i: number) => void): void {
this.vals.forEach(callback);
}
addListener(eventName: 'remove_at' | 'insert_at' | 'set_at', handler: (...args: any[]) => void): google.maps.MapsEventListener {
const listenerArr = this.listeners[eventName];
listenerArr.push(handler);
return {
remove: () => {
listenerArr.splice(listenerArr.indexOf(handler), 1);
},
};
}
bindTo(): never { throw new Error('Not implemented'); }
changed(): never { throw new Error('Not implemented'); }
get(): never { throw new Error('Not implemented'); }
notify(): never { throw new Error('Not implemented'); }
set(): never { throw new Error('Not implemented'); }
setValues(): never { throw new Error('Not implemented'); }
unbind(): never { throw new Error('Not implemented'); }
unbindAll(): never { throw new Error('Not implemented'); }
} | newArr: T[];
eventName: MvcEventType;
index: number;
previous?: T; | random_line_split |
__openerp__.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) cgstudiomap <cgstudiomap@gmail.com> | # 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Res Partner phone: missing details',
'version': '0.2',
'author': 'cgstudiomap',
'maintainer': 'cgstudiomap',
'license': 'AGPL-3',
'category': 'Sales',
'summary': 'Set up for phone for missing details bot',
'depends': [
'res_partner_missing_details',
'base_phone_validation',
],
'external_dependencies': {},
'data': [
'missing_details.xml',
],
'installable': True,
} | #
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as | random_line_split |
history.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use abomonation_derive::Abomonation;
use anyhow::Error;
use filenodes::{FilenodeInfo, FilenodeInfoCached};
#[derive(Abomonation, Clone)]
pub struct FilenodeHistoryCached {
// TODO: We could store this more efficiently by deduplicating filenode IDs.
history: Vec<FilenodeInfoCached>,
}
impl FilenodeHistoryCached {
pub fn into_filenode_info(self) -> Result<Vec<FilenodeInfo>, Error> {
self.history.into_iter().map(|c| c.try_into()).collect()
}
| let history = filenodes.into_iter().map(|f| f.into()).collect::<Vec<_>>();
Self { history }
}
} | pub fn from_filenodes(filenodes: Vec<FilenodeInfo>) -> Self { | random_line_split |
history.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use abomonation_derive::Abomonation;
use anyhow::Error;
use filenodes::{FilenodeInfo, FilenodeInfoCached};
#[derive(Abomonation, Clone)]
pub struct FilenodeHistoryCached {
// TODO: We could store this more efficiently by deduplicating filenode IDs.
history: Vec<FilenodeInfoCached>,
}
impl FilenodeHistoryCached {
pub fn | (self) -> Result<Vec<FilenodeInfo>, Error> {
self.history.into_iter().map(|c| c.try_into()).collect()
}
pub fn from_filenodes(filenodes: Vec<FilenodeInfo>) -> Self {
let history = filenodes.into_iter().map(|f| f.into()).collect::<Vec<_>>();
Self { history }
}
}
| into_filenode_info | identifier_name |
read_all.rs | use std::borrow::Cow;
use std::convert::TryInto;
use raw::client_messages;
use raw::client_messages::mod_ReadAllEventsCompleted::ReadAllResult;
use LogPosition;
/// Successful response to `Message::ReadAllEvents`.
#[derive(Debug, Clone, PartialEq)]
pub struct ReadAllCompleted<'a> {
/// Position of the commit of the current prepare
pub commit_position: LogPosition,
/// Position of the current prepare
pub prepare_position: LogPosition,
/// The read events, with position metadata
pub events: Vec<ResolvedEvent<'a>>,
/// For paging: next commit position
pub next_commit_position: Option<LogPosition>,
/// For paging: next prepare position
pub next_prepare_position: Option<LogPosition>,
}
/// Read event in `ReadAllSuccess` response
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedEvent<'a> {
/// The read event
pub event: client_messages::EventRecord<'a>,
/// Possible linking event
pub link: Option<client_messages::EventRecord<'a>>,
/// Position where this events transaction is commited
pub commit_position: LogPosition, | impl<'a> From<client_messages::ResolvedEvent<'a>> for ResolvedEvent<'a> {
fn from(e: client_messages::ResolvedEvent<'a>) -> ResolvedEvent<'a> {
ResolvedEvent {
event: e.event.into(),
link: e.link.into(),
commit_position: e.commit_position.try_into().unwrap(),
prepare_position: e.prepare_position.try_into().unwrap()
}
}
}
/// Failure cases of wire enum `ReadAllResult`.
#[derive(Debug, Clone, PartialEq)]
pub enum ReadAllError<'a> {
/// Unknown when this happens,
NotModified,
/// Other error
Error(Option<Cow<'a, str>>),
/// Access was denied (no credentials provided or insufficient permissions)
AccessDenied
}
impl<'a> From<(ReadAllResult, Option<Cow<'a, str>>)> for ReadAllError<'a> {
fn from((r, msg): (ReadAllResult, Option<Cow<'a, str>>)) -> ReadAllError<'a> {
use self::ReadAllResult::*;
match r {
Success => unreachable!(),
NotModified => ReadAllError::NotModified,
Error => ReadAllError::Error(msg),
AccessDenied => ReadAllError::AccessDenied,
}
}
} | /// Position where this event is stored
pub prepare_position: LogPosition,
}
| random_line_split |
read_all.rs | use std::borrow::Cow;
use std::convert::TryInto;
use raw::client_messages;
use raw::client_messages::mod_ReadAllEventsCompleted::ReadAllResult;
use LogPosition;
/// Successful response to `Message::ReadAllEvents`.
#[derive(Debug, Clone, PartialEq)]
pub struct ReadAllCompleted<'a> {
/// Position of the commit of the current prepare
pub commit_position: LogPosition,
/// Position of the current prepare
pub prepare_position: LogPosition,
/// The read events, with position metadata
pub events: Vec<ResolvedEvent<'a>>,
/// For paging: next commit position
pub next_commit_position: Option<LogPosition>,
/// For paging: next prepare position
pub next_prepare_position: Option<LogPosition>,
}
/// Read event in `ReadAllSuccess` response
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedEvent<'a> {
/// The read event
pub event: client_messages::EventRecord<'a>,
/// Possible linking event
pub link: Option<client_messages::EventRecord<'a>>,
/// Position where this events transaction is commited
pub commit_position: LogPosition,
/// Position where this event is stored
pub prepare_position: LogPosition,
}
impl<'a> From<client_messages::ResolvedEvent<'a>> for ResolvedEvent<'a> {
fn from(e: client_messages::ResolvedEvent<'a>) -> ResolvedEvent<'a> {
ResolvedEvent {
event: e.event.into(),
link: e.link.into(),
commit_position: e.commit_position.try_into().unwrap(),
prepare_position: e.prepare_position.try_into().unwrap()
}
}
}
/// Failure cases of wire enum `ReadAllResult`.
#[derive(Debug, Clone, PartialEq)]
pub enum | <'a> {
/// Unknown when this happens,
NotModified,
/// Other error
Error(Option<Cow<'a, str>>),
/// Access was denied (no credentials provided or insufficient permissions)
AccessDenied
}
impl<'a> From<(ReadAllResult, Option<Cow<'a, str>>)> for ReadAllError<'a> {
fn from((r, msg): (ReadAllResult, Option<Cow<'a, str>>)) -> ReadAllError<'a> {
use self::ReadAllResult::*;
match r {
Success => unreachable!(),
NotModified => ReadAllError::NotModified,
Error => ReadAllError::Error(msg),
AccessDenied => ReadAllError::AccessDenied,
}
}
}
| ReadAllError | identifier_name |
getUserID.js | "use strict";
var utils = require("../utils");
var log = require("npmlog");
function | (data) {
return {
userID: utils.formatID(data.uid.toString()),
photoUrl: data.photo,
indexRank: data.index_rank,
name: data.text,
isVerified: data.is_verified,
profileUrl: data.path,
category: data.category,
score: data.score,
};
}
module.exports = function(defaultFuncs, api, ctx) {
return function getUserID(name, callback) {
if(!callback) {
throw {error: "getUserID: need callback"};
}
var form = {
'value' : name.toLowerCase(),
'viewer' : ctx.userID,
'rsp' : "search",
'context' : "search",
'path' : "/home.php",
'request_id' : utils.getGUID(),
};
defaultFuncs
.get("https://www.facebook.com/ajax/typeahead/search.php", ctx.jar, form)
.then(utils.parseAndCheckLogin(ctx, defaultFuncs))
.then(function(resData) {
if (resData.error) {
throw resData;
}
var data = resData.payload.entries;
if(data[0].type !== "user") {
throw {error: "Couldn't find a user with name " + name + ". Bes match: " + data[0].path};
}
callback(null, data.map(formatData));
})
.catch(function(err) {
log.error("getUserID", err);
return callback(err);
});
};
};
| formatData | identifier_name |
getUserID.js | "use strict";
var utils = require("../utils");
var log = require("npmlog");
function formatData(data) |
module.exports = function(defaultFuncs, api, ctx) {
return function getUserID(name, callback) {
if(!callback) {
throw {error: "getUserID: need callback"};
}
var form = {
'value' : name.toLowerCase(),
'viewer' : ctx.userID,
'rsp' : "search",
'context' : "search",
'path' : "/home.php",
'request_id' : utils.getGUID(),
};
defaultFuncs
.get("https://www.facebook.com/ajax/typeahead/search.php", ctx.jar, form)
.then(utils.parseAndCheckLogin(ctx, defaultFuncs))
.then(function(resData) {
if (resData.error) {
throw resData;
}
var data = resData.payload.entries;
if(data[0].type !== "user") {
throw {error: "Couldn't find a user with name " + name + ". Bes match: " + data[0].path};
}
callback(null, data.map(formatData));
})
.catch(function(err) {
log.error("getUserID", err);
return callback(err);
});
};
};
| {
return {
userID: utils.formatID(data.uid.toString()),
photoUrl: data.photo,
indexRank: data.index_rank,
name: data.text,
isVerified: data.is_verified,
profileUrl: data.path,
category: data.category,
score: data.score,
};
} | identifier_body |
getUserID.js | "use strict";
var utils = require("../utils");
var log = require("npmlog");
function formatData(data) {
return {
userID: utils.formatID(data.uid.toString()),
photoUrl: data.photo,
indexRank: data.index_rank,
name: data.text,
isVerified: data.is_verified,
profileUrl: data.path,
category: data.category,
score: data.score,
};
}
module.exports = function(defaultFuncs, api, ctx) {
return function getUserID(name, callback) {
if(!callback) {
throw {error: "getUserID: need callback"};
}
var form = {
'value' : name.toLowerCase(),
'viewer' : ctx.userID,
'rsp' : "search",
'context' : "search",
'path' : "/home.php",
'request_id' : utils.getGUID(),
};
defaultFuncs
.get("https://www.facebook.com/ajax/typeahead/search.php", ctx.jar, form) | .then(function(resData) {
if (resData.error) {
throw resData;
}
var data = resData.payload.entries;
if(data[0].type !== "user") {
throw {error: "Couldn't find a user with name " + name + ". Bes match: " + data[0].path};
}
callback(null, data.map(formatData));
})
.catch(function(err) {
log.error("getUserID", err);
return callback(err);
});
};
}; | .then(utils.parseAndCheckLogin(ctx, defaultFuncs)) | random_line_split |
getUserID.js | "use strict";
var utils = require("../utils");
var log = require("npmlog");
function formatData(data) {
return {
userID: utils.formatID(data.uid.toString()),
photoUrl: data.photo,
indexRank: data.index_rank,
name: data.text,
isVerified: data.is_verified,
profileUrl: data.path,
category: data.category,
score: data.score,
};
}
module.exports = function(defaultFuncs, api, ctx) {
return function getUserID(name, callback) {
if(!callback) {
throw {error: "getUserID: need callback"};
}
var form = {
'value' : name.toLowerCase(),
'viewer' : ctx.userID,
'rsp' : "search",
'context' : "search",
'path' : "/home.php",
'request_id' : utils.getGUID(),
};
defaultFuncs
.get("https://www.facebook.com/ajax/typeahead/search.php", ctx.jar, form)
.then(utils.parseAndCheckLogin(ctx, defaultFuncs))
.then(function(resData) {
if (resData.error) |
var data = resData.payload.entries;
if(data[0].type !== "user") {
throw {error: "Couldn't find a user with name " + name + ". Bes match: " + data[0].path};
}
callback(null, data.map(formatData));
})
.catch(function(err) {
log.error("getUserID", err);
return callback(err);
});
};
};
| {
throw resData;
} | conditional_block |
IsoTriangleFactory.js | /**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var GameObjectFactory = require('../../GameObjectFactory');
var IsoTriangle = require('./IsoTriangle');
/**
* Creates a new IsoTriangle Shape Game Object and adds it to the Scene.
*
* Note: This method will only be available if the IsoTriangle Game Object has been built into Phaser.
*
* The IsoTriangle Shape is a Game Object that can be added to a Scene, Group or Container. You can | * treat it like any other Game Object in your game, such as tweening it, scaling it, or enabling
* it for input or physics. It provides a quick and easy way for you to render this shape in your
* game without using a texture, while still taking advantage of being fully batched in WebGL.
*
* This shape supports only fill colors and cannot be stroked.
*
* An IsoTriangle is an 'isometric' triangle. Think of it like a pyramid. Each face has a different
* fill color. You can set the color of the top, left and right faces of the triangle respectively
* You can also choose which of the faces are rendered via the `showTop`, `showLeft` and `showRight` properties.
*
* You cannot view an IsoTriangle from under-neath, however you can change the 'angle' by setting
* the `projection` property. The `reversed` property controls if the IsoTriangle is rendered upside
* down or not.
*
* @method Phaser.GameObjects.GameObjectFactory#isotriangle
* @since 3.13.0
*
* @param {number} [x=0] - The horizontal position of this Game Object in the world.
* @param {number} [y=0] - The vertical position of this Game Object in the world.
* @param {number} [size=48] - The width of the iso triangle in pixels. The left and right faces will be exactly half this value.
* @param {number} [height=32] - The height of the iso triangle. The left and right faces will be this tall. The overall height of the iso triangle will be this value plus half the `size` value.
* @param {boolean} [reversed=false] - Is the iso triangle upside down?
* @param {number} [fillTop=0xeeeeee] - The fill color of the top face of the iso triangle.
* @param {number} [fillLeft=0x999999] - The fill color of the left face of the iso triangle.
* @param {number} [fillRight=0xcccccc] - The fill color of the right face of the iso triangle.
*
* @return {Phaser.GameObjects.IsoTriangle} The Game Object that was created.
*/
GameObjectFactory.register('isotriangle', function (x, y, size, height, reversed, fillTop, fillLeft, fillRight)
{
return this.displayList.add(new IsoTriangle(this.scene, x, y, size, height, reversed, fillTop, fillLeft, fillRight));
}); | random_line_split | |
equipos.js | /**
* @author David Yzaguirre <dvdyzag@gmail.com>
*
* @copyright Copyright (c) 2016, David Yzaguirre, Aníbal Rodríguez
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
var db = require('../models');
exports.listar = function(request, reply){
if (request.params.idEquipo){
db.Equipo.findOne({_id: request.params.idEquipo}, function(err, equipo){
if (err){
reply({statusCode: 600, error: "Database", message:"Equipo no encontrado"});
} else if (equipo){
reply({statusCode:200,equipo:equipo});
} else {
reply({statusCode: 600, error: "Database", message:"Equipo no encontrado"});
}
});
} else {
db.Equipo.find(function(err, equipos){
if (err){
reply({statusCode: 600, error: "Database", message:"Equipo no encontrado"});
} else if (equipos){
reply({statusCode:200,equipos:equipos});
} else {
reply({statusCode: 600, error: "Database", message:"Equipo no encontrado"});
}
});
}
};
exports.create = function(request, reply){
new db.Equipo(request.payload).save(function(err, equipo, numberAffected){
if(err){
return reply({statusCode: 600, error: "Database", message: "Error de Base de datos."});
}
return reply({statusCode: 200, _id: equipo._id});
});
}
exports.save = function(request, reply){
var equipo = request.payload;
equipo.modified = Date.now();
db.Equipo.update({_id:request.params.idEquipo}, {$set: equipo}, function(err, raw){ | }
return reply({statusCode: 200});
});
}
exports.delete = function(request, reply){
db.Equipo.remove({_id:request.params.idEquipo}, function(err){
if (err) {
console.log("ATLETAS_DELETE err="+JSON.stringify(err));
return reply({statusCode:600});
}
return reply({statusCode: 200});
});
} | if (err) {
console.log("EQUIPOS_SAVE err="+JSON.stringify(err));
return reply({statusCode:600}); | random_line_split |
equipos.js | /**
* @author David Yzaguirre <dvdyzag@gmail.com>
*
* @copyright Copyright (c) 2016, David Yzaguirre, Aníbal Rodríguez
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
var db = require('../models');
exports.listar = function(request, reply){
if (request.params.idEquipo){
db.Equipo.findOne({_id: request.params.idEquipo}, function(err, equipo){
if (err){
reply({statusCode: 600, error: "Database", message:"Equipo no encontrado"});
} else if (equipo){
reply({statusCode:200,equipo:equipo});
} else {
reply({statusCode: 600, error: "Database", message:"Equipo no encontrado"});
}
});
} else {
db.Equipo.find(function(err, equipos){
if (err){
reply({statusCode: 600, error: "Database", message:"Equipo no encontrado"});
} else if (equipos){
reply({statusCode:200,equipos:equipos});
} else {
reply({statusCode: 600, error: "Database", message:"Equipo no encontrado"});
}
});
}
};
exports.create = function(request, reply){
new db.Equipo(request.payload).save(function(err, equipo, numberAffected){
if(err){
return reply({statusCode: 600, error: "Database", message: "Error de Base de datos."});
}
return reply({statusCode: 200, _id: equipo._id});
});
}
exports.save = function(request, reply){
var equipo = request.payload;
equipo.modified = Date.now();
db.Equipo.update({_id:request.params.idEquipo}, {$set: equipo}, function(err, raw){
if (err) {
console.log("EQUIPOS_SAVE err="+JSON.stringify(err));
return reply({statusCode:600});
}
return reply({statusCode: 200});
});
}
exports.delete = function(request, reply){
db.Equipo.remove({_id:request.params.idEquipo}, function(err){
if (err) {
| return reply({statusCode: 200});
});
}
| console.log("ATLETAS_DELETE err="+JSON.stringify(err));
return reply({statusCode:600});
}
| conditional_block |
stage_2.py | #!/usr/bin/env python
# File written by pyctools-editor. Do not edit.
import argparse
import logging
from pyctools.core.compound import Compound
import pyctools.components.arithmetic
import pyctools.components.qt.qtdisplay
import pyctools.components.zone.zoneplategenerator
class Network(object):
components = \
{ 'clipper': { 'class': 'pyctools.components.arithmetic.Arithmetic',
'config': "{'func': '16+((data > 180)*219)'}",
'pos': (200.0, 200.0)},
'clipper2': { 'class': 'pyctools.components.arithmetic.Arithmetic',
'config': "{'func': '16+((data > 230)*219)'}",
'pos': (200.0, 330.0)},
'qd': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay',
'config': "{'framerate': 60}",
'pos': (460.0, 200.0)},
'stacker': { 'class': 'pyctools.components.arithmetic.Arithmetic2',
'config': "{'func': 'numpy.vstack((data1,data2))'}",
'pos': (330.0, 200.0)},
'zpg': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator',
'config': "{'kx': 0.04, 'kt': -0.34, 'xlen': 600, 'ylen': "
"400, 'zlen': 1000, 'looping': 'repeat'}",
'pos': (70.0, 200.0)},
'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator',
'config': "{'kx': 0.002, 'kt': -0.017, 'xlen': 600, 'ylen': "
"200, 'zlen': 1000, 'looping': 'repeat'}",
'pos': (70.0, 330.0)}}
linkages = \
{ ('clipper', 'output'): [('stacker', 'input1')],
('clipper2', 'output'): [('stacker', 'input2')],
('stacker', 'output'): [('qd', 'input')],
('zpg', 'output'): [('clipper', 'input')],
('zpg2', 'output'): [('clipper2', 'input')]}
def make(self):
|
if __name__ == '__main__':
from PyQt5 import QtCore, QtWidgets
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads)
app = QtWidgets.QApplication([])
comp = Network().make()
cnf = comp.get_config()
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
cnf.parser_add(parser)
parser.add_argument('-v', '--verbose', action='count', default=0,
help='increase verbosity of log messages')
args = parser.parse_args()
logging.basicConfig(level=logging.ERROR - (args.verbose * 10))
del args.verbose
cnf.parser_set(args)
comp.set_config(cnf)
comp.start()
app.exec_()
comp.stop()
comp.join()
| comps = {}
for name, component in self.components.items():
comps[name] = eval(component['class'])(config=eval(component['config']))
return Compound(linkages=self.linkages, **comps) | identifier_body |
stage_2.py | #!/usr/bin/env python
# File written by pyctools-editor. Do not edit.
import argparse
import logging
from pyctools.core.compound import Compound
import pyctools.components.arithmetic
import pyctools.components.qt.qtdisplay
import pyctools.components.zone.zoneplategenerator
class Network(object):
components = \
{ 'clipper': { 'class': 'pyctools.components.arithmetic.Arithmetic',
'config': "{'func': '16+((data > 180)*219)'}",
'pos': (200.0, 200.0)},
'clipper2': { 'class': 'pyctools.components.arithmetic.Arithmetic',
'config': "{'func': '16+((data > 230)*219)'}",
'pos': (200.0, 330.0)},
'qd': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay',
'config': "{'framerate': 60}",
'pos': (460.0, 200.0)},
'stacker': { 'class': 'pyctools.components.arithmetic.Arithmetic2',
'config': "{'func': 'numpy.vstack((data1,data2))'}",
'pos': (330.0, 200.0)},
'zpg': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', | 'config': "{'kx': 0.04, 'kt': -0.34, 'xlen': 600, 'ylen': "
"400, 'zlen': 1000, 'looping': 'repeat'}",
'pos': (70.0, 200.0)},
'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator',
'config': "{'kx': 0.002, 'kt': -0.017, 'xlen': 600, 'ylen': "
"200, 'zlen': 1000, 'looping': 'repeat'}",
'pos': (70.0, 330.0)}}
linkages = \
{ ('clipper', 'output'): [('stacker', 'input1')],
('clipper2', 'output'): [('stacker', 'input2')],
('stacker', 'output'): [('qd', 'input')],
('zpg', 'output'): [('clipper', 'input')],
('zpg2', 'output'): [('clipper2', 'input')]}
def make(self):
comps = {}
for name, component in self.components.items():
comps[name] = eval(component['class'])(config=eval(component['config']))
return Compound(linkages=self.linkages, **comps)
if __name__ == '__main__':
from PyQt5 import QtCore, QtWidgets
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads)
app = QtWidgets.QApplication([])
comp = Network().make()
cnf = comp.get_config()
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
cnf.parser_add(parser)
parser.add_argument('-v', '--verbose', action='count', default=0,
help='increase verbosity of log messages')
args = parser.parse_args()
logging.basicConfig(level=logging.ERROR - (args.verbose * 10))
del args.verbose
cnf.parser_set(args)
comp.set_config(cnf)
comp.start()
app.exec_()
comp.stop()
comp.join() | random_line_split | |
stage_2.py | #!/usr/bin/env python
# File written by pyctools-editor. Do not edit.
import argparse
import logging
from pyctools.core.compound import Compound
import pyctools.components.arithmetic
import pyctools.components.qt.qtdisplay
import pyctools.components.zone.zoneplategenerator
class Network(object):
components = \
{ 'clipper': { 'class': 'pyctools.components.arithmetic.Arithmetic',
'config': "{'func': '16+((data > 180)*219)'}",
'pos': (200.0, 200.0)},
'clipper2': { 'class': 'pyctools.components.arithmetic.Arithmetic',
'config': "{'func': '16+((data > 230)*219)'}",
'pos': (200.0, 330.0)},
'qd': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay',
'config': "{'framerate': 60}",
'pos': (460.0, 200.0)},
'stacker': { 'class': 'pyctools.components.arithmetic.Arithmetic2',
'config': "{'func': 'numpy.vstack((data1,data2))'}",
'pos': (330.0, 200.0)},
'zpg': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator',
'config': "{'kx': 0.04, 'kt': -0.34, 'xlen': 600, 'ylen': "
"400, 'zlen': 1000, 'looping': 'repeat'}",
'pos': (70.0, 200.0)},
'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator',
'config': "{'kx': 0.002, 'kt': -0.017, 'xlen': 600, 'ylen': "
"200, 'zlen': 1000, 'looping': 'repeat'}",
'pos': (70.0, 330.0)}}
linkages = \
{ ('clipper', 'output'): [('stacker', 'input1')],
('clipper2', 'output'): [('stacker', 'input2')],
('stacker', 'output'): [('qd', 'input')],
('zpg', 'output'): [('clipper', 'input')],
('zpg2', 'output'): [('clipper2', 'input')]}
def make(self):
comps = {}
for name, component in self.components.items():
|
return Compound(linkages=self.linkages, **comps)
if __name__ == '__main__':
from PyQt5 import QtCore, QtWidgets
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads)
app = QtWidgets.QApplication([])
comp = Network().make()
cnf = comp.get_config()
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
cnf.parser_add(parser)
parser.add_argument('-v', '--verbose', action='count', default=0,
help='increase verbosity of log messages')
args = parser.parse_args()
logging.basicConfig(level=logging.ERROR - (args.verbose * 10))
del args.verbose
cnf.parser_set(args)
comp.set_config(cnf)
comp.start()
app.exec_()
comp.stop()
comp.join()
| comps[name] = eval(component['class'])(config=eval(component['config'])) | conditional_block |
stage_2.py | #!/usr/bin/env python
# File written by pyctools-editor. Do not edit.
import argparse
import logging
from pyctools.core.compound import Compound
import pyctools.components.arithmetic
import pyctools.components.qt.qtdisplay
import pyctools.components.zone.zoneplategenerator
class Network(object):
components = \
{ 'clipper': { 'class': 'pyctools.components.arithmetic.Arithmetic',
'config': "{'func': '16+((data > 180)*219)'}",
'pos': (200.0, 200.0)},
'clipper2': { 'class': 'pyctools.components.arithmetic.Arithmetic',
'config': "{'func': '16+((data > 230)*219)'}",
'pos': (200.0, 330.0)},
'qd': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay',
'config': "{'framerate': 60}",
'pos': (460.0, 200.0)},
'stacker': { 'class': 'pyctools.components.arithmetic.Arithmetic2',
'config': "{'func': 'numpy.vstack((data1,data2))'}",
'pos': (330.0, 200.0)},
'zpg': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator',
'config': "{'kx': 0.04, 'kt': -0.34, 'xlen': 600, 'ylen': "
"400, 'zlen': 1000, 'looping': 'repeat'}",
'pos': (70.0, 200.0)},
'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator',
'config': "{'kx': 0.002, 'kt': -0.017, 'xlen': 600, 'ylen': "
"200, 'zlen': 1000, 'looping': 'repeat'}",
'pos': (70.0, 330.0)}}
linkages = \
{ ('clipper', 'output'): [('stacker', 'input1')],
('clipper2', 'output'): [('stacker', 'input2')],
('stacker', 'output'): [('qd', 'input')],
('zpg', 'output'): [('clipper', 'input')],
('zpg2', 'output'): [('clipper2', 'input')]}
def | (self):
comps = {}
for name, component in self.components.items():
comps[name] = eval(component['class'])(config=eval(component['config']))
return Compound(linkages=self.linkages, **comps)
if __name__ == '__main__':
from PyQt5 import QtCore, QtWidgets
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads)
app = QtWidgets.QApplication([])
comp = Network().make()
cnf = comp.get_config()
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
cnf.parser_add(parser)
parser.add_argument('-v', '--verbose', action='count', default=0,
help='increase verbosity of log messages')
args = parser.parse_args()
logging.basicConfig(level=logging.ERROR - (args.verbose * 10))
del args.verbose
cnf.parser_set(args)
comp.set_config(cnf)
comp.start()
app.exec_()
comp.stop()
comp.join()
| make | identifier_name |
__init__.py | #
# Copyright 2011-2013 Blender Foundation
#
# 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.
#
# <pep8 compliant>
bl_info = {
"name": "Cycles Render Engine",
"author": "",
"blender": (2, 76, 0),
"location": "Info header, render engine menu",
"description": "Cycles Render Engine integration",
"warning": "",
"wiki_url": "https://www.blender.org/manual/render/cycles/index.html",
"tracker_url": "",
"support": 'OFFICIAL',
"category": "Render"}
import bpy
from . import (
engine,
version_update,
)
class CyclesRender(bpy.types.RenderEngine):
bl_idname = 'CYCLES'
bl_label = "Cycles Render"
bl_use_shading_nodes = True
bl_use_preview = True
bl_use_exclude_layers = True
bl_use_save_buffers = True
bl_use_spherical_stereo = True
def __init__(self):
|
def __del__(self):
engine.free(self)
# final render
def update(self, data, scene):
if not self.session:
if self.is_preview:
cscene = bpy.context.scene.cycles
use_osl = cscene.shading_system and cscene.device == 'CPU'
engine.create(self, data, scene,
None, None, None, use_osl)
else:
engine.create(self, data, scene)
else:
engine.reset(self, data, scene)
def render(self, scene):
engine.render(self)
def bake(self, scene, obj, pass_type, pass_filter, object_id, pixel_array, num_pixels, depth, result):
engine.bake(self, obj, pass_type, pass_filter, object_id, pixel_array, num_pixels, depth, result)
# viewport render
def view_update(self, context):
if not self.session:
engine.create(self, context.blend_data, context.scene,
context.region, context.space_data, context.region_data)
engine.update(self, context.blend_data, context.scene)
def view_draw(self, context):
engine.draw(self, context.region, context.space_data, context.region_data)
def update_script_node(self, node):
if engine.with_osl():
from . import osl
osl.update_script_node(node, self.report)
else:
self.report({'ERROR'}, "OSL support disabled in this build.")
def engine_exit():
engine.exit()
def register():
from . import ui
from . import properties
from . import presets
import atexit
# Make sure we only registered the callback once.
atexit.unregister(engine_exit)
atexit.register(engine_exit)
engine.init()
properties.register()
ui.register()
presets.register()
bpy.utils.register_module(__name__)
bpy.app.handlers.version_update.append(version_update.do_versions)
def unregister():
from . import ui
from . import properties
from . import presets
import atexit
bpy.app.handlers.version_update.remove(version_update.do_versions)
ui.unregister()
properties.unregister()
presets.unregister()
bpy.utils.unregister_module(__name__)
| self.session = None | identifier_body |
__init__.py | #
# Copyright 2011-2013 Blender Foundation
#
# 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.
#
# <pep8 compliant>
bl_info = {
"name": "Cycles Render Engine",
"author": "",
"blender": (2, 76, 0),
"location": "Info header, render engine menu",
"description": "Cycles Render Engine integration",
"warning": "",
"wiki_url": "https://www.blender.org/manual/render/cycles/index.html",
"tracker_url": "",
"support": 'OFFICIAL',
"category": "Render"}
import bpy
from . import (
engine,
version_update,
)
class CyclesRender(bpy.types.RenderEngine):
bl_idname = 'CYCLES'
bl_label = "Cycles Render"
bl_use_shading_nodes = True
bl_use_preview = True
bl_use_exclude_layers = True
bl_use_save_buffers = True
bl_use_spherical_stereo = True
def __init__(self):
self.session = None
def __del__(self):
engine.free(self)
# final render
def update(self, data, scene):
if not self.session:
if self.is_preview:
cscene = bpy.context.scene.cycles
use_osl = cscene.shading_system and cscene.device == 'CPU'
engine.create(self, data, scene,
None, None, None, use_osl)
else:
engine.create(self, data, scene)
else:
engine.reset(self, data, scene)
def render(self, scene):
engine.render(self)
def bake(self, scene, obj, pass_type, pass_filter, object_id, pixel_array, num_pixels, depth, result):
engine.bake(self, obj, pass_type, pass_filter, object_id, pixel_array, num_pixels, depth, result)
# viewport render
def view_update(self, context):
if not self.session:
engine.create(self, context.blend_data, context.scene,
context.region, context.space_data, context.region_data)
engine.update(self, context.blend_data, context.scene)
def view_draw(self, context):
engine.draw(self, context.region, context.space_data, context.region_data)
def update_script_node(self, node):
if engine.with_osl():
from . import osl
osl.update_script_node(node, self.report)
else:
self.report({'ERROR'}, "OSL support disabled in this build.")
def engine_exit():
engine.exit()
def register():
from . import ui
from . import properties
from . import presets
import atexit | engine.init()
properties.register()
ui.register()
presets.register()
bpy.utils.register_module(__name__)
bpy.app.handlers.version_update.append(version_update.do_versions)
def unregister():
from . import ui
from . import properties
from . import presets
import atexit
bpy.app.handlers.version_update.remove(version_update.do_versions)
ui.unregister()
properties.unregister()
presets.unregister()
bpy.utils.unregister_module(__name__) |
# Make sure we only registered the callback once.
atexit.unregister(engine_exit)
atexit.register(engine_exit)
| random_line_split |
__init__.py | #
# Copyright 2011-2013 Blender Foundation
#
# 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.
#
# <pep8 compliant>
bl_info = {
"name": "Cycles Render Engine",
"author": "",
"blender": (2, 76, 0),
"location": "Info header, render engine menu",
"description": "Cycles Render Engine integration",
"warning": "",
"wiki_url": "https://www.blender.org/manual/render/cycles/index.html",
"tracker_url": "",
"support": 'OFFICIAL',
"category": "Render"}
import bpy
from . import (
engine,
version_update,
)
class CyclesRender(bpy.types.RenderEngine):
bl_idname = 'CYCLES'
bl_label = "Cycles Render"
bl_use_shading_nodes = True
bl_use_preview = True
bl_use_exclude_layers = True
bl_use_save_buffers = True
bl_use_spherical_stereo = True
def __init__(self):
self.session = None
def __del__(self):
engine.free(self)
# final render
def update(self, data, scene):
if not self.session:
if self.is_preview:
cscene = bpy.context.scene.cycles
use_osl = cscene.shading_system and cscene.device == 'CPU'
engine.create(self, data, scene,
None, None, None, use_osl)
else:
engine.create(self, data, scene)
else:
engine.reset(self, data, scene)
def render(self, scene):
engine.render(self)
def bake(self, scene, obj, pass_type, pass_filter, object_id, pixel_array, num_pixels, depth, result):
engine.bake(self, obj, pass_type, pass_filter, object_id, pixel_array, num_pixels, depth, result)
# viewport render
def view_update(self, context):
if not self.session:
engine.create(self, context.blend_data, context.scene,
context.region, context.space_data, context.region_data)
engine.update(self, context.blend_data, context.scene)
def view_draw(self, context):
engine.draw(self, context.region, context.space_data, context.region_data)
def update_script_node(self, node):
if engine.with_osl():
from . import osl
osl.update_script_node(node, self.report)
else:
self.report({'ERROR'}, "OSL support disabled in this build.")
def engine_exit():
engine.exit()
def register():
from . import ui
from . import properties
from . import presets
import atexit
# Make sure we only registered the callback once.
atexit.unregister(engine_exit)
atexit.register(engine_exit)
engine.init()
properties.register()
ui.register()
presets.register()
bpy.utils.register_module(__name__)
bpy.app.handlers.version_update.append(version_update.do_versions)
def | ():
from . import ui
from . import properties
from . import presets
import atexit
bpy.app.handlers.version_update.remove(version_update.do_versions)
ui.unregister()
properties.unregister()
presets.unregister()
bpy.utils.unregister_module(__name__)
| unregister | identifier_name |
__init__.py | #
# Copyright 2011-2013 Blender Foundation
#
# 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.
#
# <pep8 compliant>
bl_info = {
"name": "Cycles Render Engine",
"author": "",
"blender": (2, 76, 0),
"location": "Info header, render engine menu",
"description": "Cycles Render Engine integration",
"warning": "",
"wiki_url": "https://www.blender.org/manual/render/cycles/index.html",
"tracker_url": "",
"support": 'OFFICIAL',
"category": "Render"}
import bpy
from . import (
engine,
version_update,
)
class CyclesRender(bpy.types.RenderEngine):
bl_idname = 'CYCLES'
bl_label = "Cycles Render"
bl_use_shading_nodes = True
bl_use_preview = True
bl_use_exclude_layers = True
bl_use_save_buffers = True
bl_use_spherical_stereo = True
def __init__(self):
self.session = None
def __del__(self):
engine.free(self)
# final render
def update(self, data, scene):
if not self.session:
if self.is_preview:
cscene = bpy.context.scene.cycles
use_osl = cscene.shading_system and cscene.device == 'CPU'
engine.create(self, data, scene,
None, None, None, use_osl)
else:
engine.create(self, data, scene)
else:
engine.reset(self, data, scene)
def render(self, scene):
engine.render(self)
def bake(self, scene, obj, pass_type, pass_filter, object_id, pixel_array, num_pixels, depth, result):
engine.bake(self, obj, pass_type, pass_filter, object_id, pixel_array, num_pixels, depth, result)
# viewport render
def view_update(self, context):
if not self.session:
engine.create(self, context.blend_data, context.scene,
context.region, context.space_data, context.region_data)
engine.update(self, context.blend_data, context.scene)
def view_draw(self, context):
engine.draw(self, context.region, context.space_data, context.region_data)
def update_script_node(self, node):
if engine.with_osl():
from . import osl
osl.update_script_node(node, self.report)
else:
|
def engine_exit():
engine.exit()
def register():
from . import ui
from . import properties
from . import presets
import atexit
# Make sure we only registered the callback once.
atexit.unregister(engine_exit)
atexit.register(engine_exit)
engine.init()
properties.register()
ui.register()
presets.register()
bpy.utils.register_module(__name__)
bpy.app.handlers.version_update.append(version_update.do_versions)
def unregister():
from . import ui
from . import properties
from . import presets
import atexit
bpy.app.handlers.version_update.remove(version_update.do_versions)
ui.unregister()
properties.unregister()
presets.unregister()
bpy.utils.unregister_module(__name__)
| self.report({'ERROR'}, "OSL support disabled in this build.") | conditional_block |
browser-files.js | 'use strict'
var EventManager = require('ethereum-remix').lib.EventManager
function Files (storage) {
var event = new EventManager()
this.event = event
var readonly = {}
this.type = 'browser'
this.exists = function (path) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config file
if (path === '.remix.config') {
return false
}
return this.isReadOnly(unprefixedpath) || storage.exists(unprefixedpath)
}
this.init = function (cb) {
cb()
}
this.get = function (path, cb) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config file
if (path === '.remix.config') {
return null
}
var content = readonly[unprefixedpath] || storage.get(unprefixedpath)
if (cb) {
cb(null, content)
}
return content
}
this.set = function (path, content) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config file
if (path === '.remix.config') {
return false
}
if (!this.isReadOnly(unprefixedpath)) {
var exists = storage.exists(unprefixedpath)
if (!storage.set(unprefixedpath, content)) {
return false
}
if (!exists) {
event.trigger('fileAdded', [this.type + '/' + unprefixedpath, false])
} else {
event.trigger('fileChanged', [this.type + '/' + unprefixedpath])
}
return true
}
return false
}
this.addReadOnly = function (path, content) {
var unprefixedpath = this.removePrefix(path)
if (!storage.exists(unprefixedpath)) {
readonly[unprefixedpath] = content
event.trigger('fileAdded', [this.type + '/' + unprefixedpath, true])
return true
}
return false
}
this.isReadOnly = function (path) {
path = this.removePrefix(path)
return readonly[path] !== undefined
}
this.remove = function (path) {
var unprefixedpath = this.removePrefix(path)
if (!this.exists(unprefixedpath)) {
return false
}
if (this.isReadOnly(unprefixedpath)) {
readonly[unprefixedpath] = undefined
} else {
if (!storage.remove(unprefixedpath)) {
return false
}
}
event.trigger('fileRemoved', [this.type + '/' + unprefixedpath])
return true
}
this.rename = function (oldPath, newPath, isFolder) {
var unprefixedoldPath = this.removePrefix(oldPath)
var unprefixednewPath = this.removePrefix(newPath)
if (!this.isReadOnly(unprefixedoldPath) && storage.exists(unprefixedoldPath)) {
if (!storage.rename(unprefixedoldPath, unprefixednewPath)) {
return false
}
event.trigger('fileRenamed', [this.type + '/' + unprefixedoldPath, this.type + '/' + unprefixednewPath, isFolder])
return true
}
return false
}
this.list = function () {
var files = {}
// add r/w files to the list
storage.keys().forEach((path) => {
// NOTE: as a temporary measure do not show the config file
if (path !== '.remix.config') {
files[this.type + '/' + path] = false
}
})
// add r/o files to the list
Object.keys(readonly).forEach((path) => {
files[this.type + '/' + path] = true
})
return files
}
this.removePrefix = function (path) {
return path.indexOf(this.type + '/') === 0 ? path.replace(this.type + '/', '') : path
}
//
// Tree model for files
// {
// 'a': { }, // empty directory 'a'
// 'b': {
// 'c': {}, // empty directory 'b/c'
// 'd': { '/readonly': true, '/content': 'Hello World' } // files 'b/c/d'
// 'e': { '/readonly': false, '/path': 'b/c/d' } // symlink to 'b/c/d'
// 'f': { '/readonly': false, '/content': '<executable>', '/mode': 0755 }
// }
// }
//
this.listAsTree = function () {
function hashmapize (obj, path, val) |
var tree = {}
var self = this
// This does not include '.remix.config', because it is filtered
// inside list().
Object.keys(this.list()).forEach(function (path) {
hashmapize(tree, path, {
'/readonly': self.isReadOnly(path),
'/content': self.get(path)
})
})
return tree
}
// rename .browser-solidity.json to .remix.config
if (this.exists('.browser-solidity.json')) {
this.rename('.browser-solidity.json', '.remix.config')
}
}
module.exports = Files
| {
var nodes = path.split('/')
var i = 0
for (; i < nodes.length - 1; i++) {
var node = nodes[i]
if (obj[node] === undefined) {
obj[node] = {}
}
obj = obj[node]
}
obj[nodes[i]] = val
} | identifier_body |
browser-files.js | 'use strict'
var EventManager = require('ethereum-remix').lib.EventManager
function Files (storage) {
var event = new EventManager()
this.event = event
var readonly = {}
this.type = 'browser'
this.exists = function (path) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config file
if (path === '.remix.config') {
return false
}
return this.isReadOnly(unprefixedpath) || storage.exists(unprefixedpath)
}
this.init = function (cb) {
cb()
}
this.get = function (path, cb) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config file
if (path === '.remix.config') {
return null
}
var content = readonly[unprefixedpath] || storage.get(unprefixedpath)
if (cb) {
cb(null, content)
}
return content
}
this.set = function (path, content) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config file
if (path === '.remix.config') {
return false
}
if (!this.isReadOnly(unprefixedpath)) {
var exists = storage.exists(unprefixedpath)
if (!storage.set(unprefixedpath, content)) {
return false
}
if (!exists) {
event.trigger('fileAdded', [this.type + '/' + unprefixedpath, false])
} else {
event.trigger('fileChanged', [this.type + '/' + unprefixedpath])
}
return true
}
return false
}
this.addReadOnly = function (path, content) {
var unprefixedpath = this.removePrefix(path)
if (!storage.exists(unprefixedpath)) {
readonly[unprefixedpath] = content
event.trigger('fileAdded', [this.type + '/' + unprefixedpath, true])
return true
}
return false
}
this.isReadOnly = function (path) {
path = this.removePrefix(path)
return readonly[path] !== undefined
}
this.remove = function (path) {
var unprefixedpath = this.removePrefix(path)
if (!this.exists(unprefixedpath)) {
return false
}
if (this.isReadOnly(unprefixedpath)) {
readonly[unprefixedpath] = undefined
} else {
if (!storage.remove(unprefixedpath)) {
return false
}
}
event.trigger('fileRemoved', [this.type + '/' + unprefixedpath])
return true
}
this.rename = function (oldPath, newPath, isFolder) {
var unprefixedoldPath = this.removePrefix(oldPath)
var unprefixednewPath = this.removePrefix(newPath)
if (!this.isReadOnly(unprefixedoldPath) && storage.exists(unprefixedoldPath)) {
if (!storage.rename(unprefixedoldPath, unprefixednewPath)) {
return false
}
event.trigger('fileRenamed', [this.type + '/' + unprefixedoldPath, this.type + '/' + unprefixednewPath, isFolder])
return true
}
return false
}
this.list = function () {
var files = {}
// add r/w files to the list
storage.keys().forEach((path) => {
// NOTE: as a temporary measure do not show the config file
if (path !== '.remix.config') {
files[this.type + '/' + path] = false
}
})
// add r/o files to the list
Object.keys(readonly).forEach((path) => {
files[this.type + '/' + path] = true
})
return files
} | this.removePrefix = function (path) {
return path.indexOf(this.type + '/') === 0 ? path.replace(this.type + '/', '') : path
}
//
// Tree model for files
// {
// 'a': { }, // empty directory 'a'
// 'b': {
// 'c': {}, // empty directory 'b/c'
// 'd': { '/readonly': true, '/content': 'Hello World' } // files 'b/c/d'
// 'e': { '/readonly': false, '/path': 'b/c/d' } // symlink to 'b/c/d'
// 'f': { '/readonly': false, '/content': '<executable>', '/mode': 0755 }
// }
// }
//
this.listAsTree = function () {
function hashmapize (obj, path, val) {
var nodes = path.split('/')
var i = 0
for (; i < nodes.length - 1; i++) {
var node = nodes[i]
if (obj[node] === undefined) {
obj[node] = {}
}
obj = obj[node]
}
obj[nodes[i]] = val
}
var tree = {}
var self = this
// This does not include '.remix.config', because it is filtered
// inside list().
Object.keys(this.list()).forEach(function (path) {
hashmapize(tree, path, {
'/readonly': self.isReadOnly(path),
'/content': self.get(path)
})
})
return tree
}
// rename .browser-solidity.json to .remix.config
if (this.exists('.browser-solidity.json')) {
this.rename('.browser-solidity.json', '.remix.config')
}
}
module.exports = Files | random_line_split | |
browser-files.js | 'use strict'
var EventManager = require('ethereum-remix').lib.EventManager
function Files (storage) {
var event = new EventManager()
this.event = event
var readonly = {}
this.type = 'browser'
this.exists = function (path) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config file
if (path === '.remix.config') {
return false
}
return this.isReadOnly(unprefixedpath) || storage.exists(unprefixedpath)
}
this.init = function (cb) {
cb()
}
this.get = function (path, cb) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config file
if (path === '.remix.config') {
return null
}
var content = readonly[unprefixedpath] || storage.get(unprefixedpath)
if (cb) {
cb(null, content)
}
return content
}
this.set = function (path, content) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config file
if (path === '.remix.config') {
return false
}
if (!this.isReadOnly(unprefixedpath)) {
var exists = storage.exists(unprefixedpath)
if (!storage.set(unprefixedpath, content)) {
return false
}
if (!exists) {
event.trigger('fileAdded', [this.type + '/' + unprefixedpath, false])
} else {
event.trigger('fileChanged', [this.type + '/' + unprefixedpath])
}
return true
}
return false
}
this.addReadOnly = function (path, content) {
var unprefixedpath = this.removePrefix(path)
if (!storage.exists(unprefixedpath)) {
readonly[unprefixedpath] = content
event.trigger('fileAdded', [this.type + '/' + unprefixedpath, true])
return true
}
return false
}
this.isReadOnly = function (path) {
path = this.removePrefix(path)
return readonly[path] !== undefined
}
this.remove = function (path) {
var unprefixedpath = this.removePrefix(path)
if (!this.exists(unprefixedpath)) {
return false
}
if (this.isReadOnly(unprefixedpath)) {
readonly[unprefixedpath] = undefined
} else {
if (!storage.remove(unprefixedpath)) {
return false
}
}
event.trigger('fileRemoved', [this.type + '/' + unprefixedpath])
return true
}
this.rename = function (oldPath, newPath, isFolder) {
var unprefixedoldPath = this.removePrefix(oldPath)
var unprefixednewPath = this.removePrefix(newPath)
if (!this.isReadOnly(unprefixedoldPath) && storage.exists(unprefixedoldPath)) {
if (!storage.rename(unprefixedoldPath, unprefixednewPath)) |
event.trigger('fileRenamed', [this.type + '/' + unprefixedoldPath, this.type + '/' + unprefixednewPath, isFolder])
return true
}
return false
}
this.list = function () {
var files = {}
// add r/w files to the list
storage.keys().forEach((path) => {
// NOTE: as a temporary measure do not show the config file
if (path !== '.remix.config') {
files[this.type + '/' + path] = false
}
})
// add r/o files to the list
Object.keys(readonly).forEach((path) => {
files[this.type + '/' + path] = true
})
return files
}
this.removePrefix = function (path) {
return path.indexOf(this.type + '/') === 0 ? path.replace(this.type + '/', '') : path
}
//
// Tree model for files
// {
// 'a': { }, // empty directory 'a'
// 'b': {
// 'c': {}, // empty directory 'b/c'
// 'd': { '/readonly': true, '/content': 'Hello World' } // files 'b/c/d'
// 'e': { '/readonly': false, '/path': 'b/c/d' } // symlink to 'b/c/d'
// 'f': { '/readonly': false, '/content': '<executable>', '/mode': 0755 }
// }
// }
//
this.listAsTree = function () {
function hashmapize (obj, path, val) {
var nodes = path.split('/')
var i = 0
for (; i < nodes.length - 1; i++) {
var node = nodes[i]
if (obj[node] === undefined) {
obj[node] = {}
}
obj = obj[node]
}
obj[nodes[i]] = val
}
var tree = {}
var self = this
// This does not include '.remix.config', because it is filtered
// inside list().
Object.keys(this.list()).forEach(function (path) {
hashmapize(tree, path, {
'/readonly': self.isReadOnly(path),
'/content': self.get(path)
})
})
return tree
}
// rename .browser-solidity.json to .remix.config
if (this.exists('.browser-solidity.json')) {
this.rename('.browser-solidity.json', '.remix.config')
}
}
module.exports = Files
| {
return false
} | conditional_block |
browser-files.js | 'use strict'
var EventManager = require('ethereum-remix').lib.EventManager
function Files (storage) {
var event = new EventManager()
this.event = event
var readonly = {}
this.type = 'browser'
this.exists = function (path) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config file
if (path === '.remix.config') {
return false
}
return this.isReadOnly(unprefixedpath) || storage.exists(unprefixedpath)
}
this.init = function (cb) {
cb()
}
this.get = function (path, cb) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config file
if (path === '.remix.config') {
return null
}
var content = readonly[unprefixedpath] || storage.get(unprefixedpath)
if (cb) {
cb(null, content)
}
return content
}
this.set = function (path, content) {
var unprefixedpath = this.removePrefix(path)
// NOTE: ignore the config file
if (path === '.remix.config') {
return false
}
if (!this.isReadOnly(unprefixedpath)) {
var exists = storage.exists(unprefixedpath)
if (!storage.set(unprefixedpath, content)) {
return false
}
if (!exists) {
event.trigger('fileAdded', [this.type + '/' + unprefixedpath, false])
} else {
event.trigger('fileChanged', [this.type + '/' + unprefixedpath])
}
return true
}
return false
}
this.addReadOnly = function (path, content) {
var unprefixedpath = this.removePrefix(path)
if (!storage.exists(unprefixedpath)) {
readonly[unprefixedpath] = content
event.trigger('fileAdded', [this.type + '/' + unprefixedpath, true])
return true
}
return false
}
this.isReadOnly = function (path) {
path = this.removePrefix(path)
return readonly[path] !== undefined
}
this.remove = function (path) {
var unprefixedpath = this.removePrefix(path)
if (!this.exists(unprefixedpath)) {
return false
}
if (this.isReadOnly(unprefixedpath)) {
readonly[unprefixedpath] = undefined
} else {
if (!storage.remove(unprefixedpath)) {
return false
}
}
event.trigger('fileRemoved', [this.type + '/' + unprefixedpath])
return true
}
this.rename = function (oldPath, newPath, isFolder) {
var unprefixedoldPath = this.removePrefix(oldPath)
var unprefixednewPath = this.removePrefix(newPath)
if (!this.isReadOnly(unprefixedoldPath) && storage.exists(unprefixedoldPath)) {
if (!storage.rename(unprefixedoldPath, unprefixednewPath)) {
return false
}
event.trigger('fileRenamed', [this.type + '/' + unprefixedoldPath, this.type + '/' + unprefixednewPath, isFolder])
return true
}
return false
}
this.list = function () {
var files = {}
// add r/w files to the list
storage.keys().forEach((path) => {
// NOTE: as a temporary measure do not show the config file
if (path !== '.remix.config') {
files[this.type + '/' + path] = false
}
})
// add r/o files to the list
Object.keys(readonly).forEach((path) => {
files[this.type + '/' + path] = true
})
return files
}
this.removePrefix = function (path) {
return path.indexOf(this.type + '/') === 0 ? path.replace(this.type + '/', '') : path
}
//
// Tree model for files
// {
// 'a': { }, // empty directory 'a'
// 'b': {
// 'c': {}, // empty directory 'b/c'
// 'd': { '/readonly': true, '/content': 'Hello World' } // files 'b/c/d'
// 'e': { '/readonly': false, '/path': 'b/c/d' } // symlink to 'b/c/d'
// 'f': { '/readonly': false, '/content': '<executable>', '/mode': 0755 }
// }
// }
//
this.listAsTree = function () {
function | (obj, path, val) {
var nodes = path.split('/')
var i = 0
for (; i < nodes.length - 1; i++) {
var node = nodes[i]
if (obj[node] === undefined) {
obj[node] = {}
}
obj = obj[node]
}
obj[nodes[i]] = val
}
var tree = {}
var self = this
// This does not include '.remix.config', because it is filtered
// inside list().
Object.keys(this.list()).forEach(function (path) {
hashmapize(tree, path, {
'/readonly': self.isReadOnly(path),
'/content': self.get(path)
})
})
return tree
}
// rename .browser-solidity.json to .remix.config
if (this.exists('.browser-solidity.json')) {
this.rename('.browser-solidity.json', '.remix.config')
}
}
module.exports = Files
| hashmapize | identifier_name |
hintrc.js | {
// environment
"browser": true,
"node": true,
"globals": {
"L": true,
"define": true,
"map":true,
"jQuery":true
// "drawnItems":true
},
"strict": false,
// code style
"bitwise": true,
"camelcase": true,
"curly": true,
"eqeqeq": true,
"forin": false,
"immed": true,
"latedef": true,
"newcap": true,
"noarg": true,
"noempty": true,
"nonew": true,
"undef": true,
"unused": true,
"quotmark": "single",
// whitespace
"indent": 4,
"trailing": true,
"white": true,
"smarttabs": true,
"maxlen": 150 | // "maxparams": 4,
// "maxdepth": 4
} |
// code simplicity - not enforced but nice to check from time to time
// "maxstatements": 20,
// "maxcomplexity": 5 | random_line_split |
movie-score.component.ts | import {Component, OnInit, OnChanges, SimpleChange, Input, Output, EventEmitter, ChangeDetectionStrategy} from '@angular/core';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'movie-score',
templateUrl: 'app/components/movie-score/movie-score.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MovieScoreComponent implements OnInit, OnChanges {
upVoteWidth: string = "0%";
downVoteWidth: string = "0%";
@Input() upVotes: number;
@Input() downVotes: number;
@Output() public scoringOutput: EventEmitter<any> = new EventEmitter();
constructor() {
|
upVoteThisRecord() {
this.scoringOutput.emit('upvote');
}
downVoteThisRecord() {
this.scoringOutput.emit('downvote');
}
recalculateVoteStatusBar() {
let totalVotes = this.upVotes + this.downVotes;
if (this.upVotes > 0) {
this.upVoteWidth = ((this.upVotes / totalVotes) * 100) + "%";
}
if (this.downVotes > 0) {
this.downVoteWidth = ((this.downVotes / totalVotes) * 100) + "%";
}
}
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
this.recalculateVoteStatusBar();
}
ngOnInit() {
}
} |
}
| identifier_body |
movie-score.component.ts | import {Component, OnInit, OnChanges, SimpleChange, Input, Output, EventEmitter, ChangeDetectionStrategy} from '@angular/core';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'movie-score',
templateUrl: 'app/components/movie-score/movie-score.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MovieScoreComponent implements OnInit, OnChanges {
upVoteWidth: string = "0%";
downVoteWidth: string = "0%";
@Input() upVotes: number;
@Input() downVotes: number;
@Output() public scoringOutput: EventEmitter<any> = new EventEmitter();
co | {
}
upVoteThisRecord() {
this.scoringOutput.emit('upvote');
}
downVoteThisRecord() {
this.scoringOutput.emit('downvote');
}
recalculateVoteStatusBar() {
let totalVotes = this.upVotes + this.downVotes;
if (this.upVotes > 0) {
this.upVoteWidth = ((this.upVotes / totalVotes) * 100) + "%";
}
if (this.downVotes > 0) {
this.downVoteWidth = ((this.downVotes / totalVotes) * 100) + "%";
}
}
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
this.recalculateVoteStatusBar();
}
ngOnInit() {
}
} | nstructor() | identifier_name |
movie-score.component.ts | import {Component, OnInit, OnChanges, SimpleChange, Input, Output, EventEmitter, ChangeDetectionStrategy} from '@angular/core';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'movie-score',
templateUrl: 'app/components/movie-score/movie-score.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MovieScoreComponent implements OnInit, OnChanges {
upVoteWidth: string = "0%";
downVoteWidth: string = "0%";
@Input() upVotes: number;
@Input() downVotes: number;
@Output() public scoringOutput: EventEmitter<any> = new EventEmitter();
constructor() {
}
upVoteThisRecord() {
this.scoringOutput.emit('upvote');
}
downVoteThisRecord() {
this.scoringOutput.emit('downvote');
}
recalculateVoteStatusBar() {
let totalVotes = this.upVotes + this.downVotes;
if (this.upVotes > 0) {
this.upVoteWidth = ((this.upVotes / totalVotes) * 100) + "%";
}
if (this.downVotes > 0) {
| }
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
this.recalculateVoteStatusBar();
}
ngOnInit() {
}
} |
this.downVoteWidth = ((this.downVotes / totalVotes) * 100) + "%";
}
| conditional_block |
movie-score.component.ts | import {Component, OnInit, OnChanges, SimpleChange, Input, Output, EventEmitter, ChangeDetectionStrategy} from '@angular/core';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'movie-score',
templateUrl: 'app/components/movie-score/movie-score.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MovieScoreComponent implements OnInit, OnChanges {
| @Output() public scoringOutput: EventEmitter<any> = new EventEmitter();
constructor() {
}
upVoteThisRecord() {
this.scoringOutput.emit('upvote');
}
downVoteThisRecord() {
this.scoringOutput.emit('downvote');
}
recalculateVoteStatusBar() {
let totalVotes = this.upVotes + this.downVotes;
if (this.upVotes > 0) {
this.upVoteWidth = ((this.upVotes / totalVotes) * 100) + "%";
}
if (this.downVotes > 0) {
this.downVoteWidth = ((this.downVotes / totalVotes) * 100) + "%";
}
}
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
this.recalculateVoteStatusBar();
}
ngOnInit() {
}
} | upVoteWidth: string = "0%";
downVoteWidth: string = "0%";
@Input() upVotes: number;
@Input() downVotes: number;
| random_line_split |
RichEditor.tsx | import * as React from 'react';
import { useAppDispatch, useAppSelector } from '~/hooks';
import * as editor from '~/core/editor';
import * as entities from '~/core/entities';
import { fluent } from '~/core/utils';
import RichTranslationForm from './RichTranslationForm';
type Props = {
ftlSwitch: React.ReactNode;
};
/**
* Rich Editor for supported Fluent strings.
*
* This shows the Fluent translation based on its AST, presenting a nicer
* interface to the user. The translation is stored as an AST, and changes
* are made directly to that AST. That is why lots of Editor methods are | const dispatch = useAppDispatch();
const sendTranslation = editor.useSendTranslation();
const updateTranslation = editor.useUpdateTranslation();
const translation = useAppSelector((state) => state.editor.translation);
const entity = useAppSelector((state) =>
entities.selectors.getSelectedEntity(state),
);
const changeSource = useAppSelector((state) => state.editor.changeSource);
const locale = useAppSelector((state) => state.locale);
/**
* Hook that makes sure the translation is a Fluent message.
*/
React.useLayoutEffect(() => {
if (typeof translation === 'string') {
const message = fluent.parser.parseEntry(translation);
// We need to check the syntax, because it can happen that a
// translation changes syntax, for example if loading a new one
// from history. In such cases, this RichEditor will render with
// the new translation, but must not re-format it. We thus make sure
// that the syntax of the translation is "rich" before we update it.
const syntax = fluent.getSyntaxType(message);
if (syntax !== 'rich') {
return;
}
updateTranslation(fluent.flattenMessage(message), changeSource);
}
}, [translation, changeSource, updateTranslation, dispatch]);
function clearEditor() {
if (entity) {
updateTranslation(
fluent.getEmptyMessage(
fluent.parser.parseEntry(entity.original),
locale,
),
);
}
}
function copyOriginalIntoEditor() {
if (entity) {
const origMsg = fluent.parser.parseEntry(entity.original);
updateTranslation(fluent.flattenMessage(origMsg));
}
}
function sendFluentTranslation(ignoreWarnings?: boolean) {
const fluentString = fluent.serializer.serializeEntry(translation);
sendTranslation(ignoreWarnings, fluentString);
}
return (
<>
<RichTranslationForm
clearEditor={clearEditor}
copyOriginalIntoEditor={copyOriginalIntoEditor}
sendTranslation={sendFluentTranslation}
updateTranslation={updateTranslation}
/>
<editor.EditorMenu
firstItemHook={props.ftlSwitch}
clearEditor={clearEditor}
copyOriginalIntoEditor={copyOriginalIntoEditor}
sendTranslation={sendFluentTranslation}
/>
</>
);
} | * overwritten, to handle the conversion from AST to string and back.
*/
export default function RichEditor(props: Props): React.ReactElement<any> { | random_line_split |
RichEditor.tsx | import * as React from 'react';
import { useAppDispatch, useAppSelector } from '~/hooks';
import * as editor from '~/core/editor';
import * as entities from '~/core/entities';
import { fluent } from '~/core/utils';
import RichTranslationForm from './RichTranslationForm';
type Props = {
ftlSwitch: React.ReactNode;
};
/**
* Rich Editor for supported Fluent strings.
*
* This shows the Fluent translation based on its AST, presenting a nicer
* interface to the user. The translation is stored as an AST, and changes
* are made directly to that AST. That is why lots of Editor methods are
* overwritten, to handle the conversion from AST to string and back.
*/
export default function RichEditor(props: Props): React.ReactElement<any> {
const dispatch = useAppDispatch();
const sendTranslation = editor.useSendTranslation();
const updateTranslation = editor.useUpdateTranslation();
const translation = useAppSelector((state) => state.editor.translation);
const entity = useAppSelector((state) =>
entities.selectors.getSelectedEntity(state),
);
const changeSource = useAppSelector((state) => state.editor.changeSource);
const locale = useAppSelector((state) => state.locale);
/**
* Hook that makes sure the translation is a Fluent message.
*/
React.useLayoutEffect(() => {
if (typeof translation === 'string') {
const message = fluent.parser.parseEntry(translation);
// We need to check the syntax, because it can happen that a
// translation changes syntax, for example if loading a new one
// from history. In such cases, this RichEditor will render with
// the new translation, but must not re-format it. We thus make sure
// that the syntax of the translation is "rich" before we update it.
const syntax = fluent.getSyntaxType(message);
if (syntax !== 'rich') {
return;
}
updateTranslation(fluent.flattenMessage(message), changeSource);
}
}, [translation, changeSource, updateTranslation, dispatch]);
function clearEditor() {
if (entity) |
}
function copyOriginalIntoEditor() {
if (entity) {
const origMsg = fluent.parser.parseEntry(entity.original);
updateTranslation(fluent.flattenMessage(origMsg));
}
}
function sendFluentTranslation(ignoreWarnings?: boolean) {
const fluentString = fluent.serializer.serializeEntry(translation);
sendTranslation(ignoreWarnings, fluentString);
}
return (
<>
<RichTranslationForm
clearEditor={clearEditor}
copyOriginalIntoEditor={copyOriginalIntoEditor}
sendTranslation={sendFluentTranslation}
updateTranslation={updateTranslation}
/>
<editor.EditorMenu
firstItemHook={props.ftlSwitch}
clearEditor={clearEditor}
copyOriginalIntoEditor={copyOriginalIntoEditor}
sendTranslation={sendFluentTranslation}
/>
</>
);
}
| {
updateTranslation(
fluent.getEmptyMessage(
fluent.parser.parseEntry(entity.original),
locale,
),
);
} | conditional_block |
RichEditor.tsx | import * as React from 'react';
import { useAppDispatch, useAppSelector } from '~/hooks';
import * as editor from '~/core/editor';
import * as entities from '~/core/entities';
import { fluent } from '~/core/utils';
import RichTranslationForm from './RichTranslationForm';
type Props = {
ftlSwitch: React.ReactNode;
};
/**
* Rich Editor for supported Fluent strings.
*
* This shows the Fluent translation based on its AST, presenting a nicer
* interface to the user. The translation is stored as an AST, and changes
* are made directly to that AST. That is why lots of Editor methods are
* overwritten, to handle the conversion from AST to string and back.
*/
export default function RichEditor(props: Props): React.ReactElement<any> {
const dispatch = useAppDispatch();
const sendTranslation = editor.useSendTranslation();
const updateTranslation = editor.useUpdateTranslation();
const translation = useAppSelector((state) => state.editor.translation);
const entity = useAppSelector((state) =>
entities.selectors.getSelectedEntity(state),
);
const changeSource = useAppSelector((state) => state.editor.changeSource);
const locale = useAppSelector((state) => state.locale);
/**
* Hook that makes sure the translation is a Fluent message.
*/
React.useLayoutEffect(() => {
if (typeof translation === 'string') {
const message = fluent.parser.parseEntry(translation);
// We need to check the syntax, because it can happen that a
// translation changes syntax, for example if loading a new one
// from history. In such cases, this RichEditor will render with
// the new translation, but must not re-format it. We thus make sure
// that the syntax of the translation is "rich" before we update it.
const syntax = fluent.getSyntaxType(message);
if (syntax !== 'rich') {
return;
}
updateTranslation(fluent.flattenMessage(message), changeSource);
}
}, [translation, changeSource, updateTranslation, dispatch]);
function clearEditor() |
function copyOriginalIntoEditor() {
if (entity) {
const origMsg = fluent.parser.parseEntry(entity.original);
updateTranslation(fluent.flattenMessage(origMsg));
}
}
function sendFluentTranslation(ignoreWarnings?: boolean) {
const fluentString = fluent.serializer.serializeEntry(translation);
sendTranslation(ignoreWarnings, fluentString);
}
return (
<>
<RichTranslationForm
clearEditor={clearEditor}
copyOriginalIntoEditor={copyOriginalIntoEditor}
sendTranslation={sendFluentTranslation}
updateTranslation={updateTranslation}
/>
<editor.EditorMenu
firstItemHook={props.ftlSwitch}
clearEditor={clearEditor}
copyOriginalIntoEditor={copyOriginalIntoEditor}
sendTranslation={sendFluentTranslation}
/>
</>
);
}
| {
if (entity) {
updateTranslation(
fluent.getEmptyMessage(
fluent.parser.parseEntry(entity.original),
locale,
),
);
}
} | identifier_body |
RichEditor.tsx | import * as React from 'react';
import { useAppDispatch, useAppSelector } from '~/hooks';
import * as editor from '~/core/editor';
import * as entities from '~/core/entities';
import { fluent } from '~/core/utils';
import RichTranslationForm from './RichTranslationForm';
type Props = {
ftlSwitch: React.ReactNode;
};
/**
* Rich Editor for supported Fluent strings.
*
* This shows the Fluent translation based on its AST, presenting a nicer
* interface to the user. The translation is stored as an AST, and changes
* are made directly to that AST. That is why lots of Editor methods are
* overwritten, to handle the conversion from AST to string and back.
*/
export default function RichEditor(props: Props): React.ReactElement<any> {
const dispatch = useAppDispatch();
const sendTranslation = editor.useSendTranslation();
const updateTranslation = editor.useUpdateTranslation();
const translation = useAppSelector((state) => state.editor.translation);
const entity = useAppSelector((state) =>
entities.selectors.getSelectedEntity(state),
);
const changeSource = useAppSelector((state) => state.editor.changeSource);
const locale = useAppSelector((state) => state.locale);
/**
* Hook that makes sure the translation is a Fluent message.
*/
React.useLayoutEffect(() => {
if (typeof translation === 'string') {
const message = fluent.parser.parseEntry(translation);
// We need to check the syntax, because it can happen that a
// translation changes syntax, for example if loading a new one
// from history. In such cases, this RichEditor will render with
// the new translation, but must not re-format it. We thus make sure
// that the syntax of the translation is "rich" before we update it.
const syntax = fluent.getSyntaxType(message);
if (syntax !== 'rich') {
return;
}
updateTranslation(fluent.flattenMessage(message), changeSource);
}
}, [translation, changeSource, updateTranslation, dispatch]);
function | () {
if (entity) {
updateTranslation(
fluent.getEmptyMessage(
fluent.parser.parseEntry(entity.original),
locale,
),
);
}
}
function copyOriginalIntoEditor() {
if (entity) {
const origMsg = fluent.parser.parseEntry(entity.original);
updateTranslation(fluent.flattenMessage(origMsg));
}
}
function sendFluentTranslation(ignoreWarnings?: boolean) {
const fluentString = fluent.serializer.serializeEntry(translation);
sendTranslation(ignoreWarnings, fluentString);
}
return (
<>
<RichTranslationForm
clearEditor={clearEditor}
copyOriginalIntoEditor={copyOriginalIntoEditor}
sendTranslation={sendFluentTranslation}
updateTranslation={updateTranslation}
/>
<editor.EditorMenu
firstItemHook={props.ftlSwitch}
clearEditor={clearEditor}
copyOriginalIntoEditor={copyOriginalIntoEditor}
sendTranslation={sendFluentTranslation}
/>
</>
);
}
| clearEditor | identifier_name |
all_4.js | var searchData=
[
['detailcontroller',['DetailController',['../classDetailController.html',1,'']]],
['detailcontroller_2ephp',['detailController.php',['../detailController_8php.html',1,'']]],
['detailmodel_2ephp',['detailModel.php',['../detailModel_8php.html',1,'']]],
['detailsitemodel_2ephp',['DetailSiteModel.php',['../DetailSiteModel_8php.html',1,'']]],
['detailsiteremplissage_2ephp',['DetailSiteRemplissage.php',['../DetailSiteRemplissage_8php.html',1,'']]],
['detailview_2ephp',['detailView.php',['../detailView_8php.html',1,'']]],
['disconnect',['Disconnect',['../classArcheoPDO.html#a872bf37047ac3c88f223ee09e0464d28',1,'ArcheoPDO']]],
['displaydeconnexion',['DisplayDeconnexion',['../classUserController.html#a3236e398d5a6dacd18740fdedc8c3f29',1,'UserController']]],
['displaydetailview',['DisplayDetailView',['../classDetailController.html#a9f86c923984a8a14890a5b5a74d6747c',1,'DetailController']]],
['displaymapview',['displayMapView',['../classMap.html#a071b0a13bf443b369d8f14567ac49f1f',1,'Map']]],
['displayresultsearchview',['DisplayResultSearchView',['../classSearchController.html#a68ab90cf69065e355f8b9e9e023ad368',1,'SearchController\DisplayResultSearchView()'],['../classSearchModel.html#ad3a49bd5b6df2acd84cf3ff4f2568cb3',1,'SearchModel\DisplayResultSearchView()']]],
['displaysearchview',['DisplaySearchView',['../classSearchController.html#a79cce4afdc955c3bbe507fef15f9cfcf',1,'SearchController']]],
['displaysitesview',['DisplaySitesView',['../classSitesController.html#a816b3be90b55f6ab00001a7719beb6db',1,'SitesController']]], | ]; | ['displaystatsview',['DisplayStatsView',['../classStats.html#a8283b7e12c9c60c298a4407212204494',1,'Stats']]] | random_line_split |
editableFieldDirective.js | /* Copyright 2013-2016 Extended Mind Technologies Oy
*
* 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.
*/
'use strict';
/* global cordova */
function | ($parse, $rootScope, $timeout, packaging) {
return {
require: '^?editableFieldContainer',
restrict: 'A',
link: function(scope, element, attrs, editableFieldContainerController) {
var editableFieldType;
if (attrs.editableField.length > 0){
editableFieldType = $parse(attrs.editableField)(scope);
}
if (attrs.editableFieldRegisterCallbacks){
var registerCallbacksFn = $parse(attrs.editableFieldRegisterCallbacks);
registerCallbacksFn(scope, {focus: focusElement, blur: blurElement});
}
if (attrs.editableFieldFocus) {
var focusCallback = $parse(attrs.editableFieldFocus).bind(undefined, scope);
}
if (attrs.editableFieldBlur) {
var blurCallback = $parse(attrs.editableFieldBlur).bind(undefined, scope);
}
if (attrs.editableFieldAutofocus && $parse(attrs.editableFieldAutofocus)(scope)) {
focusElement();
}
function focusElement() {
function doFocusElement(){
element[0].focus();
if (packaging === 'android-cordova'){
// In Android we need to force the keyboard up
cordova.plugins.Keyboard.show();
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/document.activeElement
if (document.activeElement !== element[0]){
if ($rootScope.$$phase || scope.$$phase){
// It seems $timeout can not be avoided here:
// https://github.com/angular/angular.js/issues/1250
// "In the future, this will (hopefully) be solved with Object.observe."
// We would get "$digest already in progress" without this in some cases.
$timeout(function(){
doFocusElement();
});
}else {
doFocusElement();
}
}
}
var unfocusInProgress = false;
function blurElement(deactivateAfterBlur) {
function doBlurElement(){
element[0].blur();
if (deactivateAfterBlur && editableFieldContainerController)
editableFieldContainerController.deactivateContainer();
}
if (document.activeElement === element[0]){
unfocusInProgress = true;
if ($rootScope.$$phase || scope.$$phase){
// It seems $timeout can not be avoided here:
// https://github.com/angular/angular.js/issues/1250
// "In the future, this will (hopefully) be solved with Object.observe."
// We would get "$digest already in progress" without this in some cases.
$timeout(function(){
doBlurElement();
});
}else {
doBlurElement();
}
}
}
var refocusInProgress = false;
function reFocusEditableField(){
refocusInProgress = true;
focusElement();
}
var editableFieldClicked = function() {
if (editableFieldContainerController) editableFieldContainerController.notifyFocus();
reFocusEditableField();
};
var editableFieldFocus = function() {
if (!refocusInProgress){
if (editableFieldContainerController) editableFieldContainerController.notifyFocus();
if (typeof focusCallback === 'function') executeFocusCallback(focusCallback);
}
refocusInProgress = false;
};
var editableFieldBlur = function() {
if (editableFieldType === 'sticky' && !unfocusInProgress){
reFocusEditableField();
if (editableFieldContainerController) editableFieldContainerController.notifyReFocus(blurElement);
}else{
unfocusInProgress = false;
if (packaging === 'android-cordova'){
// In Android we need to force the keyboard down
cordova.plugins.Keyboard.close();
}
}
if (typeof blurCallback === 'function') blurCallback();
};
function executeFocusCallback(callback) {
// Use $evalAsync, because: "As the focus event is executed synchronously when calling input.focus()
// AngularJS executes the expression using scope.$evalAsync if the event is fired during an $apply to
// ensure a consistent state"
if ($rootScope.$$phase || scope.$$phase){
scope.$evalAsync(callback);
} else {
scope.$apply(callback);
}
}
var editableFieldKeydown = function(event){
// ESC button
if (event.keyCode === 27){
editableFieldBlur();
if (editableFieldContainerController) editableFieldContainerController.deactivateContainer();
}
};
angular.element(element).bind('focus', editableFieldFocus);
angular.element(element).bind('blur', editableFieldBlur);
angular.element(element).bind('keydown', editableFieldKeydown);
if (editableFieldType === 'sticky')
angular.element(element).bind('click', editableFieldClicked);
scope.$on('$destroy', function() {
angular.element(element).unbind('focus', editableFieldFocus);
angular.element(element).unbind('blur', editableFieldBlur);
angular.element(element).unbind('keydown', editableFieldKeydown);
if (editableFieldType === 'sticky')
angular.element(element).unbind('click', editableFieldClicked);
});
}
};
}
editableFieldDirective['$inject'] = ['$parse', '$rootScope', '$timeout', 'packaging'];
angular.module('common').directive('editableField', editableFieldDirective);
| editableFieldDirective | identifier_name |
editableFieldDirective.js | /* Copyright 2013-2016 Extended Mind Technologies Oy
*
* 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.
*/
'use strict';
/* global cordova */
function editableFieldDirective($parse, $rootScope, $timeout, packaging) {
return { |
var editableFieldType;
if (attrs.editableField.length > 0){
editableFieldType = $parse(attrs.editableField)(scope);
}
if (attrs.editableFieldRegisterCallbacks){
var registerCallbacksFn = $parse(attrs.editableFieldRegisterCallbacks);
registerCallbacksFn(scope, {focus: focusElement, blur: blurElement});
}
if (attrs.editableFieldFocus) {
var focusCallback = $parse(attrs.editableFieldFocus).bind(undefined, scope);
}
if (attrs.editableFieldBlur) {
var blurCallback = $parse(attrs.editableFieldBlur).bind(undefined, scope);
}
if (attrs.editableFieldAutofocus && $parse(attrs.editableFieldAutofocus)(scope)) {
focusElement();
}
function focusElement() {
function doFocusElement(){
element[0].focus();
if (packaging === 'android-cordova'){
// In Android we need to force the keyboard up
cordova.plugins.Keyboard.show();
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/document.activeElement
if (document.activeElement !== element[0]){
if ($rootScope.$$phase || scope.$$phase){
// It seems $timeout can not be avoided here:
// https://github.com/angular/angular.js/issues/1250
// "In the future, this will (hopefully) be solved with Object.observe."
// We would get "$digest already in progress" without this in some cases.
$timeout(function(){
doFocusElement();
});
}else {
doFocusElement();
}
}
}
var unfocusInProgress = false;
function blurElement(deactivateAfterBlur) {
function doBlurElement(){
element[0].blur();
if (deactivateAfterBlur && editableFieldContainerController)
editableFieldContainerController.deactivateContainer();
}
if (document.activeElement === element[0]){
unfocusInProgress = true;
if ($rootScope.$$phase || scope.$$phase){
// It seems $timeout can not be avoided here:
// https://github.com/angular/angular.js/issues/1250
// "In the future, this will (hopefully) be solved with Object.observe."
// We would get "$digest already in progress" without this in some cases.
$timeout(function(){
doBlurElement();
});
}else {
doBlurElement();
}
}
}
var refocusInProgress = false;
function reFocusEditableField(){
refocusInProgress = true;
focusElement();
}
var editableFieldClicked = function() {
if (editableFieldContainerController) editableFieldContainerController.notifyFocus();
reFocusEditableField();
};
var editableFieldFocus = function() {
if (!refocusInProgress){
if (editableFieldContainerController) editableFieldContainerController.notifyFocus();
if (typeof focusCallback === 'function') executeFocusCallback(focusCallback);
}
refocusInProgress = false;
};
var editableFieldBlur = function() {
if (editableFieldType === 'sticky' && !unfocusInProgress){
reFocusEditableField();
if (editableFieldContainerController) editableFieldContainerController.notifyReFocus(blurElement);
}else{
unfocusInProgress = false;
if (packaging === 'android-cordova'){
// In Android we need to force the keyboard down
cordova.plugins.Keyboard.close();
}
}
if (typeof blurCallback === 'function') blurCallback();
};
function executeFocusCallback(callback) {
// Use $evalAsync, because: "As the focus event is executed synchronously when calling input.focus()
// AngularJS executes the expression using scope.$evalAsync if the event is fired during an $apply to
// ensure a consistent state"
if ($rootScope.$$phase || scope.$$phase){
scope.$evalAsync(callback);
} else {
scope.$apply(callback);
}
}
var editableFieldKeydown = function(event){
// ESC button
if (event.keyCode === 27){
editableFieldBlur();
if (editableFieldContainerController) editableFieldContainerController.deactivateContainer();
}
};
angular.element(element).bind('focus', editableFieldFocus);
angular.element(element).bind('blur', editableFieldBlur);
angular.element(element).bind('keydown', editableFieldKeydown);
if (editableFieldType === 'sticky')
angular.element(element).bind('click', editableFieldClicked);
scope.$on('$destroy', function() {
angular.element(element).unbind('focus', editableFieldFocus);
angular.element(element).unbind('blur', editableFieldBlur);
angular.element(element).unbind('keydown', editableFieldKeydown);
if (editableFieldType === 'sticky')
angular.element(element).unbind('click', editableFieldClicked);
});
}
};
}
editableFieldDirective['$inject'] = ['$parse', '$rootScope', '$timeout', 'packaging'];
angular.module('common').directive('editableField', editableFieldDirective); | require: '^?editableFieldContainer',
restrict: 'A',
link: function(scope, element, attrs, editableFieldContainerController) { | random_line_split |
editableFieldDirective.js | /* Copyright 2013-2016 Extended Mind Technologies Oy
*
* 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.
*/
'use strict';
/* global cordova */
function editableFieldDirective($parse, $rootScope, $timeout, packaging) {
return {
require: '^?editableFieldContainer',
restrict: 'A',
link: function(scope, element, attrs, editableFieldContainerController) {
var editableFieldType;
if (attrs.editableField.length > 0){
editableFieldType = $parse(attrs.editableField)(scope);
}
if (attrs.editableFieldRegisterCallbacks){
var registerCallbacksFn = $parse(attrs.editableFieldRegisterCallbacks);
registerCallbacksFn(scope, {focus: focusElement, blur: blurElement});
}
if (attrs.editableFieldFocus) {
var focusCallback = $parse(attrs.editableFieldFocus).bind(undefined, scope);
}
if (attrs.editableFieldBlur) {
var blurCallback = $parse(attrs.editableFieldBlur).bind(undefined, scope);
}
if (attrs.editableFieldAutofocus && $parse(attrs.editableFieldAutofocus)(scope)) {
focusElement();
}
function focusElement() {
function doFocusElement(){
element[0].focus();
if (packaging === 'android-cordova'){
// In Android we need to force the keyboard up
cordova.plugins.Keyboard.show();
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/document.activeElement
if (document.activeElement !== element[0]){
if ($rootScope.$$phase || scope.$$phase){
// It seems $timeout can not be avoided here:
// https://github.com/angular/angular.js/issues/1250
// "In the future, this will (hopefully) be solved with Object.observe."
// We would get "$digest already in progress" without this in some cases.
$timeout(function(){
doFocusElement();
});
}else {
doFocusElement();
}
}
}
var unfocusInProgress = false;
function blurElement(deactivateAfterBlur) {
function doBlurElement() |
if (document.activeElement === element[0]){
unfocusInProgress = true;
if ($rootScope.$$phase || scope.$$phase){
// It seems $timeout can not be avoided here:
// https://github.com/angular/angular.js/issues/1250
// "In the future, this will (hopefully) be solved with Object.observe."
// We would get "$digest already in progress" without this in some cases.
$timeout(function(){
doBlurElement();
});
}else {
doBlurElement();
}
}
}
var refocusInProgress = false;
function reFocusEditableField(){
refocusInProgress = true;
focusElement();
}
var editableFieldClicked = function() {
if (editableFieldContainerController) editableFieldContainerController.notifyFocus();
reFocusEditableField();
};
var editableFieldFocus = function() {
if (!refocusInProgress){
if (editableFieldContainerController) editableFieldContainerController.notifyFocus();
if (typeof focusCallback === 'function') executeFocusCallback(focusCallback);
}
refocusInProgress = false;
};
var editableFieldBlur = function() {
if (editableFieldType === 'sticky' && !unfocusInProgress){
reFocusEditableField();
if (editableFieldContainerController) editableFieldContainerController.notifyReFocus(blurElement);
}else{
unfocusInProgress = false;
if (packaging === 'android-cordova'){
// In Android we need to force the keyboard down
cordova.plugins.Keyboard.close();
}
}
if (typeof blurCallback === 'function') blurCallback();
};
function executeFocusCallback(callback) {
// Use $evalAsync, because: "As the focus event is executed synchronously when calling input.focus()
// AngularJS executes the expression using scope.$evalAsync if the event is fired during an $apply to
// ensure a consistent state"
if ($rootScope.$$phase || scope.$$phase){
scope.$evalAsync(callback);
} else {
scope.$apply(callback);
}
}
var editableFieldKeydown = function(event){
// ESC button
if (event.keyCode === 27){
editableFieldBlur();
if (editableFieldContainerController) editableFieldContainerController.deactivateContainer();
}
};
angular.element(element).bind('focus', editableFieldFocus);
angular.element(element).bind('blur', editableFieldBlur);
angular.element(element).bind('keydown', editableFieldKeydown);
if (editableFieldType === 'sticky')
angular.element(element).bind('click', editableFieldClicked);
scope.$on('$destroy', function() {
angular.element(element).unbind('focus', editableFieldFocus);
angular.element(element).unbind('blur', editableFieldBlur);
angular.element(element).unbind('keydown', editableFieldKeydown);
if (editableFieldType === 'sticky')
angular.element(element).unbind('click', editableFieldClicked);
});
}
};
}
editableFieldDirective['$inject'] = ['$parse', '$rootScope', '$timeout', 'packaging'];
angular.module('common').directive('editableField', editableFieldDirective);
| {
element[0].blur();
if (deactivateAfterBlur && editableFieldContainerController)
editableFieldContainerController.deactivateContainer();
} | identifier_body |
editableFieldDirective.js | /* Copyright 2013-2016 Extended Mind Technologies Oy
*
* 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.
*/
'use strict';
/* global cordova */
function editableFieldDirective($parse, $rootScope, $timeout, packaging) {
return {
require: '^?editableFieldContainer',
restrict: 'A',
link: function(scope, element, attrs, editableFieldContainerController) {
var editableFieldType;
if (attrs.editableField.length > 0){
editableFieldType = $parse(attrs.editableField)(scope);
}
if (attrs.editableFieldRegisterCallbacks){
var registerCallbacksFn = $parse(attrs.editableFieldRegisterCallbacks);
registerCallbacksFn(scope, {focus: focusElement, blur: blurElement});
}
if (attrs.editableFieldFocus) {
var focusCallback = $parse(attrs.editableFieldFocus).bind(undefined, scope);
}
if (attrs.editableFieldBlur) {
var blurCallback = $parse(attrs.editableFieldBlur).bind(undefined, scope);
}
if (attrs.editableFieldAutofocus && $parse(attrs.editableFieldAutofocus)(scope)) {
focusElement();
}
function focusElement() {
function doFocusElement(){
element[0].focus();
if (packaging === 'android-cordova'){
// In Android we need to force the keyboard up
cordova.plugins.Keyboard.show();
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/document.activeElement
if (document.activeElement !== element[0]){
if ($rootScope.$$phase || scope.$$phase){
// It seems $timeout can not be avoided here:
// https://github.com/angular/angular.js/issues/1250
// "In the future, this will (hopefully) be solved with Object.observe."
// We would get "$digest already in progress" without this in some cases.
$timeout(function(){
doFocusElement();
});
}else |
}
}
var unfocusInProgress = false;
function blurElement(deactivateAfterBlur) {
function doBlurElement(){
element[0].blur();
if (deactivateAfterBlur && editableFieldContainerController)
editableFieldContainerController.deactivateContainer();
}
if (document.activeElement === element[0]){
unfocusInProgress = true;
if ($rootScope.$$phase || scope.$$phase){
// It seems $timeout can not be avoided here:
// https://github.com/angular/angular.js/issues/1250
// "In the future, this will (hopefully) be solved with Object.observe."
// We would get "$digest already in progress" without this in some cases.
$timeout(function(){
doBlurElement();
});
}else {
doBlurElement();
}
}
}
var refocusInProgress = false;
function reFocusEditableField(){
refocusInProgress = true;
focusElement();
}
var editableFieldClicked = function() {
if (editableFieldContainerController) editableFieldContainerController.notifyFocus();
reFocusEditableField();
};
var editableFieldFocus = function() {
if (!refocusInProgress){
if (editableFieldContainerController) editableFieldContainerController.notifyFocus();
if (typeof focusCallback === 'function') executeFocusCallback(focusCallback);
}
refocusInProgress = false;
};
var editableFieldBlur = function() {
if (editableFieldType === 'sticky' && !unfocusInProgress){
reFocusEditableField();
if (editableFieldContainerController) editableFieldContainerController.notifyReFocus(blurElement);
}else{
unfocusInProgress = false;
if (packaging === 'android-cordova'){
// In Android we need to force the keyboard down
cordova.plugins.Keyboard.close();
}
}
if (typeof blurCallback === 'function') blurCallback();
};
function executeFocusCallback(callback) {
// Use $evalAsync, because: "As the focus event is executed synchronously when calling input.focus()
// AngularJS executes the expression using scope.$evalAsync if the event is fired during an $apply to
// ensure a consistent state"
if ($rootScope.$$phase || scope.$$phase){
scope.$evalAsync(callback);
} else {
scope.$apply(callback);
}
}
var editableFieldKeydown = function(event){
// ESC button
if (event.keyCode === 27){
editableFieldBlur();
if (editableFieldContainerController) editableFieldContainerController.deactivateContainer();
}
};
angular.element(element).bind('focus', editableFieldFocus);
angular.element(element).bind('blur', editableFieldBlur);
angular.element(element).bind('keydown', editableFieldKeydown);
if (editableFieldType === 'sticky')
angular.element(element).bind('click', editableFieldClicked);
scope.$on('$destroy', function() {
angular.element(element).unbind('focus', editableFieldFocus);
angular.element(element).unbind('blur', editableFieldBlur);
angular.element(element).unbind('keydown', editableFieldKeydown);
if (editableFieldType === 'sticky')
angular.element(element).unbind('click', editableFieldClicked);
});
}
};
}
editableFieldDirective['$inject'] = ['$parse', '$rootScope', '$timeout', 'packaging'];
angular.module('common').directive('editableField', editableFieldDirective);
| {
doFocusElement();
} | conditional_block |
tex2.rs |
use std::io::{self, Write};
use image;
use image::GenericImage;
use nom::{le_u8, le_u32};
use byteorder::{LittleEndian, WriteBytesExt};
named!(pub tex2_header<(u32, u32, u8)>,
do_parse!(
tag!("\x11\x40") >> //.@, the magic number for the format
height: le_u32 >>
width: le_u32 >>
mipmaps: le_u8 >>
(height, width, mipmaps)
)
);
named!(pub tex2_pixel<(u8, u8, u8, u8)>,
tuple!(
le_u8,
le_u8,
le_u8,
le_u8
)
);
named!(pub tex2_image<DDTex2Image>,
do_parse!(
header: tex2_header >>
pixels: count!(tex2_pixel, calc_offset(header.0, header.1, (header.2 as u32)+1) as usize) >>
(DDTex2Image {
mipmap_levels: header.2,
mipmap_current: 0,
height: header.0,
width: header.1,
pixels: pixels
})
)
);
pub struct DDTex2Image {
pub mipmap_levels: u8,
mipmap_current: u8,
pub height: u32,
pub width: u32,
pub pixels: Vec<(u8, u8, u8, u8)>
}
impl DDTex2Image {
pub fn new(width: u32, height: u32) -> Self {
DDTex2Image {
mipmap_levels: 0,
mipmap_current: 0,
height: height,
width: width,
pixels: vec![(0, 0, 0, 0); (height*width) as usize]
}
}
pub fn save(&self, mut dst: &mut Write) -> io::Result<()> {
dst.write_u8(0x11)?;
dst.write_u8(0x40)?;
dst.write_u32::<LittleEndian>(self.height)?;
dst.write_u32::<LittleEndian>(self.width)?;
dst.write_u8(self.mipmap_levels)?;
for pixel in self.pixels.iter() {
dst.write_u8(pixel.0)?;
dst.write_u8(pixel.1)?;
dst.write_u8(pixel.2)?;
dst.write_u8(pixel.3)?;
}
Ok(())
}
pub fn set_mipmap(&mut self, new: u8) {
if new != 0 && (!self.height.is_power_of_two() || !self.width.is_power_of_two()) {
panic!("DDTex2Image {}x{}: can't do mipmap levels on non-power-of-two!", self.width, self.height);
}
self.mipmap_current = new;
}
pub fn cur_width(&self) -> u32 {
self.width >> self.mipmap_current
}
pub fn cur_height(&self) -> u32 {
self.height >> self.mipmap_current
}
pub fn | (&self, x: u32, y: u32) -> usize {
(calc_offset(self.height, self.width, (self.mipmap_current) as u32)
+ ((self.cur_width()*y) + x)) as usize
}
pub fn pixel(&self, x: u32, y: u32) -> (u8, u8, u8, u8) {
match self.pixels.get(self.pos(x, y)) {
Some(p) => *p,
None => (0xFF, 0xFF, 0xFF, 0xFF)
}
}
}
#[allow(unused_variables)]
impl GenericImage for DDTex2Image {
type Pixel = image::Rgba<u8>;
fn dimensions(&self) -> (u32, u32) {
(self.cur_width(), self.cur_height())
}
fn bounds(&self) -> (u32, u32, u32, u32) {
(0, 0, self.cur_width(), self.cur_height())
}
fn get_pixel(&self, x: u32, y: u32) -> Self::Pixel {
let p = self.pixel(x, y);
image::Rgba([p.0, p.1, p.2, p.3])
}
fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut Self::Pixel {
unimplemented!()
}
fn put_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
let pos = self.pos(x, y);
self.pixels[pos] = (pixel[0], pixel[1], pixel[2], pixel[3]);
}
fn blend_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
unimplemented!()
}
}
//12:36:48 AM <ubsan> zekesonxx: lemme think about it
//12:36:51 AM <ubsan> I have an idea
//12:37:24 AM <zekesonxx> ubsan: shoot
//12:37:42 AM <ubsan> zekesonxx: alright, so the function definition would be something like
//12:37:57 AM <ubsan> fn foo(x: usize, y: usize, n: u32) -> usize {
//12:39:51 AM <ubsan> let (x, y) = (x.trailing_zeroes(), y.trailing_zeroes()); (0..n).fold(1, |acc, n| acc += 1 << (x - n) * 1 << (y - n))
//12:39:55 AM <ubsan> something like this ^?
//12:52:55 AM <zekesonxx> ubsan: little bit of reworking needed but looks good. Thanks for the help.
//12:53:01 AM <ubsan> zekesonxx: yep!
//12:53:10 AM * ubsan has done some assembly in the past :P
fn calc_offset(height: u32, width: u32, cur_mip: u32) -> u32 {
let (x, y) = (height.trailing_zeros(), width.trailing_zeros());
(0..cur_mip).fold(0u32, |acc, n| acc + (1 << (x - n) * 1 << (y - n)))
} | pos | identifier_name |
tex2.rs |
use std::io::{self, Write};
use image;
use image::GenericImage;
use nom::{le_u8, le_u32};
use byteorder::{LittleEndian, WriteBytesExt};
named!(pub tex2_header<(u32, u32, u8)>,
do_parse!(
tag!("\x11\x40") >> //.@, the magic number for the format
height: le_u32 >>
width: le_u32 >>
mipmaps: le_u8 >>
(height, width, mipmaps)
)
);
named!(pub tex2_pixel<(u8, u8, u8, u8)>,
tuple!(
le_u8,
le_u8,
le_u8,
le_u8
)
);
named!(pub tex2_image<DDTex2Image>,
do_parse!(
header: tex2_header >>
pixels: count!(tex2_pixel, calc_offset(header.0, header.1, (header.2 as u32)+1) as usize) >>
(DDTex2Image {
mipmap_levels: header.2,
mipmap_current: 0,
height: header.0,
width: header.1,
pixels: pixels
})
)
);
pub struct DDTex2Image {
pub mipmap_levels: u8,
mipmap_current: u8,
pub height: u32,
pub width: u32,
pub pixels: Vec<(u8, u8, u8, u8)>
}
impl DDTex2Image {
pub fn new(width: u32, height: u32) -> Self {
DDTex2Image {
mipmap_levels: 0,
mipmap_current: 0,
height: height,
width: width,
pixels: vec![(0, 0, 0, 0); (height*width) as usize]
}
}
pub fn save(&self, mut dst: &mut Write) -> io::Result<()> {
dst.write_u8(0x11)?;
dst.write_u8(0x40)?;
dst.write_u32::<LittleEndian>(self.height)?;
dst.write_u32::<LittleEndian>(self.width)?;
dst.write_u8(self.mipmap_levels)?;
for pixel in self.pixels.iter() {
dst.write_u8(pixel.0)?;
dst.write_u8(pixel.1)?;
dst.write_u8(pixel.2)?;
dst.write_u8(pixel.3)?;
}
Ok(())
}
pub fn set_mipmap(&mut self, new: u8) {
if new != 0 && (!self.height.is_power_of_two() || !self.width.is_power_of_two()) {
panic!("DDTex2Image {}x{}: can't do mipmap levels on non-power-of-two!", self.width, self.height);
}
self.mipmap_current = new;
}
pub fn cur_width(&self) -> u32 {
self.width >> self.mipmap_current
}
pub fn cur_height(&self) -> u32 {
self.height >> self.mipmap_current
}
pub fn pos(&self, x: u32, y: u32) -> usize {
(calc_offset(self.height, self.width, (self.mipmap_current) as u32)
+ ((self.cur_width()*y) + x)) as usize
}
pub fn pixel(&self, x: u32, y: u32) -> (u8, u8, u8, u8) {
match self.pixels.get(self.pos(x, y)) {
Some(p) => *p,
None => (0xFF, 0xFF, 0xFF, 0xFF)
}
}
}
#[allow(unused_variables)]
impl GenericImage for DDTex2Image {
type Pixel = image::Rgba<u8>;
fn dimensions(&self) -> (u32, u32) {
(self.cur_width(), self.cur_height())
}
fn bounds(&self) -> (u32, u32, u32, u32) {
(0, 0, self.cur_width(), self.cur_height())
}
fn get_pixel(&self, x: u32, y: u32) -> Self::Pixel {
let p = self.pixel(x, y);
image::Rgba([p.0, p.1, p.2, p.3])
}
fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut Self::Pixel {
unimplemented!()
}
fn put_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) |
fn blend_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
unimplemented!()
}
}
//12:36:48 AM <ubsan> zekesonxx: lemme think about it
//12:36:51 AM <ubsan> I have an idea
//12:37:24 AM <zekesonxx> ubsan: shoot
//12:37:42 AM <ubsan> zekesonxx: alright, so the function definition would be something like
//12:37:57 AM <ubsan> fn foo(x: usize, y: usize, n: u32) -> usize {
//12:39:51 AM <ubsan> let (x, y) = (x.trailing_zeroes(), y.trailing_zeroes()); (0..n).fold(1, |acc, n| acc += 1 << (x - n) * 1 << (y - n))
//12:39:55 AM <ubsan> something like this ^?
//12:52:55 AM <zekesonxx> ubsan: little bit of reworking needed but looks good. Thanks for the help.
//12:53:01 AM <ubsan> zekesonxx: yep!
//12:53:10 AM * ubsan has done some assembly in the past :P
fn calc_offset(height: u32, width: u32, cur_mip: u32) -> u32 {
let (x, y) = (height.trailing_zeros(), width.trailing_zeros());
(0..cur_mip).fold(0u32, |acc, n| acc + (1 << (x - n) * 1 << (y - n)))
} | {
let pos = self.pos(x, y);
self.pixels[pos] = (pixel[0], pixel[1], pixel[2], pixel[3]);
} | identifier_body |
tex2.rs | use std::io::{self, Write};
use image;
use image::GenericImage;
use nom::{le_u8, le_u32};
use byteorder::{LittleEndian, WriteBytesExt};
named!(pub tex2_header<(u32, u32, u8)>,
do_parse!(
tag!("\x11\x40") >> //.@, the magic number for the format
height: le_u32 >>
width: le_u32 >>
mipmaps: le_u8 >>
(height, width, mipmaps)
)
);
named!(pub tex2_pixel<(u8, u8, u8, u8)>,
tuple!(
le_u8,
le_u8,
le_u8,
le_u8
)
);
named!(pub tex2_image<DDTex2Image>,
do_parse!(
header: tex2_header >>
pixels: count!(tex2_pixel, calc_offset(header.0, header.1, (header.2 as u32)+1) as usize) >>
(DDTex2Image {
mipmap_levels: header.2,
mipmap_current: 0,
height: header.0,
width: header.1,
pixels: pixels
})
)
);
pub struct DDTex2Image {
pub mipmap_levels: u8,
mipmap_current: u8,
pub height: u32,
pub width: u32,
pub pixels: Vec<(u8, u8, u8, u8)>
}
impl DDTex2Image {
pub fn new(width: u32, height: u32) -> Self {
DDTex2Image {
mipmap_levels: 0,
mipmap_current: 0,
height: height,
width: width,
pixels: vec![(0, 0, 0, 0); (height*width) as usize]
}
}
pub fn save(&self, mut dst: &mut Write) -> io::Result<()> {
dst.write_u8(0x11)?;
dst.write_u8(0x40)?;
dst.write_u32::<LittleEndian>(self.height)?;
dst.write_u32::<LittleEndian>(self.width)?;
dst.write_u8(self.mipmap_levels)?;
for pixel in self.pixels.iter() {
dst.write_u8(pixel.0)?;
dst.write_u8(pixel.1)?;
dst.write_u8(pixel.2)?;
dst.write_u8(pixel.3)?;
}
Ok(())
}
pub fn set_mipmap(&mut self, new: u8) {
if new != 0 && (!self.height.is_power_of_two() || !self.width.is_power_of_two()) {
panic!("DDTex2Image {}x{}: can't do mipmap levels on non-power-of-two!", self.width, self.height);
}
self.mipmap_current = new;
}
pub fn cur_width(&self) -> u32 {
self.width >> self.mipmap_current
}
pub fn cur_height(&self) -> u32 {
self.height >> self.mipmap_current
}
pub fn pos(&self, x: u32, y: u32) -> usize {
(calc_offset(self.height, self.width, (self.mipmap_current) as u32)
+ ((self.cur_width()*y) + x)) as usize
}
pub fn pixel(&self, x: u32, y: u32) -> (u8, u8, u8, u8) {
match self.pixels.get(self.pos(x, y)) {
Some(p) => *p,
None => (0xFF, 0xFF, 0xFF, 0xFF)
}
}
}
#[allow(unused_variables)]
impl GenericImage for DDTex2Image {
type Pixel = image::Rgba<u8>;
fn dimensions(&self) -> (u32, u32) { | }
fn get_pixel(&self, x: u32, y: u32) -> Self::Pixel {
let p = self.pixel(x, y);
image::Rgba([p.0, p.1, p.2, p.3])
}
fn get_pixel_mut(&mut self, x: u32, y: u32) -> &mut Self::Pixel {
unimplemented!()
}
fn put_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
let pos = self.pos(x, y);
self.pixels[pos] = (pixel[0], pixel[1], pixel[2], pixel[3]);
}
fn blend_pixel(&mut self, x: u32, y: u32, pixel: Self::Pixel) {
unimplemented!()
}
}
//12:36:48 AM <ubsan> zekesonxx: lemme think about it
//12:36:51 AM <ubsan> I have an idea
//12:37:24 AM <zekesonxx> ubsan: shoot
//12:37:42 AM <ubsan> zekesonxx: alright, so the function definition would be something like
//12:37:57 AM <ubsan> fn foo(x: usize, y: usize, n: u32) -> usize {
//12:39:51 AM <ubsan> let (x, y) = (x.trailing_zeroes(), y.trailing_zeroes()); (0..n).fold(1, |acc, n| acc += 1 << (x - n) * 1 << (y - n))
//12:39:55 AM <ubsan> something like this ^?
//12:52:55 AM <zekesonxx> ubsan: little bit of reworking needed but looks good. Thanks for the help.
//12:53:01 AM <ubsan> zekesonxx: yep!
//12:53:10 AM * ubsan has done some assembly in the past :P
fn calc_offset(height: u32, width: u32, cur_mip: u32) -> u32 {
let (x, y) = (height.trailing_zeros(), width.trailing_zeros());
(0..cur_mip).fold(0u32, |acc, n| acc + (1 << (x - n) * 1 << (y - n)))
} | (self.cur_width(), self.cur_height())
}
fn bounds(&self) -> (u32, u32, u32, u32) {
(0, 0, self.cur_width(), self.cur_height()) | random_line_split |
vi.js | /*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'link', 'vi', {
acccessKey: 'Phím hỗ trợ truy cập',
advanced: 'Mở rộng',
advisoryContentType: 'Nội dung hướng dẫn',
advisoryTitle: 'Nhan đề hướng dẫn',
anchor: {
toolbar: 'Chèn/Sửa điểm neo',
menu: 'Thuộc tính điểm neo',
title: 'Thuộc tính điểm neo',
name: 'Tên của điểm neo',
errorName: 'Hãy nhập vào tên của điểm neo',
remove: 'Xóa neo'
},
anchorId: 'Theo định danh thành phần',
anchorName: 'Theo tên điểm neo',
charset: 'Bảng mã của tài nguyên được liên kết đến',
cssClasses: 'Lớp Stylesheet',
emailAddress: 'Thư điện tử',
emailBody: 'Nội dung thông điệp',
emailSubject: 'Tiêu đề thông điệp',
id: 'Định danh',
info: 'Thông tin liên kết',
langCode: 'Mã ngôn ngữ',
langDir: 'Hướng ngôn ngữ',
langDirLTR: 'Trái sang phải (LTR)',
langDirRTL: 'Phải sang trái (RTL)',
menu: 'Sửa liên kết',
name: 'Tên',
noAnchors: '(Không có điểm neo nào trong tài liệu)',
noEmail: 'Hãy đưa vào địa chỉ thư điện tử',
noUrl: 'Hãy đưa vào đường dẫn liên kết (URL)',
other: '<khác>',
popupDependent: 'Phụ thuộc (Netscape)',
popupFeatures: 'Đặc điểm của cửa sổ Popup',
popupFullScreen: 'Toàn màn hình (IE)',
popupLeft: 'Vị trí bên trái',
popupLocationBar: 'Thanh vị trí',
popupMenuBar: 'Thanh Menu',
popupResizable: 'Có thể thay đổi kích cỡ',
popupScrollBars: 'Thanh cuộn',
popupStatusBar: 'Thanh trạng thái',
popupToolbar: 'Thanh công cụ',
popupTop: 'Vị trí phía trên',
rel: 'Quan hệ',
selectAnchor: 'Chọn một điểm neo',
styles: 'Kiểu (style)', | targetFrame: '<khung>',
targetFrameName: 'Tên khung đích',
targetPopup: '<cửa sổ popup>',
targetPopupName: 'Tên cửa sổ Popup',
title: 'Liên kết',
toAnchor: 'Neo trong trang này',
toEmail: 'Thư điện tử',
toUrl: 'URL',
toolbar: 'Chèn/Sửa liên kết',
type: 'Kiểu liên kết',
unlink: 'Xoá liên kết',
upload: 'Tải lên'
} ); | tabIndex: 'Chỉ số của Tab',
target: 'Đích', | random_line_split |
shipping_container.py | # -*- coding: utf-8 -*-
# © 2016 Comunitea - Kiko Sanchez <kiko@comunitea.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.
from odoo import api, fields, models, _
import odoo.addons.decimal_precision as dp
class ShippingContainerType(models.Model):
_ |
class ShippingContainer(models.Model):
_name = "shipping.container"
@api.one
def _get_moves(self):
self.move_ids_count = len(self.move_ids)
@api.one
def _get_partners(self):
self.partner_ids = self.picking_ids.partner_id
@api.multi
def _available_volume(self):
for container in self:
volume = container.shipping_container_type_id.volume
weight = 0.00
for move in container.move_ids:
volume -= move.product_id.volume * move.product_uom_qty
weight += move.product_id.weight * move.product_uom_qty
container.available_volume = volume
container.weight = weight
name = fields.Char("Container Ref.", required=True)
date_expected = fields.Date("Date expected", required=True)
date_shipment = fields.Date("Shipment date")
picking_ids = fields.One2many("stock.picking", "shipping_container_id", "Pickings")
company_id = fields. \
Many2one("res.company", "Company", required=True,
default=lambda self:
self.env['res.company']._company_default_get('shipping.container'))
harbor_id = fields.Many2one('res.harbor', string="Harbor", required=True)
move_ids = fields.One2many('stock.move', 'shipping_container_id', string="Moves")
move_ids_count = fields.Integer('Move ids count', compute="_get_moves")
harbor_dest_id = fields.Many2one('res.harbor', string="Dest. harbor")
state = fields.Selection([('loading', 'Loading'),
('transit', 'Transit'),
('destination', 'Destination')],
default='loading')
shipping_container_type_id = fields.Many2one('shipping.container.type', 'Type')
available_volume = fields.Float("Available volume (m3)", compute="_available_volume")
weight = fields.Float("Weight (kgr.)", compute="_available_volume")
incoterm_id = fields.Many2one('stock.incoterms', string='Incoterm')
_sql_constraints = [
('name_uniq', 'unique(name)', 'Container name must be unique')
]
@api.multi
def action_view_move_ids(self):
action = self.env.ref(
'shipping_container.container_picking_tree_action').read()[0]
action['domain'] = [('id', 'in', self.move_ids.ids)]
return action
def set_transit(self):
self.state = 'transit'
def set_destination(self):
self.state = 'destination'
def set_loading(self):
self.state = 'loading'
@api.multi
def write(self, vals):
if vals.get('date_expected', False):
for container in self:
if vals['date_expected'] != container.date_expected:
for pick in container.picking_ids:
pick.min_date = vals['date_expected']
return super(ShippingContainer, self).write(vals)
| name = "shipping.container.type"
name = fields.Char("Container type", required=True)
volume = fields.Float("Volumen", help="Container volume (m3)", required=True)
length = fields.Float("Length", help="Length(m)")
height = fields.Float("Height", help="Height(m)")
width = fields.Float("Width", help="Width(m)")
@api.onchange('length', 'height', 'width')
def onchange_dimensions(self):
if self.length and self.height and self.width:
self.volume = self.length * self.height * self.width
| identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.