prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>init_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This script can generate automate scripts for open source python project.
Scroll to ``if __name__ == "__main__":`` for more info.
"""
from __future__ import print_function
import sys
import datetime
from os import walk, mkdir
from os.path import join, abspath, dirname, basename
def write(s, path, encoding="utf-8"):
"""Write string to text file.
"""
with open(path, "wb") as f:
f.write(s.encode(encoding))
def read(path, encoding="utf-8"):
"""Read string from text file.
"""
with open(path, "rb") as f:
return f.read().decode(encoding)
def initiate_project(
package_name,
repo_name,
python_version,
github_username,
author_name,
author_email,
maintainer_name,
maintainer_email,
year,
s3_bucket,
):
"""
Generate project start files.
"""
print("Initate '%s-project' from template ..." % package_name)
template_dir = join(dirname(abspath(__file__)), "template")
output_dir = join(dirname(abspath(__file__)), "%s-project" % package_name)
for src_dir, dir_list, file_list in walk(template_dir):
# destination directory
dst_dir = src_dir.replace(template_dir, output_dir, 1)
if basename(dst_dir) == "__package__":
dst_dir = join(dirname(dst_dir), package_name)
# make destination directory
try:
print(" Create '%s' ..." % dst_dir)
mkdir(dst_dir)
except:
pass
# files
for filename in file_list:
src = join(src_dir, filename)
dst = join(dst_dir, filename)
content = read(src).\
replace("{{ package_name }}", package_name).\
replace("{{ repo_name }}", repo_name).\
replace("{{ python_version }}", python_version).\
replace("{{ github_username }}", github_username).\
replace("{{ author_name }}", author_name).\
replace("{{ author_email }}", author_email).\
replace("{{ maintainer_name }}", maintainer_name).\
replace("{{ maintainer_email }}", maintainer_email).\
replace("{{ year }}", year).\
replace("{{ s3_bucket }}", s3_bucket)
print(" Create '%s' ..." % dst)
write(content, dst)
print(" Complete!")
if __name__ == "__main__":
# --- EDIT THESE VARIABLE based on your own situation ---
package_name = "picage" # IMPORTANT
repo_name = "{package_name}-project".format(package_name=package_name)
python_version = "python%s%s" % (
sys.version_info.major, sys.version_info.minor)
github_username = "MacHu-GWU" # IMPORTANT<|fim▁hole|> author_email = "[email protected]" # IMPORTANT
maintainer_name = author_name
maintainer_email = author_email
year = str(datetime.datetime.utcnow().year)
s3_bucket = "www.wbh-doc.com" # IMPORTANT
initiate_project(
package_name,
repo_name,
python_version,
github_username,
author_name,
author_email,
maintainer_name,
maintainer_email,
year,
s3_bucket,
)<|fim▁end|> | author_name = "Sanhe Hu" # IMPORTANT |
<|file_name|>sub_photo_instance_model.js<|end_file_name|><|fim▁begin|>App.SubPhotoInstance = DS.Model.extend({<|fim▁hole|> height: DS.attr('number'),
url: DS.attr('string'),
type: 'sub_photo_instance'
});<|fim▁end|> | width: DS.attr('number'), |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>extern crate tcod;
extern crate rand;
use std::cmp;
use tcod::console::*;
use tcod::colors::{self, Color};
use rand::Rng;
// Actual size of the window
const SCREEN_WIDTH: i32 = 80;
const SCREEN_HEIGHT: i32 = 50;
// Size of the map in the window
const MAP_WIDTH: i32 = 80;
const MAP_HEIGHT: i32 = 45;
// Parameters for the autodungeon generator
const ROOM_MAX_SIZE: i32 = 10;
const ROOM_MIN_SIZE: i32 = 6;
const MAX_ROOMS: i32 = 30;
const LIMIT_FPS: i32 = 20;
const COLOR_DARK_WALL: Color = Color { r: 0, g: 0, b: 100};
const COLOR_DARK_GROUND: Color = Color {r: 50, g:50, b: 150};
type Map = Vec<Vec<Tile>>;
#[derive(Clone, Copy, Debug)]
struct Tile {
blocked: bool,
block_sight: bool,
}
impl Tile {
pub fn empty() -> Self {
Tile {blocked: false, block_sight: false}
}
pub fn wall() -> Self {
Tile {blocked: true, block_sight: true}
}
}
#[derive(Clone, Copy, Debug)]
struct Rect {
x1: i32,
y1: i32,
x2: i32,
y2: i32,
}
impl Rect {
pub fn new(x: i32, y:i32, w: i32, h: i32) -> Self {
Rect { x1: x, y1: y, x2: x + w, y2: y + h }
}
pub fn center(&self) -> (i32, i32) {
let center_x=(self.x1 + self.x2) / 2;
let center_y=(self.y1 + self.y2) / 2;
(center_x, center_y)
}
pub fn intersects_with(&self, other: &Rect) -> bool {
(self.x1 <= other.x2) && (self.x2 >= other.x1) &&
(self.y1 <= other.y2) && (self.y2 >= other.y1)
}
}
#[derive(Debug)]
struct Object {
x: i32,
y: i32,
char: char,
color: Color,
}
impl Object {
pub fn new (x: i32, y: i32, char: char, color: Color) -> Self {
Object {
x: x,
y: y,
char: char,
color: color,
}
}
pub fn move_by(&mut self, dx: i32, dy: i32, map: &Map){
if !map[(self.x + dx) as usize][(self.y + dy) as usize].blocked {
self.x += dx;
self.y += dy;
}
}
pub fn draw(&self, con: &mut Console)
{
con.set_default_foreground(self.color);
con.put_char(self.x, self.y, self.char, BackgroundFlag::None);
}
pub fn clear(&self, con: &mut Console)
{
con.put_char(self.x, self.y, ' ', BackgroundFlag::None)
}
}
fn create_room(room: Rect, map: &mut Map) {
for x in (room.x1 + 1)..room.x2 {
for y in (room.y1 + 1)..room.y2 {
map[x as usize][y as usize] = Tile::empty();
}
}
}
fn create_h_tunnel(x1: i32, x2: i32, y: i32, map: &mut Map) {
for x in cmp::min(x1, x2)..cmp::max(x1, x2) + 1 {
map[x as usize][y as usize] = Tile::empty();
}
}
fn create_v_tunnel(y1: i32, y2: i32, y: i32, map: &mut Map) {
for x in cmp::min(y1, y2)..cmp::max(y1, y2) + 1 {
map[x as usize][y as usize] = Tile::empty();
}
}
fn make_map() -> (Map, (i32, i32)) {
let mut map = vec![vec![Tile::wall(); MAP_HEIGHT as usize]; MAP_WIDTH as usize];
let mut rooms = vec![];
let mut starting_position = (0,0);
<|fim▁hole|> let w = rand::thread_rng().gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1);
let h = rand::thread_rng().gen_range(ROOM_MIN_SIZE, ROOM_MAX_SIZE + 1);
let x = rand::thread_rng().gen_range(0, MAP_WIDTH - w);
let y = rand::thread_rng().gen_range(0, MAP_HEIGHT - h);
let new_room = Rect::new(x, y, w, h);
let failed = rooms.iter().any(|other_room| new_room.intersects_with(other_room));
if !failed {
create_room(new_room, &mut map);
let (new_x, new_y) = new_room.center();
if rooms.is_empty() {
starting_position = (new_x, new_y);
} else {
let (prev_x, prev_y) = rooms[rooms.len() - 1].center();
if rand::random() {
create_h_tunnel(prev_x, new_x, prev_y, &mut map);
create_v_tunnel(prev_x, new_x, new_y, &mut map);
}
}
rooms.push(new_room);
}
}
(map, starting_position)
}
fn render_all(root: &mut Root, con: &mut Offscreen, objects: &[Object], map: &Map) {
for y in 0..MAP_HEIGHT {
for x in 0..MAP_WIDTH {
let wall = map[x as usize][y as usize].block_sight;
if wall {
con.set_char_background(x, y, COLOR_DARK_WALL, BackgroundFlag::Set);
} else {
con.set_char_background(x, y, COLOR_DARK_GROUND, BackgroundFlag::Set);
}
}
}
for object in objects {
object.draw(con);
}
blit (con, (0,0), (MAP_WIDTH, MAP_HEIGHT), root, (0,0), 1.0, 1.0);
}
fn handle_keys(root: &mut Root, player: &mut Object, map: &Map) -> bool {
use tcod::input::Key;
use tcod::input::KeyCode::*;
let key = root.wait_for_keypress(true);
match key {
Key { code: Enter, alt: true, .. } => {
let fullscreen = root.is_fullscreen();
root.set_fullscreen(!fullscreen);
}
Key { code: Escape, ..} => return true,
Key { code: Up, ..} => player.move_by(0, -1, map),
Key { code: Down, .. } => player.move_by(0, 1, map),
Key { code: Left, .. } => player.move_by(-1, 0, map),
Key { code: Right, .. } => player.move_by(1, 0, map),
_ => {},
}
false
}
fn main (){
let mut root = Root::initializer()
.font("arial10x10.png", FontLayout::Tcod)
.font_type(FontType::Greyscale)
.size(SCREEN_WIDTH, SCREEN_WIDTH)
.title("Dungeon Crawler")
.init();
tcod::system::set_fps(LIMIT_FPS);
let mut con = Offscreen::new(MAP_WIDTH, MAP_HEIGHT);
let (map, (player_x, player_y)) = make_map();
let player = Object::new(player_x, player_y, '@', colors::WHITE);
let npc = Object::new(SCREEN_WIDTH /2 -5, SCREEN_HEIGHT /2, '@', colors::YELLOW);
let mut objects = [player, npc];
while !root.window_closed() {
render_all(&mut root, &mut con, &objects, &map);
root.flush();
for object in &objects {
object.clear(&mut con)
}
let player = &mut objects[0];
let exit = handle_keys(&mut root, player, &map);
if exit {
break
}
}
}<|fim▁end|> | for _ in 0..MAX_ROOMS { |
<|file_name|>test_serial.py<|end_file_name|><|fim▁begin|>"""
Tests for serial.py.
"""
import cPickle
from cStringIO import StringIO
import gzip
import shutil
import tempfile
import unittest
from rdkit import Chem
from rdkit.Chem import AllChem
from vs_utils.utils.rdkit_utils import conformers, serial
class TestMolIO(unittest.TestCase):
"""
Base test class for molecule I/O.
"""
def setUp(self):
"""
Write SDF and SMILES molecules to temporary files.
"""
self.temp_dir = tempfile.mkdtemp()
# aspirin
self.aspirin = self._get_mol_from_smiles('CC(=O)OC1=CC=CC=C1C(=O)O',
'aspirin')
self.aspirin_h = Chem.AddHs(self.aspirin)
self.aspirin_sodium = self._get_mol_from_smiles(
'CC(=O)OC1=CC=CC=C1C(=O)[O-].[Na+]', 'aspirin sodium')
# levalbuterol (chiral)
self.levalbuterol = self._get_mol_from_smiles(
'CC(C)(C)NC[C@@H](C1=CC(=C(C=C1)O)CO)O', 'levalbuterol')
self.levalbuterol_hcl = self._get_mol_from_smiles(
'CC(C)(C)NC[C@@H](C1=CC(=C(C=C1)O)CO)O.Cl',
'levalbuterol hydrochloride')
self.ref_mols = [self.aspirin, self.levalbuterol]
self.reader = serial.MolReader(compute_2d_coords=False)
def _get_mol_from_smiles(self, smiles, name=None):
"""
Construct a molecule from a SMILES string.
Molecules loaded from SMILES strings have zero conformers, but
molecules loaded from SDF blocks are treated as 3D and have one
conformer even if coordinates are not set. This method dumps the
molecule to SDF and loads it again to obtain a molecule with one
conformer.
Parameters
----------
smiles : str
SMILES string.
name : str, optional
Molecule name.
"""
mol = Chem.MolFromSmiles(smiles)
if name is not None:
mol.SetProp('_Name', name)
AllChem.Compute2DCoords(mol) # required to preserve stereo
sdf = Chem.MolToMolBlock(mol, includeStereo=True)
mol_with_conf = Chem.MolFromMolBlock(sdf)
return mol_with_conf
def tearDown(self):
"""
Clean up temporary files.
"""
shutil.rmtree(self.temp_dir)
def test_guess_mol_format(self):
"""
Test MolIO.guess_mol_format.
"""
mol_formats = {
'pkl': ['test.pkl', 'test.pkl.gz', 'test.test.pkl',
'test.test.pkl.gz'],
'sdf': ['test.sdf', 'test.sdf.gz', 'test.test.sdf',
'test.test.sdf.gz'],
'smi': ['test.smi', 'test.smi.gz', 'test.can', 'test.can.gz',
'test.ism', 'test.ism.gz', 'test.test.smi',
'test.test.smi.gz']
}
for mol_format in mol_formats.keys():
for filename in mol_formats[mol_format]:
assert self.reader.guess_mol_format(filename) == mol_format
def test_close_context(self):
"""
Make sure MolIO closes files it opened.
"""
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
self.reader.open(filename)
self.reader.close()
assert self.reader.f.closed
# also test the context manager
with self.reader.open(filename):
pass
assert self.reader.f.closed
def test_not_close_other(self):
"""
Make sure MolIO doesn't close files it didn't open.
"""
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
with open(filename) as f:
reader = serial.MolReader(f, mol_format='sdf')
reader.close()
assert not f.closed
# also test the context manager
with open(filename) as g:
with serial.MolReader(g, mol_format='sdf'):
pass
assert not g.closed
class TestMolReader(TestMolIO):
"""
Test MolReader.
"""
def test_read_sdf(self):
"""
Read an SDF file.
"""
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
with open(filename, 'wb') as f:
f.write(Chem.MolToMolBlock(self.aspirin))
self.reader.open(filename)
mols = self.reader.get_mols()
assert mols.next().ToBinary() == self.aspirin.ToBinary()
def test_read_sdf_gz(self):
"""
Read a compressed SDF file.
"""
_, filename = tempfile.mkstemp(suffix='.sdf.gz', dir=self.temp_dir)
with gzip.open(filename, 'wb') as f:
f.write(Chem.MolToMolBlock(self.aspirin))
self.reader.open(filename)
mols = self.reader.get_mols()
assert mols.next().ToBinary() == self.aspirin.ToBinary()
def test_read_smi(self):
"""
Read a SMILES file.
"""
self.aspirin.RemoveAllConformers() # SMILES are read without confs
_, filename = tempfile.mkstemp(suffix='.smi', dir=self.temp_dir)
with open(filename, 'wb') as f:
f.write(Chem.MolToSmiles(self.aspirin))
self.reader.open(filename)
mols = self.reader.get_mols()
assert mols.next().ToBinary() == self.aspirin.ToBinary()
def test_read_smi_title(self):
"""
Read a SMILES file with molecule titles.
"""
self.aspirin.RemoveAllConformers() # SMILES are read without confs
_, filename = tempfile.mkstemp(suffix='.smi', dir=self.temp_dir)
with open(filename, 'wb') as f:
f.write('{}\t{}'.format(Chem.MolToSmiles(self.aspirin), 'aspirin'))
self.reader.open(filename)
mols = self.reader.get_mols()
mol = mols.next()
assert mol.ToBinary() == self.aspirin.ToBinary()
assert mol.GetProp('_Name') == self.aspirin.GetProp('_Name')
def test_read_smi_gz(self):
"""
Read a compressed SMILES file.
"""
self.aspirin.RemoveAllConformers() # SMILES are read without confs
_, filename = tempfile.mkstemp(suffix='.smi.gz', dir=self.temp_dir)
with gzip.open(filename, 'wb') as f:
f.write(Chem.MolToSmiles(self.aspirin))
self.reader.open(filename)
mols = self.reader.get_mols()
assert mols.next().ToBinary() == self.aspirin.ToBinary()
def test_read_pickle(self):
"""
Read from a pickle.
"""
_, filename = tempfile.mkstemp(suffix='.pkl', dir=self.temp_dir)
with open(filename, 'wb') as f:
cPickle.dump([self.aspirin], f, cPickle.HIGHEST_PROTOCOL)
self.reader.open(filename)
mols = self.reader.get_mols()
assert mols.next().ToBinary() == self.aspirin.ToBinary()
def test_read_pickle_gz(self):
"""
Read from a compressed pickle.
"""
_, filename = tempfile.mkstemp(suffix='.pkl.gz', dir=self.temp_dir)
with gzip.open(filename, 'wb') as f:
cPickle.dump([self.aspirin], f, cPickle.HIGHEST_PROTOCOL)
self.reader.open(filename)
mols = self.reader.get_mols()
assert mols.next().ToBinary() == self.aspirin.ToBinary()
def test_read_file_like(self):
"""
Read from a file-like object.
"""
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
with open(filename, 'wb') as f:
f.write(Chem.MolToMolBlock(self.aspirin))
with open(filename) as f:
reader = serial.MolReader(f, mol_format='sdf')
mols = reader.get_mols()
assert mols.next().ToBinary() == self.aspirin.ToBinary()
def test_read_compressed_file_like(self):
"""
Read from a file-like object using gzip.
"""
_, filename = tempfile.mkstemp(suffix='.sdf.gz', dir=self.temp_dir)
with gzip.open(filename, 'wb') as f:
f.write(Chem.MolToMolBlock(self.aspirin))
with gzip.open(filename) as f:
reader = serial.MolReader(f, mol_format='sdf')
mols = reader.get_mols()
assert mols.next().ToBinary() == self.aspirin.ToBinary()
def test_read_multiple_sdf(self):
"""
Read a multiple-molecule SDF file.
"""
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
with open(filename, 'wb') as f:
for mol in self.ref_mols:
sdf = Chem.MolToMolBlock(mol)
f.write(sdf)
f.write('$$$$\n') # add molecule delimiter
self.reader.open(filename)
mols = self.reader.get_mols()
mols = list(mols)
assert len(mols) == 2
for i in xrange(len(mols)):
assert mols[i].ToBinary() == self.ref_mols[i].ToBinary()
def test_read_multiple_smiles(self):
"""
Read a multiple-molecule SMILES file.
"""
ref_mols = []
for mol in self.ref_mols:
mol = Chem.MolFromSmiles(Chem.MolToSmiles(mol))
ref_mols.append(mol)
_, filename = tempfile.mkstemp(suffix='.smi', dir=self.temp_dir)
with open(filename, 'wb') as f:
for mol in self.ref_mols:
smiles = Chem.MolToSmiles(mol)
name = mol.GetProp('_Name')
f.write('{}\t{}\n'.format(smiles, name))
self.reader.open(filename)
mols = self.reader.get_mols()
mols = list(mols)
assert len(mols) == 2
for i in xrange(len(mols)):
assert mols[i].ToBinary() == ref_mols[i].ToBinary()
def test_read_multiconformer(self):
"""
Read a multiconformer SDF file.
"""
# generate conformers
engine = conformers.ConformerGenerator(max_conformers=3,
pool_multiplier=1)
ref_mol = engine.generate_conformers(self.aspirin)
assert ref_mol.GetNumConformers() > 1
# write to disk
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
with open(filename, 'wb') as f:
for conf in ref_mol.GetConformers():
f.write(Chem.MolToMolBlock(ref_mol, confId=conf.GetId()))
f.write('$$$$\n') # add molecule delimiter
# compare
self.reader.open(filename)
mols = self.reader.get_mols()
mols = list(mols)
assert len(mols) == 1
# FIXME get ToBinary test to work
# assert mols[0].ToBinary() == ref_mol.ToBinary()
assert Chem.MolToMolBlock(mols[0]) == Chem.MolToMolBlock(ref_mol)
def test_read_multiple_multiconformer(self):
"""
Read a multiconformer SDF file containing multiple molecules.
"""
# generate conformers
ref_mols = []
engine = conformers.ConformerGenerator(max_conformers=3,
pool_multiplier=1)
for mol in self.ref_mols:
expanded = engine.generate_conformers(mol)
assert expanded.GetNumConformers() > 1
ref_mols.append(expanded)
# write to disk
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
with open(filename, 'wb') as f:
for mol in ref_mols:
for conf in mol.GetConformers():
f.write(Chem.MolToMolBlock(mol, includeStereo=1,
confId=conf.GetId()))
f.write('$$$$\n') # add molecule delimiter
# compare
self.reader.open(filename)
mols = self.reader.get_mols()
mols = list(mols)
assert len(mols) == 2
for mol, ref_mol in zip(mols, ref_mols):
# FIXME get ToBinary test to work
# assert mol.ToBinary() == ref_mol.ToBinary()
assert Chem.MolToMolBlock(
mol, includeStereo=1) == Chem.MolToMolBlock(ref_mol,
includeStereo=1)
def test_are_same_molecule(self):
"""
Test MolReader.are_same_molecule.
"""
assert self.reader.are_same_molecule(self.aspirin, self.aspirin)
assert not self.reader.are_same_molecule(self.aspirin,
self.levalbuterol)
def test_no_remove_hydrogens(self):
"""
Test hydrogen retention.
"""
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
with open(filename, 'wb') as f:
f.write(Chem.MolToMolBlock(self.aspirin_h))
reader = serial.MolReader(remove_hydrogens=False, remove_salts=False)
reader.open(filename)
mols = reader.get_mols()
# FIXME get ToBinary test to work
# assert mols.next().ToBinary() == self.aspirin_h.ToBinary()
assert Chem.MolToMolBlock(mols.next()) == Chem.MolToMolBlock(
self.aspirin_h)
def test_remove_hydrogens(self):
"""
Test hydrogen removal.
"""
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
with open(filename, 'wb') as f:
f.write(Chem.MolToMolBlock(self.aspirin_h))
reader = serial.MolReader(remove_hydrogens=True)
reader.open(filename)
mols = reader.get_mols()
assert mols.next().ToBinary() == self.aspirin.ToBinary()
def test_remove_salts(self):
"""
Test salt removal.
"""
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
with open(filename, 'wb') as f:
for mol in [self.aspirin_sodium, self.levalbuterol_hcl]:
f.write(Chem.MolToMolBlock(mol))
f.write('$$$$\n') # molecule delimiter
ref_mols = [self.aspirin_sodium, self.levalbuterol_hcl]
self.reader = serial.MolReader(remove_salts=True)
self.reader.open(filename)
mols = self.reader.get_mols()<|fim▁hole|> assert len(mols) == 2
for mol, ref_mol in zip(mols, ref_mols):
assert mol.GetNumAtoms() < ref_mol.GetNumAtoms()
desalted = self.reader.clean_mol(ref_mol)
assert mol.ToBinary() == desalted.ToBinary()
def test_no_remove_salts(self):
"""
Test salt retention.
"""
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
with open(filename, 'wb') as f:
for mol in [self.aspirin_sodium, self.levalbuterol_hcl]:
f.write(Chem.MolToMolBlock(mol))
f.write('$$$$\n') # molecule delimiter
ref_mols = [self.aspirin_sodium, self.levalbuterol_hcl]
self.reader = serial.MolReader(remove_salts=False)
self.reader.open(filename)
mols = self.reader.get_mols()
mols = list(mols)
assert len(mols) == 2
self.reader = serial.MolReader(remove_salts=True)
for mol, ref_mol in zip(mols, ref_mols):
assert mol.ToBinary() == ref_mol.ToBinary()
desalted = self.reader.clean_mol(ref_mol)
assert mol.GetNumAtoms() > desalted.GetNumAtoms()
def test_iterator(self):
"""
Test MolWriter.__iter__.
"""
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
with open(filename, 'wb') as f:
for mol in self.ref_mols:
f.write(Chem.MolToMolBlock(mol))
f.write('$$$$\n') # molecule delimiter
self.reader.open(filename)
for i, mol in enumerate(self.reader):
assert mol.ToBinary() == self.ref_mols[i].ToBinary()
def test_context_manager(self):
"""
Test using 'with' statement to read molecules.
"""
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
with open(filename, 'wb') as f:
for mol in self.ref_mols:
f.write(Chem.MolToMolBlock(mol))
f.write('$$$$\n') # molecule delimiter
with self.reader.open(filename) as reader:
for i, mol in enumerate(reader):
assert mol.ToBinary() == self.ref_mols[i].ToBinary()
def test_skip_failures(self):
"""
Test skip read failures.
"""
smiles = 'CO(C)C'
reader = serial.MolReader(StringIO(smiles), 'smi')
mols = list(reader.get_mols())
assert len(mols) == 0
def test_is_a_salt(self):
"""
Test that a molecule that _is_ a salt is not returned empty.
"""
smiles = 'C(=CC(=O)O)C(=O)O'
reader = serial.MolReader(StringIO(smiles), 'smi', remove_salts=True)
mols = list(reader.get_mols())
assert len(mols) == 1 and mols[0].GetNumAtoms()
def test_read_multiple_pickles(self):
"""
Test reading a file containing multiple pickles. This can occur if
MolWriter.write is called multiple times.
"""
_, filename = tempfile.mkstemp(suffix='.pkl', dir=self.temp_dir)
with serial.MolWriter().open(filename) as writer:
writer.write([self.aspirin])
writer.write([self.levalbuterol])
with self.reader.open(filename) as reader:
mols = list(reader)
assert len(mols) == 2
assert mols[0].ToBinary() == self.aspirin.ToBinary()
assert mols[1].ToBinary() == self.levalbuterol.ToBinary()
class TestMolWriter(TestMolIO):
"""
Test MolWriter.
"""
def setUp(self):
"""
Add writer to inherited setup.
"""
super(TestMolWriter, self).setUp()
self.writer = serial.MolWriter()
self.aspirin_sdf = Chem.MolToMolBlock(self.aspirin)
self.aspirin_smiles = Chem.MolToSmiles(self.aspirin) + '\taspirin'
def test_write_sdf(self):
"""
Write an SDF file.
"""
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
self.writer.open(filename)
self.writer.write([self.aspirin])
self.writer.close()
self.reader.open(filename)
mols = self.reader.get_mols()
# compare molecules
assert mols.next().ToBinary() == self.aspirin.ToBinary()
# compare files
with open(filename) as f:
data = f.read()
assert data == self.aspirin_sdf + '$$$$\n'
def test_write_sdf_gz(self):
"""
Write a compressed SDF file.
"""
_, filename = tempfile.mkstemp(suffix='.sdf.gz', dir=self.temp_dir)
self.writer.open(filename)
self.writer.write([self.aspirin])
self.writer.close()
self.reader.open(filename)
mols = self.reader.get_mols()
# compare molecules
assert mols.next().ToBinary() == self.aspirin.ToBinary()
# compare files
with gzip.open(filename) as f:
data = f.read()
assert data == self.aspirin_sdf + '$$$$\n'
def test_write_smiles(self):
"""
Write a SMILES file.
"""
_, filename = tempfile.mkstemp(suffix='.smi', dir=self.temp_dir)
self.writer.open(filename)
self.writer.write([self.aspirin])
self.writer.close()
self.reader.open(filename)
mols = self.reader.get_mols()
# compare molecules
self.aspirin.RemoveAllConformers() # SMILES are read without confs
assert mols.next().ToBinary() == self.aspirin.ToBinary()
# compare files
with open(filename) as f:
data = f.read()
assert data.strip() == self.aspirin_smiles
def test_write_smiles_gz(self):
"""
Write a compressed SMILES file.
"""
_, filename = tempfile.mkstemp(suffix='.smi.gz', dir=self.temp_dir)
self.writer.open(filename)
self.writer.write([self.aspirin])
self.writer.close()
self.reader.open(filename)
mols = self.reader.get_mols()
# compare molecules
self.aspirin.RemoveAllConformers() # SMILES are read without confs
assert mols.next().ToBinary() == self.aspirin.ToBinary()
# compare files
with gzip.open(filename) as f:
data = f.read()
assert data.strip() == self.aspirin_smiles
def test_write_pickle(self):
"""
Write a pickle.
"""
_, filename = tempfile.mkstemp(suffix='.pkl', dir=self.temp_dir)
self.writer.open(filename)
self.writer.write([self.aspirin])
self.writer.close()
self.reader.open(filename)
mols = self.reader.get_mols()
# compare molecules
assert mols.next().ToBinary() == self.aspirin.ToBinary()
# compare files
with open(filename) as f:
data = f.read()
assert data == cPickle.dumps([self.aspirin],
cPickle.HIGHEST_PROTOCOL)
def test_write_pickle_gz(self):
"""
Write a compressed pickle.
"""
_, filename = tempfile.mkstemp(suffix='.pkl.gz', dir=self.temp_dir)
self.writer.open(filename)
self.writer.write([self.aspirin])
self.writer.close()
self.reader.open(filename)
mols = self.reader.get_mols()
# compare molecules
assert mols.next().ToBinary() == self.aspirin.ToBinary()
# compare files
with gzip.open(filename) as f:
data = f.read()
assert data == cPickle.dumps([self.aspirin],
cPickle.HIGHEST_PROTOCOL)
def test_stereo_setup(self):
"""
Make sure chiral reference molecule is correct.
"""
smiles = Chem.MolToSmiles(self.levalbuterol, isomericSmiles=True)
assert '@' in smiles # check for stereochemistry flag
# check that removing stereochemistry changes the molecule
original = self.levalbuterol.ToBinary()
AllChem.RemoveStereochemistry(self.levalbuterol)
assert self.levalbuterol.ToBinary() != original
def test_stereo_sdf(self):
"""
Test stereochemistry preservation when writing to SDF.
"""
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
writer = serial.MolWriter(stereo=True)
writer.open(filename)
writer.write([self.levalbuterol])
writer.close()
self.reader.open(filename)
mols = self.reader.get_mols()
assert mols.next().ToBinary() == self.levalbuterol.ToBinary()
def test_stereo_smi(self):
"""
Test stereochemistry preservation when writing to SMILES.
"""
# FIXME avoid this and use self.levalbuterol.RemoveAllConformers()
ref_mol = Chem.MolFromSmiles(Chem.MolToSmiles(self.levalbuterol,
isomericSmiles=True))
_, filename = tempfile.mkstemp(suffix='.smi', dir=self.temp_dir)
writer = serial.MolWriter(stereo=True)
writer.open(filename)
writer.write([self.levalbuterol])
writer.close()
self.reader.open(filename)
mols = self.reader.get_mols()
assert mols.next().ToBinary() == ref_mol.ToBinary()
def test_no_stereo_sdf(self):
"""
Test stereochemistry removal when writing to SDF.
"""
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
writer = serial.MolWriter(stereo=False)
writer.open(filename)
writer.write([self.levalbuterol])
writer.close()
self.reader.open(filename)
mols = self.reader.get_mols()
mol = mols.next()
# make sure the written molecule differs from the reference
assert mol.ToBinary() != self.levalbuterol.ToBinary()
# check again after removing stereochemistry
AllChem.RemoveStereochemistry(self.levalbuterol)
# FIXME get ToBinary test to work
# assert mol.ToBinary() == self.levalbuterol.ToBinary()
assert Chem.MolToMolBlock(
mol, includeStereo=True) == Chem.MolToMolBlock(
self.levalbuterol, includeStereo=True)
def test_no_stereo_smiles(self):
"""
Test stereochemistry removal when writing to SMILES.
"""
_, filename = tempfile.mkstemp(suffix='.smi', dir=self.temp_dir)
writer = serial.MolWriter(stereo=False)
writer.open(filename)
writer.write([self.levalbuterol])
writer.close()
self.reader.open(filename)
mols = self.reader.get_mols()
mol = mols.next()
# make sure the written molecule differs from the reference
assert mol.ToBinary() != self.levalbuterol.ToBinary()
# check again after removing stereochemistry
AllChem.RemoveStereochemistry(self.levalbuterol)
# FIXME get ToBinary test to work
# assert mol.ToBinary() == self.levalbuterol.ToBinary()
assert Chem.MolToSmiles(mol, isomericSmiles=True) == Chem.MolToSmiles(
self.levalbuterol, isomericSmiles=True)
def test_context_manager(self):
"""
Test use of 'with' statement to write molecules.
"""
_, filename = tempfile.mkstemp(suffix='.sdf', dir=self.temp_dir)
with self.writer.open(filename) as writer:
writer.write([self.aspirin])
self.reader.open(filename)
mols = self.reader.get_mols()
# compare molecules
assert mols.next().ToBinary() == self.aspirin.ToBinary()
# compare files
with open(filename) as f:
data = f.read()
assert data == self.aspirin_sdf + '$$$$\n'<|fim▁end|> | mols = list(mols) |
<|file_name|>validation.service.ts<|end_file_name|><|fim▁begin|>import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { IContainer } from '../../../../../model/IContainer';
<|fim▁hole|>import { ElementValidatorBase } from '../../../../../validation/element-validator-base';
import { RequiredFieldsValidator } from '../../../../../validation/required-fields-validator';
import { TextLengthValidator } from '../../../../../validation/text-length-validator';
import { ValidNameValidator } from '../../../../../validation/valid-name-validator';
import { ValidationResult } from '../../../../../validation/validation-result';
import { NavigatorService } from '../../../../navigation/modules/navigator/services/navigator.service';
import { ValidationCache, ValidationPair } from '../util/validation-cache';
import { ValidationErrorSeverity } from '../../../../../validation/validation-error-severity';
@Injectable()
export class ValidationService {
private validationCache: ValidationCache;
private validNameValidator: ValidNameValidator = new ValidNameValidator();
private textLengthValidator: TextLengthValidator = new TextLengthValidator();
constructor(private navigator: NavigatorService, translate: TranslateService) {
this.validationCache = new ValidationCache(translate);
navigator.hasNavigated.subscribe(() => this.validateCurrent());
}
public getValidationResults(parentElement: IContainer): ValidationPair[] {
return parentElement ? this.validationCache.getValidationResults(parentElement.url) : [];
}
private static requiredFieldValidatorMap: { [className: string]: RequiredFieldsValidator };
private static elementValidators: { [className: string]: ElementValidatorBase<IContainer>[] };
public validate(element: IContainer, contents: IContainer[] = []): ValidationPair[] {
return this.validateElement(element).concat(this.validateAll(contents));
}
public async validateCurrent(): Promise<void> {
const element = this.navigator.currentElement;
const contents = await this.navigator.currentContents;
this.refreshValidation(element, contents);
}
private validateElement(element: IContainer): ValidationPair[] {
if (element === undefined) {
return [];
}
return this.validationCache.getValidationResults(element.url);
}
private validateAll(elements: IContainer[]): ValidationPair[] {
return elements
.map((element: IContainer) => this.validateElement(element))
.reduce((a: ValidationPair[], b: ValidationPair[]) => a.concat(b), []);
}
public async refreshValidation(element: IContainer, contents: IContainer[] = [], clear = true): Promise<void> {
if (clear) {
this.validationCache.clear();
}
const requiredFieldsResults: ValidationResult = this.getRequiredFieldsValidator(element).validate(element);
const validNameResult: ValidationResult = this.validNameValidator.validate(element);
const textLengthValidationResult: ValidationResult = this.textLengthValidator.validate(element);
const elementValidators = this.getElementValidators(element) || [];
let elementResults: ValidationResult[] =
elementValidators.map((validator: ElementValidatorBase<IContainer>) => validator.validate(element, contents))
.concat(requiredFieldsResults)
.concat(validNameResult)
.concat(textLengthValidationResult);
this.validationCache.addValidationResultsToCache(elementResults);
}
public get currentSeverities(): ValidationErrorSeverity[] {
return this.validate(this.navigator.currentElement, this.navigator.currentContents)
.map(validationResult => validationResult.severity);
}
public isValid(element: IContainer): boolean {
const isValid = this.validationCache.isValid(element.url);
return isValid;
}
public get currentValid(): boolean {
return this.isValid(this.navigator.currentElement);
}
public allValid(contents: IContainer[]): boolean {
if (!contents) {
return true;
}
return contents.every((element: IContainer) => this.isValid(element));
}
private getRequiredFieldsValidator(element: IContainer): RequiredFieldsValidator {
if (!ValidationService.requiredFieldValidatorMap) {
ValidationService.requiredFieldValidatorMap = {};
}
let type: string = element.className;
if (!ValidationService.requiredFieldValidatorMap[type]) {
let fieldMetaInfo: FieldMetaItem[] = MetaInfo[type];
let requiredFields: string[] = [];
fieldMetaInfo.forEach((metaItem: FieldMetaItem) => {
if (metaItem.required) {
requiredFields.push(metaItem.name);
}
});
ValidationService.requiredFieldValidatorMap[type] = new RequiredFieldsValidator(requiredFields);
}
return ValidationService.requiredFieldValidatorMap[type];
}
private getElementValidators(element: IContainer): ElementValidatorBase<IContainer>[] {
return ValidationService.elementValidators[element.className];
}
public static registerElementValidator<TV extends Function & (typeof ElementValidatorBase), TE extends { className: string }>(
elementType: TE, validatorType: TV): void {
if (ValidationService.elementValidators === undefined) {
ValidationService.elementValidators = {};
}
const className: string = elementType.className;
if (ValidationService.elementValidators[className] === undefined) {
ValidationService.elementValidators[className] = [];
}
const validatorInstance: ElementValidatorBase<IContainer> = new (validatorType)();
ValidationService.elementValidators[className].push(validatorInstance);
}
}<|fim▁end|> | import { FieldMetaItem, MetaInfo } from '../../../../../model/meta/field-meta';
|
<|file_name|>WorldSocket.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2005-2014 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <ace/Message_Block.h>
#include <ace/OS_NS_string.h>
#include <ace/OS_NS_unistd.h>
#include <ace/os_include/arpa/os_inet.h>
#include <ace/os_include/netinet/os_tcp.h>
#include <ace/os_include/sys/os_types.h>
#include <ace/os_include/sys/os_socket.h>
#include <ace/OS_NS_string.h>
#include <ace/Reactor.h>
#include <ace/Auto_Ptr.h>
#include "WorldSocket.h"
#include "Common.h"
#include "Player.h"
#include "Util.h"
#include "World.h"
#include "WorldPacket.h"
#include "SharedDefines.h"
#include "ByteBuffer.h"
#include "Opcodes.h"
#include "DatabaseEnv.h"
#include "BigNumber.h"
#include "SHA1.h"
#include "WorldSession.h"
#include "WorldSocketMgr.h"
#include "Log.h"
#include "PacketLog.h"
#include "ScriptMgr.h"
#include "AccountMgr.h"
#if defined(__GNUC__)
#pragma pack(1)
#else
#pragma pack(push, 1)
#endif
struct ServerPktHeader
{
ServerPktHeader(uint32 size, uint32 cmd, AuthCrypt* _authCrypt) : size(size)
{
if (_authCrypt->IsInitialized())
{
uint32 data = (size << 13) | cmd & MAX_OPCODE;
memcpy(&header[0], &data, 4);
_authCrypt->EncryptSend((uint8*)&header[0], getHeaderLength());
}
else
{
// Dynamic header size is not needed anymore, we are using not encrypted part for only the first few packets
memcpy(&header[0], &size, 2);
memcpy(&header[2], &cmd, 2);
}
}
uint8 getHeaderLength()
{
return 4;
}
const uint32 size;
uint8 header[4];
};
struct AuthClientPktHeader
{
uint16 size;
uint32 cmd;
};
struct WorldClientPktHeader
{
uint16 size;
uint16 cmd;
};
#if defined(__GNUC__)
#pragma pack()
#else
#pragma pack(pop)
#endif
WorldSocket::WorldSocket (void): WorldHandler(),
m_LastPingTime(ACE_Time_Value::zero), m_OverSpeedPings(0), m_Session(0),
m_RecvWPct(0), m_RecvPct(), m_Header(sizeof(AuthClientPktHeader)),
m_WorldHeader(sizeof(WorldClientPktHeader)), m_OutBuffer(0),
m_OutBufferSize(65536), m_OutActive(false),
m_Seed(static_cast<uint32> (rand32()))
{
reference_counting_policy().value (ACE_Event_Handler::Reference_Counting_Policy::ENABLED);
msg_queue()->high_water_mark(8 * 1024 * 1024);
msg_queue()->low_water_mark(8 * 1024 * 1024);
}
WorldSocket::~WorldSocket (void)
{
delete m_RecvWPct;
if (m_OutBuffer)
m_OutBuffer->release();
closing_ = true;
peer().close();
}
bool WorldSocket::IsClosed (void) const
{
return closing_;
}
void WorldSocket::CloseSocket (void)
{
{
ACE_GUARD (LockType, Guard, m_OutBufferLock);
if (closing_)
return;
closing_ = true;
peer().close_writer();
}
{
ACE_GUARD (LockType, Guard, m_SessionLock);
m_Session = NULL;
}
}
const std::string& WorldSocket::GetRemoteAddress (void) const
{
return m_Address;
}
int WorldSocket::SendPacket(WorldPacket const& pct)
{
ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1);
if (closing_)
return -1;
// Dump outgoing packet
if (sPacketLog->CanLogPacket())
sPacketLog->LogPacket(pct, SERVER_TO_CLIENT);
WorldPacket const* pkt = &pct;
// Empty buffer used in case packet should be compressed
// Disable compression for now :)
/* WorldPacket buff;
if (m_Session && pkt->size() > 0x400)
{
buff.Compress(m_Session->GetCompressionStream(), pkt);
pkt = &buff;
}*/
uint16 opcodeNumber = serveurOpcodeTable[pkt->GetOpcode()]->OpcodeNumber;
if (m_Session)
TC_LOG_TRACE("network.opcode", "S->C: %s %s", m_Session->GetPlayerInfo().c_str(), GetOpcodeNameForLogging(pkt->GetOpcode(), true).c_str());
sScriptMgr->OnPacketSend(this, *pkt);
ServerPktHeader header(!m_Crypt.IsInitialized() ? pkt->size() + 2 : pct.size(), opcodeNumber, &m_Crypt);
if (m_OutBuffer->space() >= pkt->size() + header.getHeaderLength() && msg_queue()->is_empty())
{
// Put the packet on the buffer.
if (m_OutBuffer->copy((char*) header.header, header.getHeaderLength()) == -1)
ACE_ASSERT (false);
if (!pkt->empty())
if (m_OutBuffer->copy((char*) pkt->contents(), pkt->size()) == -1)
ACE_ASSERT (false);
}
else
{
// Enqueue the packet.
ACE_Message_Block* mb;
ACE_NEW_RETURN(mb, ACE_Message_Block(pkt->size() + header.getHeaderLength()), -1);
mb->copy((char*) header.header, header.getHeaderLength());
if (!pkt->empty())
mb->copy((const char*)pkt->contents(), pkt->size());
if (msg_queue()->enqueue_tail(mb, (ACE_Time_Value*)&ACE_Time_Value::zero) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::SendPacket enqueue_tail failed");
mb->release();
return -1;
}
}
return 0;
}
long WorldSocket::AddReference (void)
{
return static_cast<long> (add_reference());
}
long WorldSocket::RemoveReference (void)
{
return static_cast<long> (remove_reference());
}
int WorldSocket::open (void *a)
{
ACE_UNUSED_ARG (a);
// Prevent double call to this func.
if (m_OutBuffer)
return -1;
// This will also prevent the socket from being Updated
// while we are initializing it.
m_OutActive = true;
// Hook for the manager.
if (sWorldSocketMgr->OnSocketOpen(this) == -1)
return -1;
// Allocate the buffer.
ACE_NEW_RETURN (m_OutBuffer, ACE_Message_Block (m_OutBufferSize), -1);
// Store peer address.
ACE_INET_Addr remote_addr;
if (peer().get_remote_addr(remote_addr) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::open: peer().get_remote_addr errno = %s", ACE_OS::strerror (errno));
return -1;
}
m_Address = remote_addr.get_host_addr();
// not an opcode. this packet sends raw string WORLD OF WARCRAFT CONNECTION - SERVER TO CLIENT"
// because of our implementation, bytes "WO" become the opcode
WorldPacket packet(MSG_VERIFY_CONNECTIVITY);
packet << std::string("RLD OF WARCRAFT CONNECTION - SERVER TO CLIENT");
if (SendPacket(packet) == -1)
return -1;
// Register with ACE Reactor
if (reactor()->register_handler(this, ACE_Event_Handler::READ_MASK | ACE_Event_Handler::WRITE_MASK) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::open: unable to register client handler errno = %s", ACE_OS::strerror (errno));
return -1;
}
// reactor takes care of the socket from now on
remove_reference();
return 0;
}
int WorldSocket::close (u_long)
{
shutdown();
closing_ = true;
remove_reference();
return 0;
}
int WorldSocket::handle_input (ACE_HANDLE)
{
if (closing_)
return -1;
switch (handle_input_missing_data())
{
case -1 :
{
if ((errno == EWOULDBLOCK) ||
(errno == EAGAIN))
{
return Update(); // interesting line, isn't it ?
}
TC_LOG_DEBUG("network", "WorldSocket::handle_input: Peer error closing connection errno = %s", ACE_OS::strerror (errno));
errno = ECONNRESET;
return -1;
}
case 0:
{
TC_LOG_DEBUG("network", "WorldSocket::handle_input: Peer has closed connection");
errno = ECONNRESET;
return -1;
}
case 1:
return 1;
default:
return Update(); // another interesting line ;)
}
ACE_NOTREACHED(return -1);
}
int WorldSocket::handle_output (ACE_HANDLE)
{
ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1);
if (closing_)
return -1;
size_t send_len = m_OutBuffer->length();
if (send_len == 0)
return handle_output_queue(Guard);
#ifdef MSG_NOSIGNAL
ssize_t n = peer().send (m_OutBuffer->rd_ptr(), send_len, MSG_NOSIGNAL);
#else
ssize_t n = peer().send (m_OutBuffer->rd_ptr(), send_len);
#endif // MSG_NOSIGNAL
if (n == 0)
return -1;
else if (n == -1)
{
if (errno == EWOULDBLOCK || errno == EAGAIN)
return schedule_wakeup_output (Guard);
return -1;
}
else if (n < (ssize_t)send_len) //now n > 0
{
m_OutBuffer->rd_ptr (static_cast<size_t> (n));
// move the data to the base of the buffer
m_OutBuffer->crunch();
return schedule_wakeup_output (Guard);
}
else //now n == send_len
{
m_OutBuffer->reset();
return handle_output_queue (Guard);
}
ACE_NOTREACHED (return 0);
}
int WorldSocket::handle_output_queue (GuardType& g)
{
if (msg_queue()->is_empty())
return cancel_wakeup_output(g);
ACE_Message_Block* mblk;
if (msg_queue()->dequeue_head(mblk, (ACE_Time_Value*)&ACE_Time_Value::zero) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::handle_output_queue dequeue_head");
return -1;
}
const size_t send_len = mblk->length();
#ifdef MSG_NOSIGNAL
ssize_t n = peer().send(mblk->rd_ptr(), send_len, MSG_NOSIGNAL);
#else
ssize_t n = peer().send(mblk->rd_ptr(), send_len);
#endif // MSG_NOSIGNAL
if (n == 0)
{
mblk->release();
return -1;
}
else if (n == -1)
{
if (errno == EWOULDBLOCK || errno == EAGAIN)
{
msg_queue()->enqueue_head(mblk, (ACE_Time_Value*) &ACE_Time_Value::zero);
return schedule_wakeup_output (g);
}
mblk->release();
return -1;
}
else if (n < (ssize_t)send_len) //now n > 0
{
mblk->rd_ptr(static_cast<size_t> (n));
if (msg_queue()->enqueue_head(mblk, (ACE_Time_Value*) &ACE_Time_Value::zero) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::handle_output_queue enqueue_head");
mblk->release();
return -1;
}
return schedule_wakeup_output (g);
}
else //now n == send_len
{
mblk->release();
return msg_queue()->is_empty() ? cancel_wakeup_output(g) : ACE_Event_Handler::WRITE_MASK;
}
ACE_NOTREACHED(return -1);
}
int WorldSocket::handle_close (ACE_HANDLE h, ACE_Reactor_Mask)
{
// Critical section
{
ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1);
closing_ = true;
if (h == ACE_INVALID_HANDLE)
peer().close_writer();
}
// Critical section
{
ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1);
m_Session = NULL;
}
reactor()->remove_handler(this, ACE_Event_Handler::DONT_CALL | ACE_Event_Handler::ALL_EVENTS_MASK);
return 0;
}
int WorldSocket::Update (void)
{
if (closing_)
return -1;
if (m_OutActive)
return 0;
{
ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, 0);
if (m_OutBuffer->length() == 0 && msg_queue()->is_empty())
return 0;
}
int ret;
do
ret = handle_output(get_handle());
while (ret > 0);
return ret;
}
int WorldSocket::handle_input_header (void)
{
ACE_ASSERT(m_RecvWPct == NULL);
if (m_Crypt.IsInitialized())
{
ACE_ASSERT(m_WorldHeader.length() == sizeof(WorldClientPktHeader));
uint8* uintHeader = (uint8*)m_WorldHeader.rd_ptr();
m_Crypt.DecryptRecv(uintHeader, sizeof(WorldClientPktHeader));
WorldClientPktHeader& header = *(WorldClientPktHeader*)uintHeader;
uint32 value = *(uint32*)uintHeader;
header.cmd = value & 0x1FFF;
header.size = ((value & ~(uint32)0x1FFF) >> 13);
if (header.size > 10236)
{
Player* _player = m_Session ? m_Session->GetPlayer() : NULL;
TC_LOG_ERROR("network", "WorldSocket::handle_input_header(): client (account: %u, char [GUID: %u, name: %s]) sent malformed packet (size: %d, cmd: %d)",
m_Session ? m_Session->GetAccountId() : 0,
_player ? _player->GetGUIDLow() : 0,
_player ? _player->GetName().c_str() : "<none>",
header.size, header.cmd);
errno = EINVAL;
return -1;
}
uint16 opcodeNumber = PacketFilter::DropHighBytes(header.cmd);
ACE_NEW_RETURN(m_RecvWPct, WorldPacket(clientOpcodeTable.GetOpcodeByNumber(opcodeNumber), header.size), -1);
m_RecvWPct->SetReceivedOpcode(opcodeNumber);
if (header.size > 0)
{
m_RecvWPct->resize(header.size);
m_RecvPct.base ((char*) m_RecvWPct->contents(), m_RecvWPct->size());
}
else
ACE_ASSERT(m_RecvPct.space() == 0);
}
else
{
ACE_ASSERT(m_Header.length() == sizeof(AuthClientPktHeader));
uint8* uintHeader = (uint8*)m_Header.rd_ptr();
AuthClientPktHeader& header = *((AuthClientPktHeader*)uintHeader);
if ((header.size < 4) || (header.size > 10240))
{
Player* _player = m_Session ? m_Session->GetPlayer() : NULL;
TC_LOG_ERROR("network", "WorldSocket::handle_input_header(): client (account: %u, char [GUID: %u, name: %s]) sent malformed packet (size: %d, cmd: %d)",
m_Session ? m_Session->GetAccountId() : 0,
_player ? _player->GetGUIDLow() : 0,
_player ? _player->GetName().c_str() : "<none>",
header.size, header.cmd);
errno = EINVAL;
return -1;
}
header.size -= 4;
uint16 opcodeNumber = PacketFilter::DropHighBytes(header.cmd);
ACE_NEW_RETURN(m_RecvWPct, WorldPacket(clientOpcodeTable.GetOpcodeByNumber(opcodeNumber), header.size), -1);
m_RecvWPct->SetReceivedOpcode(opcodeNumber);
if (header.size > 0)
{
m_RecvWPct->resize(header.size);
m_RecvPct.base ((char*) m_RecvWPct->contents(), m_RecvWPct->size());
}
else
ACE_ASSERT(m_RecvPct.space() == 0);
}
return 0;
}
int WorldSocket::handle_input_payload (void)
{
// set errno properly here on error !!!
// now have a header and payload
if (m_Crypt.IsInitialized())
{
ACE_ASSERT (m_RecvPct.space() == 0);
ACE_ASSERT (m_WorldHeader.space() == 0);
ACE_ASSERT (m_RecvWPct != NULL);
const int ret = ProcessIncoming (m_RecvWPct);
m_RecvPct.base (NULL, 0);
m_RecvPct.reset();
m_RecvWPct = NULL;
m_WorldHeader.reset();
if (ret == -1)
errno = EINVAL;
return ret;
}
else
{
ACE_ASSERT(m_RecvPct.space() == 0);
ACE_ASSERT(m_Header.space() == 0);
ACE_ASSERT(m_RecvWPct != NULL);
const int ret = ProcessIncoming(m_RecvWPct);
m_RecvPct.base(NULL, 0);
m_RecvPct.reset();
m_RecvWPct = NULL;
m_Header.reset();
if (ret == -1)
errno = EINVAL;
return ret;
}
}
int WorldSocket::handle_input_missing_data (void)
{
char buf [4096];
<|fim▁hole|> 0,
0,
ACE_Message_Block::DONT_DELETE,
0);
ACE_Message_Block message_block(&db,
ACE_Message_Block::DONT_DELETE,
0);
const size_t recv_size = message_block.space();
const ssize_t n = peer().recv (message_block.wr_ptr(),
recv_size);
if (n <= 0)
return int(n);
message_block.wr_ptr (n);
while (message_block.length() > 0)
{
if (m_Crypt.IsInitialized())
{
if (m_WorldHeader.space() > 0)
{
//need to receive the header
const size_t to_header = (message_block.length() > m_WorldHeader.space() ? m_WorldHeader.space() : message_block.length());
m_WorldHeader.copy (message_block.rd_ptr(), to_header);
message_block.rd_ptr (to_header);
if (m_WorldHeader.space() > 0)
{
// Couldn't receive the whole header this time.
ACE_ASSERT (message_block.length() == 0);
errno = EWOULDBLOCK;
return -1;
}
// We just received nice new header
if (handle_input_header() == -1)
{
ACE_ASSERT ((errno != EWOULDBLOCK) && (errno != EAGAIN));
return -1;
}
}
}
else
{
if (m_Header.space() > 0)
{
//need to receive the header
const size_t to_header = (message_block.length() > m_Header.space() ? m_Header.space() : message_block.length());
m_Header.copy (message_block.rd_ptr(), to_header);
message_block.rd_ptr (to_header);
if (m_Header.space() > 0)
{
// Couldn't receive the whole header this time.
ACE_ASSERT (message_block.length() == 0);
errno = EWOULDBLOCK;
return -1;
}
// We just received nice new header
if (handle_input_header() == -1)
{
ACE_ASSERT ((errno != EWOULDBLOCK) && (errno != EAGAIN));
return -1;
}
}
}
// Its possible on some error situations that this happens
// for example on closing when epoll receives more chunked data and stuff
// hope this is not hack, as proper m_RecvWPct is asserted around
if (!m_RecvWPct)
{
TC_LOG_ERROR("network", "Forcing close on input m_RecvWPct = NULL");
errno = EINVAL;
return -1;
}
// We have full read header, now check the data payload
if (m_RecvPct.space() > 0)
{
//need more data in the payload
const size_t to_data = (message_block.length() > m_RecvPct.space() ? m_RecvPct.space() : message_block.length());
m_RecvPct.copy (message_block.rd_ptr(), to_data);
message_block.rd_ptr (to_data);
if (m_RecvPct.space() > 0)
{
// Couldn't receive the whole data this time.
ACE_ASSERT (message_block.length() == 0);
errno = EWOULDBLOCK;
return -1;
}
}
//just received fresh new payload
if (handle_input_payload() == -1)
{
ACE_ASSERT ((errno != EWOULDBLOCK) && (errno != EAGAIN));
return -1;
}
}
return size_t(n) == recv_size ? 1 : 2;
}
int WorldSocket::cancel_wakeup_output (GuardType& g)
{
if (!m_OutActive)
return 0;
m_OutActive = false;
g.release();
if (reactor()->cancel_wakeup
(this, ACE_Event_Handler::WRITE_MASK) == -1)
{
// would be good to store errno from reactor with errno guard
TC_LOG_ERROR("network", "WorldSocket::cancel_wakeup_output");
return -1;
}
return 0;
}
int WorldSocket::schedule_wakeup_output (GuardType& g)
{
if (m_OutActive)
return 0;
m_OutActive = true;
g.release();
if (reactor()->schedule_wakeup
(this, ACE_Event_Handler::WRITE_MASK) == -1)
{
TC_LOG_ERROR("network", "WorldSocket::schedule_wakeup_output");
return -1;
}
return 0;
}
int WorldSocket::ProcessIncoming(WorldPacket* new_pct)
{
ACE_ASSERT (new_pct);
// manage memory ;)
ACE_Auto_Ptr<WorldPacket> aptr(new_pct);
Opcodes opcode = new_pct->GetOpcode();
if (closing_)
return -1;
// Dump received packet.
if (sPacketLog->CanLogPacket())
sPacketLog->LogPacket(*new_pct, CLIENT_TO_SERVER);
std::string opcodeName = GetOpcodeNameForLogging(opcode, false);
if (m_Session)
TC_LOG_TRACE("network.opcode", "C->S: %s %s", m_Session->GetPlayerInfo().c_str(), opcodeName.c_str());
try
{
switch (opcode)
{
case CMSG_PING:
return HandlePing(*new_pct);
case CMSG_AUTH_SESSION:
if (m_Session)
{
TC_LOG_ERROR("network", "WorldSocket::ProcessIncoming: received duplicate CMSG_AUTH_SESSION from %s", m_Session->GetPlayerInfo().c_str());
return -1;
}
sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct));
return HandleAuthSession(*new_pct);
//case CMSG_KEEP_ALIVE:
// sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct));
// return 0;
case CMSG_LOG_DISCONNECT:
new_pct->rfinish(); // contains uint32 disconnectReason;
sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct));
return 0;
// not an opcode, client sends string "WORLD OF WARCRAFT CONNECTION - CLIENT TO SERVER" without opcode
// first 4 bytes become the opcode (2 dropped)
case MSG_VERIFY_CONNECTIVITY:
{
sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct));
std::string str;
*new_pct >> str;
if (str != "D OF WARCRAFT CONNECTION - CLIENT TO SERVER")
return -1;
return HandleSendAuthSession();
}
/*case CMSG_ENABLE_NAGLE:
{
TC_LOG_DEBUG("network", "%s", opcodeName.c_str());
sScriptMgr->OnPacketReceive(this, WorldPacket(*new_pct));
return m_Session ? m_Session->HandleEnableNagleAlgorithm() : -1;
}*/
default:
{
ACE_GUARD_RETURN(LockType, Guard, m_SessionLock, -1);
if (!m_Session)
{
TC_LOG_ERROR("network.opcode", "ProcessIncoming: Client not authed opcode = %u", uint32(opcode));
return -1;
}
// prevent invalid memory access/crash with custom opcodes
if (opcode >= NUM_OPCODES)
return 0;
OpcodeHandler const* handler = clientOpcodeTable[opcode];
if (!handler || handler->Status == STATUS_UNHANDLED)
{
TC_LOG_ERROR("network.opcode", "No defined handler for opcode %s sent by %s", GetOpcodeNameForLogging(new_pct->GetOpcode(), false, new_pct->GetReceivedOpcode()).c_str(), m_Session->GetPlayerInfo().c_str());
return 0;
}
// Our Idle timer will reset on any non PING opcodes.
// Catches people idling on the login screen and any lingering ingame connections.
m_Session->ResetTimeOutTime();
// OK, give the packet to WorldSession
aptr.release();
// WARNING here we call it with locks held.
// Its possible to cause deadlock if QueuePacket calls back
m_Session->QueuePacket(new_pct);
return 0;
}
}
}
catch (ByteBufferException &)
{
TC_LOG_ERROR("network", "WorldSocket::ProcessIncoming ByteBufferException occured while parsing an instant handled packet %s from client %s, accountid=%i. Disconnected client.",
opcodeName.c_str(), GetRemoteAddress().c_str(), m_Session ? int32(m_Session->GetAccountId()) : -1);
new_pct->hexlike();
return -1;
}
ACE_NOTREACHED (return 0);
}
int WorldSocket::HandleSendAuthSession()
{
WorldPacket packet(SMSG_AUTH_CHALLENGE, 37);
packet << uint16(0);
for (int i = 0; i < 8; i++)
packet << uint32(0);
packet << uint8(1);
packet << uint32(m_Seed);
return SendPacket(packet);
}
int WorldSocket::HandleAuthSession(WorldPacket& recvPacket)
{
uint8 digest[20];
uint32 clientSeed;
uint8 security;
uint16 clientBuild;
uint32 id;
uint32 addonSize;
LocaleConstant locale;
std::string account;
SHA1Hash sha;
BigNumber k;
WorldPacket addonsData;
recvPacket.read_skip<uint32>();
recvPacket.read_skip<uint32>();
recvPacket >> digest[18];
recvPacket >> digest[14];
recvPacket >> digest[3];
recvPacket >> digest[4];
recvPacket >> digest[0];
recvPacket.read_skip<uint32>();
recvPacket >> digest[11];
recvPacket >> clientSeed;
recvPacket >> digest[19];
recvPacket.read_skip<uint8>();
recvPacket.read_skip<uint8>();
recvPacket >> digest[2];
recvPacket >> digest[9];
recvPacket >> digest[12];
recvPacket.read_skip<uint64>();
recvPacket.read_skip<uint32>();
recvPacket >> digest[16];
recvPacket >> digest[5];
recvPacket >> digest[6];
recvPacket >> digest[8];
recvPacket >> clientBuild;
recvPacket >> digest[17];
recvPacket >> digest[7];
recvPacket >> digest[13];
recvPacket >> digest[15];
recvPacket >> digest[1];
recvPacket >> digest[10];
recvPacket >> addonSize;
addonsData.resize(addonSize);
recvPacket.read((uint8*)addonsData.contents(), addonSize);
recvPacket.ReadBit();
uint32 accountNameLength = recvPacket.ReadBits(11);
account = recvPacket.ReadString(accountNameLength);
if (sWorld->IsClosed())
{
SendAuthResponseError(AUTH_REJECT);
TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: World closed, denying client (%s).", GetRemoteAddress().c_str());
return -1;
}
// Get the account information from the realmd database
// 0 1 2 3 4 5 6 7 8
// SELECT id, sessionkey, last_ip, locked, expansion, mutetime, locale, recruiter, os FROM account WHERE username = ?
PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_INFO_BY_NAME);
stmt->setString(0, account);
PreparedQueryResult result = LoginDatabase.Query(stmt);
// Stop if the account is not found
if (!result)
{
SendAuthResponseError(AUTH_UNKNOWN_ACCOUNT);
TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Sent Auth Response (unknown account).");
return -1;
}
Field* fields = result->Fetch();
uint8 expansion = fields[4].GetUInt8();
uint32 world_expansion = sWorld->getIntConfig(CONFIG_EXPANSION);
if (expansion > world_expansion)
expansion = world_expansion;
///- Re-check ip locking (same check as in realmd).
if (fields[3].GetUInt8() == 1) // if ip is locked
{
if (strcmp (fields[2].GetCString(), GetRemoteAddress().c_str()))
{
SendAuthResponseError(AUTH_FAILED);
TC_LOG_DEBUG("network", "WorldSocket::HandleAuthSession: Sent Auth Response (Account IP differs).");
return -1;
}
}
id = fields[0].GetUInt32();
k.SetHexStr(fields[1].GetCString());
int64 mutetime = fields[5].GetInt64();
//! Negative mutetime indicates amount of seconds to be muted effective on next login - which is now.
if (mutetime < 0)
{
mutetime = time(NULL) + llabs(mutetime);
PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME_LOGIN);
stmt->setInt64(0, mutetime);
stmt->setUInt32(1, id);
LoginDatabase.Execute(stmt);
}
locale = LocaleConstant (fields[6].GetUInt8());
if (locale >= TOTAL_LOCALES)
locale = LOCALE_enUS;
uint32 recruiter = fields[7].GetUInt32();
std::string os = fields[8].GetString();
// Must be done before WorldSession is created
if (sWorld->getBoolConfig(CONFIG_WARDEN_ENABLED) && os != "Win" && os != "OSX")
{
SendAuthResponseError(AUTH_REJECT);
TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Client %s attempted to log in using invalid client OS (%s).", GetRemoteAddress().c_str(), os.c_str());
return -1;
}
// Checks gmlevel per Realm
stmt = LoginDatabase.GetPreparedStatement(LOGIN_GET_GMLEVEL_BY_REALMID);
stmt->setUInt32(0, id);
stmt->setInt32(1, int32(realmID));
result = LoginDatabase.Query(stmt);
if (!result)
security = 0;
else
{
fields = result->Fetch();
security = fields[0].GetUInt8();
}
// Re-check account ban (same check as in realmd)
stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_BANS);
stmt->setUInt32(0, id);
stmt->setString(1, GetRemoteAddress());
PreparedQueryResult banresult = LoginDatabase.Query(stmt);
if (banresult) // if account banned
{
SendAuthResponseError(AUTH_BANNED);
TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Sent Auth Response (Account banned).");
return -1;
}
// Check locked state for serveur
AccountTypes allowedAccountType = sWorld->GetPlayerSecurityLimit();
TC_LOG_DEBUG("network", "Allowed Level: %u Player Level %u", allowedAccountType, AccountTypes(security));
if (allowedAccountType > SEC_PLAYER && AccountTypes(security) < allowedAccountType)
{
SendAuthResponseError(AUTH_UNAVAILABLE);
TC_LOG_INFO("network", "WorldSocket::HandleAuthSession: User tries to login but his security level is not enough");
return -1;
}
// Check that Key and account name are the same on client and serveur
uint32 t = 0;
uint32 seed = m_Seed;
sha.UpdateData(account);
sha.UpdateData((uint8*)&t, 4);
sha.UpdateData((uint8*)&clientSeed, 4);
sha.UpdateData((uint8*)&seed, 4);
sha.UpdateBigNumbers(&k, NULL);
sha.Finalize();
std::string address = GetRemoteAddress();
if (memcmp(sha.GetDigest(), digest, 20))
{
SendAuthResponseError(AUTH_FAILED);
TC_LOG_ERROR("network", "WorldSocket::HandleAuthSession: Authentication failed for account: %u ('%s') address: %s", id, account.c_str(), address.c_str());
return -1;
}
TC_LOG_DEBUG("network", "WorldSocket::HandleAuthSession: Client '%s' authenticated successfully from %s.",
account.c_str(),
address.c_str());
// Check if this user is by any chance a recruiter
stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_RECRUITER);
stmt->setUInt32(0, id);
result = LoginDatabase.Query(stmt);
bool isRecruiter = false;
if (result)
isRecruiter = true;
// Update the last_ip in the database
stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_LAST_IP);
stmt->setString(0, address);
stmt->setString(1, account);
LoginDatabase.Execute(stmt);
// NOTE ATM the socket is single-threaded, have this in mind ...
ACE_NEW_RETURN(m_Session, WorldSession(id, this, AccountTypes(security), expansion, mutetime, locale, recruiter, isRecruiter), -1);
m_Crypt.Init(&k);
m_Session->LoadGlobalAccountData();
m_Session->LoadTutorialsData();
m_Session->ReadAddonsInfo(addonsData);
m_Session->LoadPermissions();
// Initialize Warden system only if it is enabled by config
if (sWorld->getBoolConfig(CONFIG_WARDEN_ENABLED))
m_Session->InitWarden(&k, os);
// Sleep this Network thread for
uint32 sleepTime = sWorld->getIntConfig(CONFIG_SESSION_ADD_DELAY);
ACE_OS::sleep(ACE_Time_Value(0, sleepTime));
sWorld->AddSession(m_Session);
return 0;
}
int WorldSocket::HandlePing (WorldPacket& recvPacket)
{
uint32 ping;
uint32 latency;
// Get the ping packet content
recvPacket >> latency;
recvPacket >> ping;
if (m_LastPingTime == ACE_Time_Value::zero)
m_LastPingTime = ACE_OS::gettimeofday(); // for 1st ping
else
{
ACE_Time_Value cur_time = ACE_OS::gettimeofday();
ACE_Time_Value diff_time (cur_time);
diff_time -= m_LastPingTime;
m_LastPingTime = cur_time;
if (diff_time < ACE_Time_Value (27))
{
++m_OverSpeedPings;
uint32 max_count = sWorld->getIntConfig (CONFIG_MAX_OVERSPEED_PINGS);
if (max_count && m_OverSpeedPings > max_count)
{
ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1);
if (m_Session && !m_Session->HasPermission(rbac::RBAC_PERM_SKIP_CHECK_OVERSPEED_PING))
{
TC_LOG_ERROR("network", "WorldSocket::HandlePing: %s kicked for over-speed pings (address: %s)",
m_Session->GetPlayerInfo().c_str(), GetRemoteAddress().c_str());
return -1;
}
}
}
else
m_OverSpeedPings = 0;
}
// critical section
{
ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1);
if (m_Session)
{
m_Session->SetLatency (latency);
m_Session->ResetClientTimeDelay();
}
else
{
TC_LOG_ERROR("network", "WorldSocket::HandlePing: peer sent CMSG_PING, "
"but is not authenticated or got recently kicked, "
" address = %s",
GetRemoteAddress().c_str());
return -1;
}
}
WorldPacket packet(SMSG_PONG, 4);
packet << ping;
return SendPacket(packet);
}
void WorldSocket::SendAuthResponseError(uint8 code)
{
WorldPacket packet(SMSG_AUTH_RESPONSE, 1);
packet.WriteBit(0); // has account info
packet.WriteBit(0); // has queue info
packet << uint8(code);
SendPacket(packet);
}<|fim▁end|> | ACE_Data_Block db (sizeof (buf),
ACE_Message_Block::MB_DATA,
buf, |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import excmem
def pyasm(scope,s):
cp = codePackageFromFile(cStringIO.StringIO(s),PythonConstants)
mem = CpToMemory(cp)
mem.MakeMemory()
mem.BindPythonFunctions(scope)<|fim▁end|> | from x86asm import codePackageFromFile
from x86cpToMemory import CpToMemory
from pythonConstants import PythonConstants
import cStringIO |
<|file_name|>string_serde_test.py<|end_file_name|><|fim▁begin|># syft absolute
import syft as sy
from syft.lib.python.string import String
from syft.proto.lib.python.string_pb2 import String as String_PB
def test_string_serde() -> None:
syft_string = String("Hello OpenMined")
serialized = syft_string._object2proto()
assert isinstance(serialized, String_PB)
deserialized = String._proto2object(proto=serialized)
assert isinstance(deserialized, String)
assert deserialized.id == syft_string.id
def test_string_send(client: sy.VirtualMachineClient) -> None:
syft_string = String("Hello OpenMined!")
ptr = syft_string.send(client)
<|fim▁hole|> assert ptr.__class__.__name__ == "StringPointer"
# Check that we can get back the object
res = ptr.get()
assert res == syft_string<|fim▁end|> | # Check pointer type |
<|file_name|>ufcs-explicit-self-bad.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::owned::Box;
struct Foo {
f: int,
}
impl Foo {
fn foo(self: int, x: int) -> int { //~ ERROR mismatched self type
//~^ ERROR not a valid type for `self`
self.f + x<|fim▁hole|> f: T,
}
impl<T> Bar<T> {
fn foo(self: Bar<int>, x: int) -> int { //~ ERROR mismatched self type
//~^ ERROR not a valid type for `self`
x
}
fn bar(self: &Bar<uint>, x: int) -> int { //~ ERROR mismatched self type
//~^ ERROR not a valid type for `self`
x
}
}
fn main() {
let foo = box Foo {
f: 1,
};
println!("{}", foo.foo(2));
let bar = box Bar {
f: 1,
};
println!("{} {}", bar.foo(2), bar.bar(2));
}<|fim▁end|> | }
}
struct Bar<T> { |
<|file_name|>spherical_harmonics.py<|end_file_name|><|fim▁begin|>import numpy as np
from scipy.special import sph_harm, lpmv
try:
from scipy.misc import factorial
except:
from scipy.special import factorial
def sh(l, m, theta, phi, field='real', normalization='quantum', condon_shortley=True):
if field == 'real':
return rsh(l, m, theta, phi, normalization, condon_shortley)
elif field == 'complex':
return csh(l, m, theta, phi, normalization, condon_shortley)
else:
raise ValueError('Unknown field: ' + str(field))
def sh_squared_norm(l, normalization='quantum', normalized_haar=True):
"""
Compute the squared norm of the spherical harmonics.
The squared norm of a function on the sphere is defined as
|f|^2 = int_S^2 |f(x)|^2 dx
where dx is a Haar measure.
:param l: for some normalization conventions, the norm of a spherical harmonic Y^l_m depends on the degree l
:param normalization: normalization convention for the spherical harmonic
:param normalized_haar: whether to use the Haar measure da db sinb or the normalized Haar measure da db sinb / 4pi
:return: the squared norm of the spherical harmonic with respect to given measure
"""
if normalization == 'quantum' or normalization == 'seismology':
# The quantum and seismology spherical harmonics are normalized with respect to the Haar measure
# dmu(theta, phi) = dtheta sin(theta) dphi
sqnorm = 1.
elif normalization == 'geodesy':
# The geodesy spherical harmonics are normalized with respect to the *normalized* Haar measure
# dmu(theta, phi) = dtheta sin(theta) dphi / 4pi
sqnorm = 4 * np.pi
elif normalization == 'nfft':
sqnorm = 4 * np.pi / (2 * l + 1)
else:
raise ValueError('Unknown normalization')
if normalized_haar:
return sqnorm / (4 * np.pi)
else:
return sqnorm
def block_sh_ph(L_max, theta, phi):
"""
Compute all spherical harmonics up to and including degree L_max, for angles theta and phi.
This function is currently rather hacky, but the method used here is very fast and stable, compared
to builtin scipy functions.
:param L_max:
:param theta:
:param phi:
:return:
"""
from .pinchon_hoggan.pinchon_hoggan import apply_rotation_block, make_c2b
from .irrep_bases import change_of_basis_function
irreps = np.arange(L_max + 1)
ls = [[ls] * (2 * ls + 1) for ls in irreps]
ls = np.array([ll for sublist in ls for ll in sublist]) # 0, 1, 1, 1, 2, 2, 2, 2, 2, ...
ms = [list(range(-ls, ls + 1)) for ls in irreps]
ms = np.array([mm for sublist in ms for mm in sublist]) # 0, -1, 0, 1, -2, -1, 0, 1, 2, ...
# Get a vector Y that selects the 0-frequency component from each irrep in the centered basis
# If D is a Wigner D matrix, then D Y is the center column of D, which is equal to the spherical harmonics.
Y = (ms == 0).astype(float)
# Change to / from the block basis (since the rotation code works in that basis)
c2b = change_of_basis_function(irreps,
frm=('real', 'quantum', 'centered', 'cs'),
to=('real', 'quantum', 'block', 'cs'))
b2c = change_of_basis_function(irreps,
frm=('real', 'quantum', 'block', 'cs'),
to=('real', 'quantum', 'centered', 'cs'))
Yb = c2b(Y)
# Rotate Yb:
c2b = make_c2b(irreps)
import os
J_block = np.load(os.path.join(os.path.dirname(__file__), 'pinchon_hoggan', 'J_block_0-278.npy'), allow_pickle=True)
J_block = list(J_block[irreps])
g = np.zeros((theta.size, 3))
g[:, 0] = phi
g[:, 1] = theta
TYb = apply_rotation_block(g=g, X=Yb[np.newaxis, :],
irreps=irreps, c2b=c2b,
J_block=J_block, l_max=np.max(irreps))
print(Yb.shape, TYb.shape)
# Change back to centered basis
TYc = b2c(TYb.T).T # b2c doesn't work properly for matrices, so do a transpose hack
print(TYc.shape)
# Somehow, the SH obtained so far are equal to real, nfft, cs spherical harmonics
# Change to real quantum centered cs
c = change_of_basis_function(irreps,
frm=('real', 'nfft', 'centered', 'cs'),
to=('real', 'quantum', 'centered', 'cs'))
TYc2 = c(TYc)
print(TYc2.shape)
return TYc2
def rsh(l, m, theta, phi, normalization='quantum', condon_shortley=True):
"""
Compute the real spherical harmonic (RSH) S_l^m(theta, phi).
The RSH are obtained from Complex Spherical Harmonics (CSH) as follows:
if m < 0:
S_l^m = i / sqrt(2) * (Y_l^m - (-1)^m Y_l^{-m})
if m == 0:
S_l^m = Y_l^0
if m > 0:
S_l^m = 1 / sqrt(2) * (Y_l^{-m} + (-1)^m Y_l^m)
(see [1])
Various normalizations for the CSH exist, see the CSH() function. Since the CSH->RSH change of basis is unitary,
the orthogonality and normalization properties of the RSH are the same as those of the CSH from which they were
obtained. Furthermore, the operation of changing normalization and that of changeing field
(complex->real or vice-versa) commute, because the ratio c_m of normalization constants are always the same for
m and -m (to see this that this implies commutativity, substitute Y_l^m * c_m for Y_l^m in the above formula).
Pinchon & Hoggan [2] define a different change of basis for CSH -> RSH, but they also use an unusual definition
of CSH. To obtain RSH as defined by Pinchon-Hoggan, use this function with normalization='quantum'.
References:
[1] http://en.wikipedia.org/wiki/Spherical_harmonics#Real_form
[2] Rotation matrices for real spherical harmonics: general rotations of atomic orbitals in space-fixed axes.
:param l: non-negative integer; the degree of the CSH.
:param m: integer, -l <= m <= l; the order of the CSH.
:param theta: the colatitude / polar angle,
ranging from 0 (North Pole, (X,Y,Z)=(0,0,1)) to pi (South Pole, (X,Y,Z)=(0,0,-1)).
:param phi: the longitude / azimuthal angle, ranging from 0 to 2 pi.
:param normalization: how to normalize the RSH:
'seismology', 'quantum', 'geodesy'.
these are immediately passed to the CSH functions, and since the change of basis
from CSH to RSH is unitary, the orthogonality and normalization properties are unchanged.
:return: the value of the real spherical harmonic S^l_m(theta, phi)
"""
l, m, theta, phi = np.broadcast_arrays(l, m, theta, phi)<|fim▁hole|> # The reason is that the code that changes from CSH to RSH assumes CS phase.
a = csh(l=l, m=m, theta=theta, phi=phi, normalization=normalization, condon_shortley=True)
b = csh(l=l, m=-m, theta=theta, phi=phi, normalization=normalization, condon_shortley=True)
#if m > 0:
# y = np.array((b + ((-1.)**m) * a).real / np.sqrt(2.))
#elif m < 0:
# y = np.array((1j * a - 1j * ((-1.)**(-m)) * b).real / np.sqrt(2.))
#else:
# # For m == 0, the complex spherical harmonics are already real
# y = np.array(a.real)
y = ((m > 0) * np.array((b + ((-1.)**m) * a).real / np.sqrt(2.))
+ (m < 0) * np.array((1j * a - 1j * ((-1.)**(-m)) * b).real / np.sqrt(2.))
+ (m == 0) * np.array(a.real))
if condon_shortley:
return y
else:
# Cancel the CS phase of y (i.e. multiply by -1 when m is both odd and greater than 0)
return y * ((-1.) ** (m * (m > 0)))
def csh(l, m, theta, phi, normalization='quantum', condon_shortley=True):
"""
Compute Complex Spherical Harmonics (CSH) Y_l^m(theta, phi).
Unlike the scipy.special.sph_harm function, we use the common convention that
theta is the polar angle (0 to pi) and phi is the azimuthal angle (0 to 2pi).
The spherical harmonic 'backbone' is:
Y_l^m(theta, phi) = P_l^m(cos(theta)) exp(i m phi)
where P_l^m is the associated Legendre function as defined in the scipy library (scipy.special.sph_harm).
Various normalization factors can be multiplied with this function.
-> seismology: sqrt( ((2 l + 1) * (l - m)!) / (4 pi * (l + m)!) )
-> quantum: (-1)^2 sqrt( ((2 l + 1) * (l - m)!) / (4 pi * (l + m)!) )
-> unnormalized: 1
-> geodesy: sqrt( ((2 l + 1) * (l - m)!) / (l + m)! )
-> nfft: sqrt( (l - m)! / (l + m)! )
The 'quantum' and 'seismology' CSH are normalized so that
<Y_l^m, Y_l'^m'>
=
int_S^2 Y_l^m(theta, phi) Y_l'^m'* dOmega
=
delta(l, l') delta(m, m')
where dOmega is the volume element for the sphere S^2:
dOmega = sin(theta) dtheta dphi
The 'geodesy' convention have unit power, meaning the norm is equal to the surface area of the unit sphere (4 pi)
<Y_l^m, Y_l'^m'> = 4pi delta(l, l') delta(m, m')
So these are orthonormal with respect to the *normalized* Haar measure sin(theta) dtheta dphi / 4pi
On each of these normalizations, one can optionally include a Condon-Shortley phase factor:
(-1)^m (if m > 0)
1 (otherwise)
Note that this is the definition of Condon-Shortley according to wikipedia [1], but other sources call a
phase factor of (-1)^m a Condon-Shortley phase (without mentioning the condition m > 0).
References:
[1] http://en.wikipedia.org/wiki/Spherical_harmonics#Conventions
:param l: non-negative integer; the degree of the CSH.
:param m: integer, -l <= m <= l; the order of the CSH.
:param theta: the colatitude / polar angle,
ranging from 0 (North Pole, (X,Y,Z)=(0,0,1)) to pi (South Pole, (X,Y,Z)=(0,0,-1)).
:param phi: the longitude / azimuthal angle, ranging from 0 to 2 pi.
:param normalization: how to normalize the CSH:
'seismology', 'quantum', 'geodesy', 'unnormalized', 'nfft'.
:return: the value of the complex spherical harmonic Y^l_m(theta, phi)
"""
# NOTE: it seems like in the current version of scipy.special, sph_harm no longer accepts keyword arguments,
# so I'm removing them. I hope the order of args hasn't changed
if normalization == 'quantum':
# y = ((-1.) ** m) * sph_harm(m, l, theta=phi, phi=theta)
y = ((-1.) ** m) * sph_harm(m, l, phi, theta)
elif normalization == 'seismology':
# y = sph_harm(m, l, theta=phi, phi=theta)
y = sph_harm(m, l, phi, theta)
elif normalization == 'geodesy':
# y = np.sqrt(4 * np.pi) * sph_harm(m, l, theta=phi, phi=theta)
y = np.sqrt(4 * np.pi) * sph_harm(m, l, phi, theta)
elif normalization == 'unnormalized':
# y = sph_harm(m, l, theta=phi, phi=theta) / np.sqrt((2 * l + 1) * factorial(l - m) /
# (4 * np.pi * factorial(l + m)))
y = sph_harm(m, l, phi, theta) / np.sqrt((2 * l + 1) * factorial(l - m) /
(4 * np.pi * factorial(l + m)))
elif normalization == 'nfft':
# y = sph_harm(m, l, theta=phi, phi=theta) / np.sqrt((2 * l + 1) / (4 * np.pi))
y = sph_harm(m, l, phi, theta) / np.sqrt((2 * l + 1) / (4 * np.pi))
else:
raise ValueError('Unknown normalization convention:' + str(normalization))
if condon_shortley:
# The sph_harm function already includes CS phase
return y
else:
# Cancel the CS phase in sph_harm (i.e. multiply by -1 when m is both odd and greater than 0)
return y * ((-1.) ** (m * (m > 0)))
# For testing only:
def _naive_csh_unnormalized(l, m, theta, phi):
"""
Compute unnormalized SH
"""
return lpmv(m, l, np.cos(theta)) * np.exp(1j * m * phi)
def _naive_csh_quantum(l, m, theta, phi):
"""
Compute orthonormalized spherical harmonics in a naive way.
"""
return (((-1.) ** m) * lpmv(m, l, np.cos(theta)) * np.exp(1j * m * phi) *
np.sqrt(((2 * l + 1) * factorial(l - m))
/
(4 * np.pi * factorial(l + m))))
def _naive_csh_seismology(l, m, theta, phi):
"""
Compute the spherical harmonics according to the seismology convention, in a naive way.
This appears to be equal to the sph_harm function in scipy.special.
"""
return (lpmv(m, l, np.cos(theta)) * np.exp(1j * m * phi) *
np.sqrt(((2 * l + 1) * factorial(l - m))
/
(4 * np.pi * factorial(l + m))))
def _naive_csh_ph(l, m, theta, phi):
"""
CSH as defined by Pinchon-Hoggan. Same as wikipedia's quantum-normalized SH = naive_Y_quantum()
"""
if l == 0 and m == 0:
return 1. / np.sqrt(4 * np.pi)
else:
phase = ((1j) ** (m + np.abs(m)))
normalizer = np.sqrt(((2 * l + 1.) * factorial(l - np.abs(m)))
/
(4 * np.pi * factorial(l + np.abs(m))))
P = lpmv(np.abs(m), l, np.cos(theta))
e = np.exp(1j * m * phi)
return phase * normalizer * P * e
def _naive_rsh_ph(l, m, theta, phi):
if m == 0:
return np.sqrt((2 * l + 1.) / (4 * np.pi)) * lpmv(m, l, np.cos(theta))
elif m < 0:
return np.sqrt(((2 * l + 1.) * factorial(l + m)) /
(2 * np.pi * factorial(l - m))) * lpmv(-m, l, np.cos(theta)) * np.sin(-m * phi)
elif m > 0:
return np.sqrt(((2 * l + 1.) * factorial(l - m)) /
(2 * np.pi * factorial(l + m))) * lpmv(m, l, np.cos(theta)) * np.cos(m * phi)<|fim▁end|> | # Get the CSH for m and -m, using Condon-Shortley phase (regardless of whhether CS is requested or not) |
<|file_name|>common.js<|end_file_name|><|fim▁begin|>! (function($){
$(function(){
if ($('.haik-config-menu').length){
$('.haik-admin-navbar-inside').prepend('<a class="navbar-brand pull-right" href="#haik_config_slider" id="config_slider_link"><img src="haik-contents/img/haiklogo.png" height="50"></a>');
// ! admin slider
$("#config_slider_link").sidr({
name: "slider-right",
source: "#haik_config_slider",
side: "right",
renaming: false,
onOpen: function(){<|fim▁hole|> $(document).on("click.configSlider keydown.configSlider", "*", function(e){
e.stopPropagation();
if ( ! $(e.target).is("[data-toggle=modal]") && $(e.target).closest(".haik-admin-slider").length > 0) return;
$.sidr('close', 'slider-right');
});
$(".haik-admin-slider .close").on('click', function(){
$.sidr('close', 'slider-right');
});
},
onClose: function(){
$(document).off(".configSlider");
}
});
}
$(".setting_list")
.on("show", "> li", function(e){
// console.log("show");
})
.on("shown", "> li", function(e, $block){
if ($(".datepicker", $block).length) {
$(".datepicker").datepicker({language: 'ja'});
}
$block.find('input:radio, select').each(function(){
var item = $(this).attr('name');
if ($(this).is(':radio'))
{
$block.find("input:radio[name="+item+"]").val([ORGM.options[item]]);
}
if ($(this).is('select') && $(this).is(':not[data-selected]'))
{
$block.find("select[name="+item+"]").val(ORGM.options[item]);
}
});
if ($.fn.passwdcheck) {
$('input[name=new_passwd]', $block).passwdcheck($.extend({}, ORGM.passwdcheck.options, {placeholderClass:"col-sm-3"}));
}
$("[data-exnote=onshown]", $block).exnote();
// console.log("shown");
// console.log($block);
})
.on("hide", "> li", function(e, $block){
// console.log("hide");
// console.log($block);
ORGM.scroll(this);
})
.on("hidden", "> li", function(e, $block){
// console.log("hidden");
// console.log($block);
var $li = $(this);
})
.on("submit", "> li", function(e, data){
var $configbox = $(this).next()
, callback = function(){};
if (data.error) {
$configbox.find("input, select, textarea").filter("[name="+data.item+"]")
.after('<span class="help-block" data-error-message>'+data.error+'</span>')
.closest(".form-group").addClass("has-error");
ORGM.notify(data.error, "error");
// パスワードの場合は、新パスワードと確認欄を消す
if (data.item == 'new_passwd' || data.item == 're_passwd') {
$configbox.find("input, select, textarea").filter("[name$=_passwd]").val('');
}
return false;
}
if (typeof data.item !== "undefined") {
// mc_api_key の場合、mc_lists を options へセットする
if (data.item === "mc_api_key") {
data.options = $.extend(data.options, {mc_lists: data.mc_lists});
}
else if (data.item === "mc_list_id" && data.mc_list_id.length > 0) {
$("#mc_form_confirm").filter(".in").collapse("hide");
}
// passwd 変更した場合、ログアウト状態になるので、
// redirect_to へ転送する
else if (data.item === "passwd" && typeof data.redirect_to !== "undefinded") {
callback = function(){
location.href = data.redirect_to;
};
}
}
ORGM.options = $.extend(ORGM.options, data.options);
$('.current', this).text(data.value);
$(this).configblock('hide');
ORGM.notify(data.message, "success", callback);
})
.on("submitStart", "> li", function(e){
var $configbox = $(this).next();
$('.form-group').filter('.has-error').removeClass('has-error')
.find('[data-error-message]').remove();
})
.on('click', '[data-image]', function(e){
e.preventDefault();
var self = this
,$filer = $("#orgm_filer_selector")
,$image = $(this);
$filer.find("iframe").data({search_word: ":image", select_mode: "exclusive"});
$filer
.on("show.bs.modal", function(){
$(document).on("selectFiles.pluginAppConfigLogImage", function(e, selectedFiles){
if (selectedFiles.length > 0) {
$image.html('<img src="'+selectedFiles[0].filepath+'" alt="" /><span class="triangle-btn triangle-right-top red show" data-image-delete><i class="orgm-icon orgm-icon-close"></i></span>');
$image.data('image', selectedFiles[0].filename).removeClass('img-add');
$image.next().val(selectedFiles[0].filename);
$filer.modal("hide");
}
});
})
.on("hidden.bs.modal", function(){
$(document).off("selectFiles.pluginAppConfigLogImage");
});
$filer.data("footer", "").modal();
})
.on('click', '[data-image-delete]', function(e){
e.preventDefault();
$image = $(this).parent();
$image.addClass('img-add').html("クリックで画像選択").next().val("");
return false;
})
.on('click', '[data-confirm]', function(e){
e.preventDefault();
var mode = $(this).data('confirm');
if (mode == 'maintenance') {
if (confirm('メンテナンスを実行しますか?')) {
var data = {
cmd: 'app_config_system',
phase: 'exec',
mode: mode
};
$.post(ORGM.baseUrl, data, function(res){
if (res.error)
{
ORGM.notify(res.error, 'error');
return false;
}
ORGM.notify(res.success);
return false;
}, 'json');
}
}
});
$(document).on("click", ".mailcheck", function(){
var username = $(this).closest('.controls').find('input[name=username]').val();
data = {
cmd: 'app_config_auth',
phase: 'mailcheck',
username: username
};
$.post(ORGM.baseUrl, data, function(res){
if (res.error)
{
ORGM.notify(res.error, 'error');
return false;
}
ORGM.notify(res.success);
return false;
}, 'json');
})
// MCフォームを更新する
.on("show.bs.collapse", "#mc_form_confirm", function(e){
var $this = $(this);
if ($this.data("mc_list_id") === ORGM.options.mc_list.id) return;
var data = {
cmd: "app_config_marketing",
phase: "get",
mc_list_id: ORGM.options.mc_list.id
};
$.ajax({
url: ORGM.baseUrl,
data: data,
dataType: "json",
type: "POST",
success: function(res){
$this.html(res[0].html).data("mc_list_id", ORGM.options.mc_list.id);
}
});
});
// set mc_lists value to options
if (typeof ORGM.mcLists !== "undefined") {
ORGM.options = $.extend({}, ORGM.options, {mc_lists: ORGM.mcLists});
}
});
})(window.jQuery);
// !ConfigBlock
!function ($) {
"use strict"; // jshint ;_;
/* ConfigBlock CLASS DEFINITION
* ====================== */
var ConfigBlock = function(element, options) {
this.options = options;
this.$element = $(element);//li element
this.$element
.on('click.configblock', '[data-edit]', $.proxy(this.show, this))
}
ConfigBlock.prototype = {
constructor: ConfigBlock
, toggle: function () {
return this[!this.isShown ? 'show' : 'hide']()
}
, show: function (e) {
e && e.preventDefault();
var that = this
, e = $.Event('show')
, $a = this.$element.find("[data-edit]")
, tmpl = "#tmpl_conf_" + $a.data("edit");
this.$element.trigger(e);
if (this.isShown || e.isDefaultPrevented()) return
this.$block = $(tmpl).tmpl(ORGM.options, {unixtime: function(){return "hoge"}});
this.$block.insertAfter(this.$element);
this.$block
.on('click.dismiss.configblock', '[data-dismiss="configblock"]', $.proxy(this.hide, this))
.on('submit.configblock', $.proxy(this.submit, this))
this.isShown = true
this.$block.addClass('in')
// .attr('aria-hidden', false)
this.$element.addClass('in')
this.$element.trigger("shown", [this.$block]);
}
, hide: function (e) {
e && e.preventDefault()
var that = this
e = $.Event('hide')
this.$element.trigger(e, [this.$block])
if (!this.isShown || e.isDefaultPrevented()) return
$(document).off('focusin.configblock')
this.isShown = false
this.$block
.removeClass('in')
// .attr('aria-hidden', true)
this.$element.removeClass("in")
$.support.transition && this.$block.hasClass('fade') ?
this.hideWithTransition() :
this.hideConfig()
}
, hideWithTransition: function () {
var that = this
, timeout = setTimeout(function () {
that.$block.off($.support.transition.end)
that.hideConfig()
}, 500)
this.$block.one($.support.transition.end, function () {
clearTimeout(timeout)
that.hideConfig()
})
}
, hideConfig: function (that) {
this.$block
.hide().remove()
this.$element
.trigger('hidden', [this.$block])
}
, submit: function (e) {
e && e.preventDefault()
var data = this.$block.find("form").serialize()
, that = this
this.$element.trigger("submitStart");
$.ajax({
url: ORGM.baseUrl,
type: "POST",
data: data,
dataType: "json",
success: function(res){
that.$element.trigger("submit", [res])
}
});
/*
$.post(ORGM.baseUrl, data, function(res){
that.$element.trigger("submit", [res])
}, "json")
*/
}
}
/* MODAL PLUGIN DEFINITION
* ======================= */
$.fn.configblock = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('configblock')
, options = $.extend({}, $.fn.configblock.defaults, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('configblock', (data = new ConfigBlock(this, options)))
if (typeof option == 'string') data[option]()
else if (options.show) data.show()
})
}
$.fn.configblock.defaults = {
show: false
}
$.fn.configblock.Constructor = ConfigBlock;
/* MODAL DATA-API
* ============== */
$(function(){
$(".setting_list > li").each(function(){$(this).configblock();});
if (location.hash && $("[data-edit='"+location.hash.substr(1)+"']").length > 0) {
$("[data-edit='"+location.hash.substr(1)+"']").click();
}
})
}(window.jQuery);<|fim▁end|> | |
<|file_name|>Test_ExecutorDispatcher.py<|end_file_name|><|fim▁begin|>""" py.test test of ExecutorDispatcher
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=protected-access
__RCSID__ = "$Id$"
from DIRAC.Core.Utilities.ExecutorDispatcher import (
ExecutorState,
ExecutorQueues,
)
execState = ExecutorState()
execState.addExecutor(1, "type1", 2)
eQ = ExecutorQueues()<|fim▁hole|> """test of ExecutorState"""
assert execState.freeSlots(1) == 2
assert execState.addTask(1, "t1") == 1
assert execState.addTask(1, "t1") == 1
assert execState.addTask(1, "t2") == 2
assert execState.freeSlots(1) == 0
assert execState.full(1)
assert execState.removeTask("t1") == 1
assert execState.freeSlots(1) == 1
assert execState.getFreeExecutors("type1") == {1: 1}
assert execState.getTasksForExecutor(1) == {"t2"}
assert execState.removeExecutor(1)
assert execState._internals()
def test_execQueues():
"""test of ExecutorQueues"""
for y in range(2):
for i in range(3):
assert eQ.pushTask("type%s" % y, "t%s%s" % (y, i)) == i + 1
assert "DONE IN"
res_internals = eQ._internals()
assert res_internals["queues"] == {"type0": ["t00", "t01", "t02"], "type1": ["t10", "t11", "t12"]}
assert set(res_internals["lastUse"].keys()) == {"type0", "type1"}
assert res_internals["taskInQueue"] == {
"t00": "type0",
"t01": "type0",
"t02": "type0",
"t10": "type1",
"t11": "type1",
"t12": "type1",
}
assert eQ.pushTask("type0", "t01") == 3
assert eQ.getState()
assert eQ.popTask("type0")[0] == "t00"
assert eQ.pushTask("type0", "t00", ahead=True) == 3
assert eQ.popTask("type0")[0] == "t00"
assert eQ.deleteTask("t01")
res_internals = eQ._internals()
assert res_internals["queues"] == {"type0": ["t02"], "type1": ["t10", "t11", "t12"]}
assert set(res_internals["lastUse"].keys()) == {"type0", "type1"}
assert res_internals["taskInQueue"] == {
"t02": "type0",
"t10": "type1",
"t11": "type1",
"t12": "type1",
}
assert eQ.getState()
assert eQ.deleteTask("t02")
res_internals = eQ._internals()
assert res_internals["queues"] == {"type0": [], "type1": ["t10", "t11", "t12"]}
assert set(res_internals["lastUse"].keys()) == {"type0", "type1"}
assert res_internals["taskInQueue"] == {
"t10": "type1",
"t11": "type1",
"t12": "type1",
}
assert eQ.getState()
for i in range(3):
assert eQ.popTask("type1")[0] == "t1%s" % i
res_internals = eQ._internals()
assert res_internals["queues"] == {"type0": [], "type1": []}
assert set(res_internals["lastUse"].keys()) == {"type0", "type1"}
assert res_internals["taskInQueue"] == {}
assert eQ.pushTask("type0", "t00") == 1
assert eQ.popTask("type0") == ("t00", "type0")
res_internals = eQ._internals()
assert res_internals["queues"] == {"type0": [], "type1": []}
assert set(res_internals["lastUse"].keys()) == {"type0", "type1"}
assert res_internals["taskInQueue"] == {}
assert eQ.pushTask("type0", "t00") == 1
assert eQ.deleteTask("t00")
res_internals = eQ._internals()
assert res_internals["queues"] == {"type0": [], "type1": []}
assert set(res_internals["lastUse"].keys()) == {"type0", "type1"}
assert res_internals["taskInQueue"] == {}
assert not eQ.deleteTask("t00")<|fim▁end|> |
def test_ExecutorState(): |
<|file_name|>production.py<|end_file_name|><|fim▁begin|>from decouple import Csv, config
from dj_database_url import parse as db_url
from .base import * # noqa
DEBUG = False
SECRET_KEY = config('SECRET_KEY')
DATABASES = {
'default': config('DATABASE_URL', cast=db_url),
}
DATABASES['default']['ATOMIC_REQUESTS'] = True
ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
MEDIA_ROOT = 'mediafiles'
MEDIA_URL = '/media/'
SERVER_EMAIL = '[email protected]'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = config('SENDGRID_USERNAME')
EMAIL_HOST_PASSWORD = config('SENDGRID_PASSWORD')
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# Security
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 3600
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True<|fim▁hole|>
# Webpack
WEBPACK_LOADER['DEFAULT']['CACHE'] = True
# Celery
CELERY_BROKER_URL = config('REDIS_URL')
CELERY_RESULT_BACKEND = config('REDIS_URL')
CELERY_SEND_TASK_ERROR_EMAILS = True
# Whitenoise
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MIDDLEWARE.insert( # insert WhiteNoiseMiddleware right after SecurityMiddleware
MIDDLEWARE.index('django.middleware.security.SecurityMiddleware') + 1,
'whitenoise.middleware.WhiteNoiseMiddleware')
# django-log-request-id
MIDDLEWARE.insert( # insert RequestIDMiddleware on the top
0, 'log_request_id.middleware.RequestIDMiddleware')
LOG_REQUEST_ID_HEADER = 'HTTP_X_REQUEST_ID'
LOG_REQUESTS = True
# Opbeat
INSTALLED_APPS += ['opbeat.contrib.django']
MIDDLEWARE.insert( # insert OpbeatAPMMiddleware on the top
0, 'opbeat.contrib.django.middleware.OpbeatAPMMiddleware')
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
},
'request_id': {
'()': 'log_request_id.filters.RequestIDFilter'
},
},
'formatters': {
'standard': {
'format': '%(levelname)-8s [%(asctime)s] [%(request_id)s] %(name)s: %(message)s'
},
},
'handlers': {
'null': {
'class': 'logging.NullHandler',
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'filters': ['require_debug_false'],
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'filters': ['request_id'],
'formatter': 'standard',
},
},
'loggers': {
'': {
'handlers': ['console'],
'level': 'INFO'
},
'django.security.DisallowedHost': {
'handlers': ['null'],
'propagate': False,
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'log_request_id.middleware': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False,
},
}
}<|fim▁end|> | X_FRAME_OPTIONS = 'DENY'
CSRF_COOKIE_HTTPONLY = True |
<|file_name|>enumeration.rs<|end_file_name|><|fim▁begin|>use crate::model::create::{CreateError, CreateResult};
use crate::model::enumeration::Enumeration;
use crate::model::symbol::Symbol;
use crate::model::Def;
use crate::xsd::restriction::Facet;
use crate::xsd::simple_type::{Payload, SimpleType};
use crate::xsd::{simple_type, Xsd};
pub(super) fn is_enumeration(st: &SimpleType) -> bool {
match &st.payload {
Payload::Restriction(r) => {
if r.facets.is_empty() {
return false;
}
for facet in &r.facets {
match facet {
Facet::Enumeration(_) => continue,
_ => return false,
}
}
return true;
}
_ => false,
}
}
pub(super) fn model_enumeration(st: &SimpleType, xsd: &Xsd) -> CreateResult {
let restriction = if let simple_type::Payload::Restriction(r) = &st.payload {
r
} else {
return Err(CreateError::new("expected restriction"));
};
let mut members = Vec::new();
for facet in &restriction.facets {
let s = if let Facet::Enumeration(s) = facet {
s
} else {
return Err(CreateError::new("expected enumeration"));
};
members.push(Symbol::new(s.as_str()));
}
let default = members
.first()
.ok_or_else(|| make_create_err!("no members!"))?
.clone();
let enm = Enumeration {
name: Symbol::new(st.name.as_str()),
members,
documentation: st.documentation(),
default,
other_field: None,
};<|fim▁hole|>}<|fim▁end|> | Ok(Some(vec![Def::Enumeration(enm)])) |
<|file_name|>test_credential.py<|end_file_name|><|fim▁begin|>import itertools
import re
import mock # noqa
import pytest
from awx.main.models import (AdHocCommand, Credential, CredentialType, Job, JobTemplate,
Inventory, InventorySource, Project,
WorkflowJobNode)
from awx.main.utils import decrypt_field
from awx.api.versioning import reverse
EXAMPLE_PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----\nxyz==\n-----END PRIVATE KEY-----'
EXAMPLE_ENCRYPTED_PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\nxyz==\n-----END PRIVATE KEY-----'
@pytest.mark.django_db
def test_idempotent_credential_type_setup():
assert CredentialType.objects.count() == 0
CredentialType.setup_tower_managed_defaults()
total = CredentialType.objects.count()
assert total > 0
CredentialType.setup_tower_managed_defaults()
assert CredentialType.objects.count() == total
@pytest.mark.django_db
@pytest.mark.parametrize('kind, total', [
('ssh', 1), ('net', 0)
])
def test_filter_by_v1_kind(get, admin, organization, kind, total):
CredentialType.setup_tower_managed_defaults()
cred = Credential(
credential_type=CredentialType.from_v1_kind('ssh'),
name='Best credential ever',
organization=organization,
inputs={
'username': u'jim',
'password': u'secret'
}
)
cred.save()
response = get(
reverse('api:credential_list', kwargs={'version': 'v1'}),
admin,
QUERY_STRING='kind=%s' % kind
)
assert response.status_code == 200
assert response.data['count'] == total
@pytest.mark.django_db
def test_filter_by_v1_kind_with_vault(get, admin, organization):
CredentialType.setup_tower_managed_defaults()
cred = Credential(
credential_type=CredentialType.objects.get(kind='ssh'),
name='Best credential ever',
organization=organization,
inputs={
'username': u'jim',
'password': u'secret'
}
)
cred.save()
cred = Credential(
credential_type=CredentialType.objects.get(kind='vault'),
name='Best credential ever',
organization=organization,
inputs={
'vault_password': u'vault!'
}
)
cred.save()
response = get(
reverse('api:credential_list', kwargs={'version': 'v1'}),
admin,
QUERY_STRING='kind=ssh'
)
assert response.status_code == 200
assert response.data['count'] == 2
@pytest.mark.django_db
def test_insights_credentials_in_v1_api_list(get, admin, organization):
credential_type = CredentialType.defaults['insights']()
credential_type.save()
cred = Credential(
credential_type=credential_type,
name='Best credential ever',
organization=organization,
inputs={
'username': u'joe',
'password': u'secret'
}
)
cred.save()
response = get(
reverse('api:credential_list', kwargs={'version': 'v1'}),
admin
)
assert response.status_code == 200
assert response.data['count'] == 1
cred = response.data['results'][0]
assert cred['kind'] == 'insights'
assert cred['username'] == 'joe'
assert cred['password'] == '$encrypted$'
@pytest.mark.django_db
def test_create_insights_credentials_in_v1(get, post, admin, organization):
credential_type = CredentialType.defaults['insights']()
credential_type.save()
response = post(
reverse('api:credential_list', kwargs={'version': 'v1'}),
{
'name': 'Best Credential Ever',
'organization': organization.id,
'kind': 'insights',
'username': 'joe',
'password': 'secret'
},
admin
)
assert response.status_code == 201
cred = Credential.objects.get(pk=response.data['id'])
assert cred.username == 'joe'
assert decrypt_field(cred, 'password') == 'secret'
assert cred.credential_type == credential_type
@pytest.mark.django_db
def test_custom_credentials_not_in_v1_api_list(get, admin, organization):
"""
'Custom' credentials (those not managed by Tower) shouldn't be visible from
the V1 credentials API list
"""
credential_type = CredentialType(
kind='cloud',
name='MyCloud',
inputs = {
'fields': [{
'id': 'password',
'label': 'Password',
'type': 'string',
'secret': True
}]
}
)
credential_type.save()
cred = Credential(
credential_type=credential_type,
name='Best credential ever',
organization=organization,
inputs={
'password': u'secret'
}
)
cred.save()
response = get(
reverse('api:credential_list', kwargs={'version': 'v1'}),
admin
)
assert response.status_code == 200
assert response.data['count'] == 0
@pytest.mark.django_db
def test_custom_credentials_not_in_v1_api_detail(get, admin, organization):
"""
'Custom' credentials (those not managed by Tower) shouldn't be visible from
the V1 credentials API detail
"""
credential_type = CredentialType(
kind='cloud',
name='MyCloud',
inputs = {
'fields': [{
'id': 'password',
'label': 'Password',
'type': 'string',
'secret': True
}]
}
)
credential_type.save()
cred = Credential(
credential_type=credential_type,
name='Best credential ever',
organization=organization,
inputs={
'password': u'secret'
}
)
cred.save()
response = get(
reverse('api:credential_detail', kwargs={'version': 'v1', 'pk': cred.pk}),
admin
)
assert response.status_code == 404
@pytest.mark.django_db
def test_filter_by_v1_invalid_kind(get, admin, organization):
response = get(
reverse('api:credential_list', kwargs={'version': 'v1'}),
admin,
QUERY_STRING='kind=bad_kind'
)
assert response.status_code == 400
#
# user credential creation
#
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {'username': 'someusername'}],
['v2', {'credential_type': 1, 'inputs': {'username': 'someusername'}}]
])
def test_create_user_credential_via_credentials_list(post, get, alice, credentialtype_ssh, version, params):
params['user'] = alice.id
params['name'] = 'Some name'
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
alice
)
assert response.status_code == 201
response = get(reverse('api:credential_list', kwargs={'version': version}), alice)
assert response.status_code == 200
assert response.data['count'] == 1
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {'username': 'someusername'}],
['v2', {'credential_type': 1, 'inputs': {'username': 'someusername'}}]
])
def test_credential_validation_error_with_bad_user(post, admin, version, credentialtype_ssh, params):
params['user'] = 'asdf'
params['name'] = 'Some name'
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 400
assert response.data['user'][0] == 'Incorrect type. Expected pk value, received unicode.'
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {'username': 'someusername'}],
['v2', {'credential_type': 1, 'inputs': {'username': 'someusername'}}]
])
def test_create_user_credential_via_user_credentials_list(post, get, alice, credentialtype_ssh, version, params):
params['user'] = alice.id
params['name'] = 'Some name'
response = post(
reverse('api:user_credentials_list', kwargs={'version': version, 'pk': alice.pk}),
params,
alice
)
assert response.status_code == 201
response = get(reverse('api:user_credentials_list', kwargs={'version': version, 'pk': alice.pk}), alice)
assert response.status_code == 200
assert response.data['count'] == 1
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {'username': 'someusername'}],
['v2', {'credential_type': 1, 'inputs': {'username': 'someusername'}}]
])
def test_create_user_credential_via_credentials_list_xfail(post, alice, bob, version, params):
params['user'] = bob.id
params['name'] = 'Some name'
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
alice
)
assert response.status_code == 403
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {'username': 'someusername'}],
['v2', {'credential_type': 1, 'inputs': {'username': 'someusername'}}]
])
def test_create_user_credential_via_user_credentials_list_xfail(post, alice, bob, version, params):
params['user'] = bob.id
params['name'] = 'Some name'
response = post(
reverse('api:user_credentials_list', kwargs={'version': version, 'pk': bob.pk}),
params,
alice
)
assert response.status_code == 403
#
# team credential creation
#
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {'username': 'someusername'}],
['v2', {'credential_type': 1, 'inputs': {'username': 'someusername'}}]
])
def test_create_team_credential(post, get, team, organization, org_admin, team_member, credentialtype_ssh, version, params):
params['team'] = team.id
params['name'] = 'Some name'
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
org_admin
)
assert response.status_code == 201
response = get(
reverse('api:team_credentials_list', kwargs={'version': version, 'pk': team.pk}),
team_member
)
assert response.status_code == 200
assert response.data['count'] == 1
# Assure that credential's organization is implictly set to team's org
assert response.data['results'][0]['summary_fields']['organization']['id'] == team.organization.id
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {'username': 'someusername'}],
['v2', {'credential_type': 1, 'inputs': {'username': 'someusername'}}]
])
def test_create_team_credential_via_team_credentials_list(post, get, team, org_admin, team_member, credentialtype_ssh, version, params):
params['team'] = team.id
params['name'] = 'Some name'
response = post(
reverse('api:team_credentials_list', kwargs={'version': version, 'pk': team.pk}),
params,
org_admin
)
assert response.status_code == 201
response = get(
reverse('api:team_credentials_list', kwargs={'version': version, 'pk': team.pk}),
team_member
)
assert response.status_code == 200
assert response.data['count'] == 1
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {'username': 'someusername'}],
['v2', {'credential_type': 1, 'inputs': {'username': 'someusername'}}]
])
def test_create_team_credential_by_urelated_user_xfail(post, team, organization, alice, team_member, version, params):
params['team'] = team.id
params['organization'] = organization.id
params['name'] = 'Some name'
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
alice
)
assert response.status_code == 403
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {'username': 'someusername'}],
['v2', {'credential_type': 1, 'inputs': {'username': 'someusername'}}]
])
def test_create_team_credential_by_team_member_xfail(post, team, organization, alice, team_member, version, params):
# Members can't add credentials, only org admins.. for now?
params['team'] = team.id
params['organization'] = organization.id
params['name'] = 'Some name'
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
team_member
)
assert response.status_code == 403
#
# Permission granting
#
@pytest.mark.django_db
@pytest.mark.parametrize('version', ['v1', 'v2'])
def test_grant_org_credential_to_org_user_through_role_users(post, credential, organization, org_admin, org_member, version):
credential.organization = organization
credential.save()
response = post(reverse('api:role_users_list', kwargs={'version': version, 'pk': credential.use_role.id}), {
'id': org_member.id
}, org_admin)
assert response.status_code == 204
@pytest.mark.django_db
@pytest.mark.parametrize('version', ['v1', 'v2'])
def test_grant_org_credential_to_org_user_through_user_roles(post, credential, organization, org_admin, org_member, version):
credential.organization = organization
credential.save()
response = post(reverse('api:user_roles_list', kwargs={'version': version, 'pk': org_member.id}), {
'id': credential.use_role.id
}, org_admin)
assert response.status_code == 204
@pytest.mark.django_db
@pytest.mark.parametrize('version', ['v1', 'v2'])
def test_grant_org_credential_to_non_org_user_through_role_users(post, credential, organization, org_admin, alice, version):
credential.organization = organization
credential.save()
response = post(reverse('api:role_users_list', kwargs={'version': version, 'pk': credential.use_role.id}), {
'id': alice.id
}, org_admin)
assert response.status_code == 400
@pytest.mark.django_db
@pytest.mark.parametrize('version', ['v1', 'v2'])
def test_grant_org_credential_to_non_org_user_through_user_roles(post, credential, organization, org_admin, alice, version):
credential.organization = organization
credential.save()
response = post(reverse('api:user_roles_list', kwargs={'version': version, 'pk': alice.id}), {
'id': credential.use_role.id
}, org_admin)
assert response.status_code == 400
@pytest.mark.django_db
@pytest.mark.parametrize('version', ['v1', 'v2'])
def test_grant_private_credential_to_user_through_role_users(post, credential, alice, bob, version):
# normal users can't do this
credential.admin_role.members.add(alice)
response = post(reverse('api:role_users_list', kwargs={'version': version, 'pk': credential.use_role.id}), {
'id': bob.id
}, alice)
assert response.status_code == 400
@pytest.mark.django_db
@pytest.mark.parametrize('version', ['v1', 'v2'])
def test_grant_private_credential_to_org_user_through_role_users(post, credential, org_admin, org_member, version):
# org admins can't either
credential.admin_role.members.add(org_admin)
response = post(reverse('api:role_users_list', kwargs={'version': version, 'pk': credential.use_role.id}), {
'id': org_member.id
}, org_admin)
assert response.status_code == 400
@pytest.mark.django_db
@pytest.mark.parametrize('version', ['v1', 'v2'])
def test_sa_grant_private_credential_to_user_through_role_users(post, credential, admin, bob, version):
# but system admins can
response = post(reverse('api:role_users_list', kwargs={'version': version, 'pk': credential.use_role.id}), {
'id': bob.id
}, admin)
assert response.status_code == 204
@pytest.mark.django_db
@pytest.mark.parametrize('version', ['v1', 'v2'])
def test_grant_private_credential_to_user_through_user_roles(post, credential, alice, bob, version):
# normal users can't do this
credential.admin_role.members.add(alice)
response = post(reverse('api:user_roles_list', kwargs={'version': version, 'pk': bob.id}), {
'id': credential.use_role.id
}, alice)
assert response.status_code == 400
@pytest.mark.django_db
@pytest.mark.parametrize('version', ['v1', 'v2'])
def test_grant_private_credential_to_org_user_through_user_roles(post, credential, org_admin, org_member, version):
# org admins can't either
credential.admin_role.members.add(org_admin)
response = post(reverse('api:user_roles_list', kwargs={'version': version, 'pk': org_member.id}), {
'id': credential.use_role.id
}, org_admin)
assert response.status_code == 400
@pytest.mark.django_db
@pytest.mark.parametrize('version', ['v1', 'v2'])
def test_sa_grant_private_credential_to_user_through_user_roles(post, credential, admin, bob, version):
# but system admins can
response = post(reverse('api:user_roles_list', kwargs={'version': version, 'pk': bob.id}), {
'id': credential.use_role.id
}, admin)
assert response.status_code == 204
@pytest.mark.django_db
@pytest.mark.parametrize('version', ['v1', 'v2'])
def test_grant_org_credential_to_team_through_role_teams(post, credential, organization, org_admin, org_auditor, team, version):
assert org_auditor not in credential.read_role
credential.organization = organization
credential.save()
response = post(reverse('api:role_teams_list', kwargs={'version': version, 'pk': credential.use_role.id}), {
'id': team.id
}, org_admin)
assert response.status_code == 204
assert org_auditor in credential.read_role
@pytest.mark.django_db
@pytest.mark.parametrize('version', ['v1', 'v2'])
def test_grant_org_credential_to_team_through_team_roles(post, credential, organization, org_admin, org_auditor, team, version):
assert org_auditor not in credential.read_role
credential.organization = organization
credential.save()
response = post(reverse('api:team_roles_list', kwargs={'version': version, 'pk': team.id}), {
'id': credential.use_role.id
}, org_admin)
assert response.status_code == 204
assert org_auditor in credential.read_role
@pytest.mark.django_db
@pytest.mark.parametrize('version', ['v1', 'v2'])
def test_sa_grant_private_credential_to_team_through_role_teams(post, credential, admin, team, version):
# not even a system admin can grant a private cred to a team though
response = post(reverse('api:role_teams_list', kwargs={'version': version, 'pk': credential.use_role.id}), {
'id': team.id
}, admin)
assert response.status_code == 400
@pytest.mark.django_db
@pytest.mark.parametrize('version', ['v1', 'v2'])
def test_sa_grant_private_credential_to_team_through_team_roles(post, credential, admin, team, version):
# not even a system admin can grant a private cred to a team though
response = post(reverse('api:role_teams_list', kwargs={'version': version, 'pk': team.id}), {
'id': credential.use_role.id
}, admin)
assert response.status_code == 400
#
# organization credentials
#
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {'username': 'someusername'}],
['v2', {'credential_type': 1, 'inputs': {'username': 'someusername'}}]
])
def test_create_org_credential_as_not_admin(post, organization, org_member, credentialtype_ssh, version, params):
params['name'] = 'Some name'
params['organization'] = organization.id
response = post(
reverse('api:credential_list'),
params,
org_member
)
assert response.status_code == 403
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {'username': 'someusername'}],
['v2', {'credential_type': 1, 'inputs': {'username': 'someusername'}}]
])
def test_create_org_credential_as_admin(post, organization, org_admin, credentialtype_ssh, version, params):
params['name'] = 'Some name'
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
org_admin
)
assert response.status_code == 201
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {'username': 'someusername'}],
['v2', {'credential_type': 1, 'inputs': {'username': 'someusername'}}]
])
def test_credential_detail(post, get, organization, org_admin, credentialtype_ssh, version, params):
params['name'] = 'Some name'
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
org_admin
)
assert response.status_code == 201
response = get(
reverse('api:credential_detail', kwargs={'version': version, 'pk': response.data['id']}),
org_admin
)
assert response.status_code == 200
summary_fields = response.data['summary_fields']
assert 'organization' in summary_fields
related_fields = response.data['related']
assert 'organization' in related_fields
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {'username': 'someusername'}],
['v2', {'credential_type': 1, 'inputs': {'username': 'someusername'}}]
])
def test_list_created_org_credentials(post, get, organization, org_admin, org_member, credentialtype_ssh, version, params):
params['name'] = 'Some name'
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
org_admin
)
assert response.status_code == 201
response = get(
reverse('api:credential_list', kwargs={'version': version}),
org_admin
)
assert response.status_code == 200
assert response.data['count'] == 1
response = get(
reverse('api:credential_list', kwargs={'version': version}),
org_member
)
assert response.status_code == 200
assert response.data['count'] == 0
response = get(
reverse('api:organization_credential_list', kwargs={'version': version, 'pk': organization.pk}),
org_admin
)
assert response.status_code == 200
assert response.data['count'] == 1
response = get(
reverse('api:organization_credential_list', kwargs={'version': version, 'pk': organization.pk}),
org_member
)
assert response.status_code == 200
assert response.data['count'] == 0
@pytest.mark.parametrize('order_by', ('password', '-password', 'password,pk', '-password,pk'))
@pytest.mark.parametrize('version', ('v1', 'v2'))
@pytest.mark.django_db
def test_list_cannot_order_by_encrypted_field(post, get, organization, org_admin, credentialtype_ssh, order_by, version):
for i, password in enumerate(('abc', 'def', 'xyz')):
response = post(
reverse('api:credential_list', kwargs={'version': version}),
{
'organization': organization.id,
'name': 'C%d' % i,
'password': password
},
org_admin
)
response = get(
reverse('api:credential_list', kwargs={'version': version}),
org_admin,
QUERY_STRING='order_by=%s' % order_by,
status=400
)
assert response.status_code == 400
@pytest.mark.django_db
def test_v1_credential_kind_validity(get, post, organization, admin, credentialtype_ssh):
params = {
'name': 'Best credential ever',
'organization': organization.id,
'kind': 'nonsense'
}
response = post(
reverse('api:credential_list', kwargs={'version': 'v1'}),
params,
admin
)
assert response.status_code == 400
assert response.data['kind'] == ['"nonsense" is not a valid choice']
@pytest.mark.django_db
def test_inputs_cannot_contain_extra_fields(get, post, organization, admin, credentialtype_ssh):
params = {
'name': 'Best credential ever',
'organization': organization.id,
'credential_type': credentialtype_ssh.pk,
'inputs': {
'invalid_field': 'foo'
},
}
response = post(
reverse('api:credential_list', kwargs={'version': 'v2'}),
params,
admin
)
assert response.status_code == 400
assert "'invalid_field' was unexpected" in response.data['inputs'][0]
@pytest.mark.django_db
@pytest.mark.parametrize('field_name, field_value', itertools.product(
['username', 'password', 'ssh_key_data', 'become_method', 'become_username', 'become_password'], # noqa
['', None]
))
def test_nullish_field_data(get, post, organization, admin, field_name, field_value):
ssh = CredentialType.defaults['ssh']()
ssh.save()
params = {
'name': 'Best credential ever',
'credential_type': ssh.pk,
'organization': organization.id,
'inputs': {
field_name: field_value
}
}
response = post(
reverse('api:credential_list', kwargs={'version': 'v2'}),
params,
admin
)
assert response.status_code == 201
assert Credential.objects.count() == 1
cred = Credential.objects.all()[:1].get()
assert getattr(cred, field_name) == ''
@pytest.mark.django_db
@pytest.mark.parametrize('field_value', ['', None, False])
def test_falsey_field_data(get, post, organization, admin, field_value):
net = CredentialType.defaults['net']()
net.save()
params = {
'name': 'Best credential ever',
'credential_type': net.pk,
'organization': organization.id,
'inputs': {
'username': 'joe-user', # username is required
'authorize': field_value
}
}
response = post(
reverse('api:credential_list', kwargs={'version': 'v2'}),
params,
admin
)
assert response.status_code == 201
assert Credential.objects.count() == 1
cred = Credential.objects.all()[:1].get()
assert cred.authorize is False
@pytest.mark.django_db
@pytest.mark.parametrize('kind, extraneous', [
['ssh', 'ssh_key_unlock'],
['scm', 'ssh_key_unlock'],
['net', 'ssh_key_unlock'],
['net', 'authorize_password'],
])
def test_field_dependencies(get, post, organization, admin, kind, extraneous):
_type = CredentialType.defaults[kind]()
_type.save()
params = {
'name': 'Best credential ever',
'credential_type': _type.pk,
'organization': organization.id,
'inputs': {extraneous: 'not needed'}
}
response = post(
reverse('api:credential_list', kwargs={'version': 'v2'}),
params,
admin
)
assert response.status_code == 400
assert re.search('cannot be set unless .+ is set.', response.content)
assert Credential.objects.count() == 0
#
# SCM Credentials
#
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'kind': 'scm',
'name': 'Best credential ever',
'username': 'some_username',
'password': 'some_password',
'ssh_key_data': EXAMPLE_ENCRYPTED_PRIVATE_KEY,
'ssh_key_unlock': 'some_key_unlock',
}],
['v2', {
'credential_type': 1,
'name': 'Best credential ever',
'inputs': {
'username': 'some_username',
'password': 'some_password',
'ssh_key_data': EXAMPLE_ENCRYPTED_PRIVATE_KEY,
'ssh_key_unlock': 'some_key_unlock',
}
}]
])
def test_scm_create_ok(post, organization, admin, version, params):
scm = CredentialType.defaults['scm']()
scm.save()
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 201
assert Credential.objects.count() == 1
cred = Credential.objects.all()[:1].get()
assert cred.inputs['username'] == 'some_username'
assert decrypt_field(cred, 'password') == 'some_password'
assert decrypt_field(cred, 'ssh_key_data') == EXAMPLE_ENCRYPTED_PRIVATE_KEY
assert decrypt_field(cred, 'ssh_key_unlock') == 'some_key_unlock'
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'kind': 'ssh',
'name': 'Best credential ever',
'password': 'secret',
'vault_password': '',
}],
['v2', {
'credential_type': 1,
'name': 'Best credential ever',
'inputs': {
'password': 'secret',
}
}]
])
def test_ssh_create_ok(post, organization, admin, version, params):
ssh = CredentialType.defaults['ssh']()
ssh.save()
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 201
assert Credential.objects.count() == 1
cred = Credential.objects.all()[:1].get()
assert cred.credential_type == ssh
assert decrypt_field(cred, 'password') == 'secret'
@pytest.mark.django_db
def test_v1_ssh_vault_ambiguity(post, organization, admin):
vault = CredentialType.defaults['vault']()
vault.save()
params = {
'organization': organization.id,
'kind': 'ssh',
'name': 'Best credential ever',
'username': 'joe',
'password': 'secret',
'ssh_key_data': 'some_key_data',
'ssh_key_unlock': 'some_key_unlock',
'vault_password': 'vault_password',
}
response = post(
reverse('api:credential_list', kwargs={'version': 'v1'}),
params,
admin
)
assert response.status_code == 400
#
# Vault Credentials
#
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'kind': 'ssh',
'name': 'Best credential ever',
'vault_password': 'some_password',
}],
['v2', {
'credential_type': 1,
'name': 'Best credential ever',
'inputs': {
'vault_password': 'some_password',
}
}]
])
def test_vault_create_ok(post, organization, admin, version, params):
vault = CredentialType.defaults['vault']()
vault.save()
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 201
assert Credential.objects.count() == 1
cred = Credential.objects.all()[:1].get()
assert decrypt_field(cred, 'vault_password') == 'some_password'
@pytest.mark.django_db
def test_vault_password_required(post, organization, admin):
vault = CredentialType.defaults['vault']()
vault.save()
response = post(
reverse('api:credential_list', kwargs={'version': 'v2'}),
{
'credential_type': vault.pk,
'organization': organization.id,
'name': 'Best credential ever',
'inputs': {}
},
admin
)
assert response.status_code == 400
assert response.data['inputs'] == {'vault_password': ['required for Vault']}
assert Credential.objects.count() == 0
#
# Net Credentials
#
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'kind': 'net',
'name': 'Best credential ever',
'username': 'some_username',
'password': 'some_password',
'ssh_key_data': EXAMPLE_ENCRYPTED_PRIVATE_KEY,
'ssh_key_unlock': 'some_key_unlock',
'authorize': True,
'authorize_password': 'some_authorize_password',
}],
['v2', {
'credential_type': 1,
'name': 'Best credential ever',
'inputs': {
'username': 'some_username',
'password': 'some_password',
'ssh_key_data': EXAMPLE_ENCRYPTED_PRIVATE_KEY,
'ssh_key_unlock': 'some_key_unlock',
'authorize': True,
'authorize_password': 'some_authorize_password',
}
}]
])
def test_net_create_ok(post, organization, admin, version, params):
net = CredentialType.defaults['net']()
net.save()
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 201
assert Credential.objects.count() == 1
cred = Credential.objects.all()[:1].get()
assert cred.inputs['username'] == 'some_username'
assert decrypt_field(cred, 'password') == 'some_password'
assert decrypt_field(cred, 'ssh_key_data') == EXAMPLE_ENCRYPTED_PRIVATE_KEY
assert decrypt_field(cred, 'ssh_key_unlock') == 'some_key_unlock'
assert decrypt_field(cred, 'authorize_password') == 'some_authorize_password'
assert cred.inputs['authorize'] is True
#
# Cloudforms Credentials
#
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'kind': 'cloudforms',
'name': 'Best credential ever',
'host': 'some_host',
'username': 'some_username',
'password': 'some_password',
}],
['v2', {
'credential_type': 1,
'name': 'Best credential ever',
'inputs': {
'host': 'some_host',
'username': 'some_username',
'password': 'some_password',
}
}]
])
def test_cloudforms_create_ok(post, organization, admin, version, params):
cloudforms = CredentialType.defaults['cloudforms']()
cloudforms.save()
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 201
assert Credential.objects.count() == 1
cred = Credential.objects.all()[:1].get()
assert cred.inputs['host'] == 'some_host'
assert cred.inputs['username'] == 'some_username'
assert decrypt_field(cred, 'password') == 'some_password'
#
# GCE Credentials
#
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'kind': 'gce',
'name': 'Best credential ever',
'username': 'some_username',
'project': 'some_project',
'ssh_key_data': EXAMPLE_PRIVATE_KEY,
}],
['v2', {
'credential_type': 1,
'name': 'Best credential ever',
'inputs': {
'username': 'some_username',
'project': 'some_project',
'ssh_key_data': EXAMPLE_PRIVATE_KEY,
}
}]
])
def test_gce_create_ok(post, organization, admin, version, params):
gce = CredentialType.defaults['gce']()
gce.save()
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 201
assert Credential.objects.count() == 1
cred = Credential.objects.all()[:1].get()
assert cred.inputs['username'] == 'some_username'
assert cred.inputs['project'] == 'some_project'
assert decrypt_field(cred, 'ssh_key_data') == EXAMPLE_PRIVATE_KEY
#
# Azure Resource Manager
#
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'kind': 'azure_rm',
'name': 'Best credential ever',
'subscription': 'some_subscription',
'username': 'some_username',
'password': 'some_password',
'client': 'some_client',
'secret': 'some_secret',
'tenant': 'some_tenant'
}],
['v2', {
'credential_type': 1,
'name': 'Best credential ever',
'inputs': {
'subscription': 'some_subscription',
'username': 'some_username',
'password': 'some_password',
'client': 'some_client',
'secret': 'some_secret',
'tenant': 'some_tenant'
}
}]
])
def test_azure_rm_create_ok(post, organization, admin, version, params):
azure_rm = CredentialType.defaults['azure_rm']()
azure_rm.save()
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 201
assert Credential.objects.count() == 1
cred = Credential.objects.all()[:1].get()
assert cred.inputs['subscription'] == 'some_subscription'
assert cred.inputs['username'] == 'some_username'
assert decrypt_field(cred, 'password') == 'some_password'
assert cred.inputs['client'] == 'some_client'
assert decrypt_field(cred, 'secret') == 'some_secret'
assert cred.inputs['tenant'] == 'some_tenant'
#
# RH Satellite6 Credentials
#
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'kind': 'satellite6',
'name': 'Best credential ever',
'host': 'some_host',
'username': 'some_username',
'password': 'some_password',
}],
['v2', {
'credential_type': 1,
'name': 'Best credential ever',
'inputs': {
'host': 'some_host',
'username': 'some_username',
'password': 'some_password',
}
}]
])
def test_satellite6_create_ok(post, organization, admin, version, params):
sat6 = CredentialType.defaults['satellite6']()
sat6.save()
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 201
assert Credential.objects.count() == 1
cred = Credential.objects.all()[:1].get()
assert cred.inputs['host'] == 'some_host'
assert cred.inputs['username'] == 'some_username'
assert decrypt_field(cred, 'password') == 'some_password'
#
# AWS Credentials
#
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'kind': 'aws',
'name': 'Best credential ever',
'username': 'some_username',
'password': 'some_password',
'security_token': 'abc123'
}],
['v2', {
'credential_type': 1,
'name': 'Best credential ever',
'inputs': {
'username': 'some_username',
'password': 'some_password',
'security_token': 'abc123'
}
}]
])
def test_aws_create_ok(post, organization, admin, version, params):
aws = CredentialType.defaults['aws']()
aws.save()
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 201
assert Credential.objects.count() == 1
cred = Credential.objects.all()[:1].get()
assert cred.inputs['username'] == 'some_username'
assert decrypt_field(cred, 'password') == 'some_password'
assert decrypt_field(cred, 'security_token') == 'abc123'
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'kind': 'aws',
'name': 'Best credential ever',
}],
['v2', {
'credential_type': 1,
'name': 'Best credential ever',
'inputs': {}
}]
])
def test_aws_create_fail_required_fields(post, organization, admin, version, params):
aws = CredentialType.defaults['aws']()
aws.save()
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 400
assert Credential.objects.count() == 0
errors = response.data
if version == 'v2':
errors = response.data['inputs']
assert errors['username'] == ['required for %s' % aws.name]
assert errors['password'] == ['required for %s' % aws.name]
#
# VMware vCenter Credentials
#
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'kind': 'vmware',
'host': 'some_host',
'name': 'Best credential ever',
'username': 'some_username',
'password': 'some_password'
}],
['v2', {
'credential_type': 1,
'name': 'Best credential ever',
'inputs': {
'host': 'some_host',
'username': 'some_username',
'password': 'some_password'
}
}]
])
def test_vmware_create_ok(post, organization, admin, version, params):
vmware = CredentialType.defaults['vmware']()
vmware.save()
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 201
assert Credential.objects.count() == 1
cred = Credential.objects.all()[:1].get()
assert cred.inputs['host'] == 'some_host'
assert cred.inputs['username'] == 'some_username'
assert decrypt_field(cred, 'password') == 'some_password'
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'kind': 'vmware',
'name': 'Best credential ever',
}],
['v2', {
'credential_type': 1,
'name': 'Best credential ever',
'inputs': {}
}]
])
def test_vmware_create_fail_required_fields(post, organization, admin, version, params):
vmware = CredentialType.defaults['vmware']()
vmware.save()
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 400
assert Credential.objects.count() == 0
errors = response.data
if version == 'v2':
errors = response.data['inputs']
assert errors['username'] == ['required for %s' % vmware.name]
assert errors['password'] == ['required for %s' % vmware.name]
assert errors['host'] == ['required for %s' % vmware.name]
#
# Openstack Credentials
#
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'username': 'some_user',
'password': 'some_password',
'project': 'some_project',
'host': 'some_host',
}],
['v2', {
'credential_type': 1,
'inputs': {
'username': 'some_user',
'password': 'some_password',
'project': 'some_project',
'host': 'some_host',
}
}]
])
def test_openstack_create_ok(post, organization, admin, version, params):
openstack = CredentialType.defaults['openstack']()
openstack.save()
params['kind'] = 'openstack'
params['name'] = 'Best credential ever'
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 201
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {}],
['v2', {
'credential_type': 1,
'inputs': {}
}]
])
def test_openstack_create_fail_required_fields(post, organization, admin, version, params):
openstack = CredentialType.defaults['openstack']()
openstack.save()
params['kind'] = 'openstack'
params['name'] = 'Best credential ever'
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 400
errors = response.data
if version == 'v2':
errors = response.data['inputs']
assert errors['username'] == ['required for %s' % openstack.name]
assert errors['password'] == ['required for %s' % openstack.name]
assert errors['host'] == ['required for %s' % openstack.name]
assert errors['project'] == ['required for %s' % openstack.name]
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'name': 'Best credential ever',
'kind': 'ssh',
'username': 'joe',
'password': '',
}],
['v2', {
'name': 'Best credential ever',
'credential_type': 1,
'inputs': {
'username': 'joe',
'password': '',
}
}]
])
def test_field_removal(put, organization, admin, credentialtype_ssh, version, params):
cred = Credential(
credential_type=credentialtype_ssh,
name='Best credential ever',
organization=organization,
inputs={
'username': u'jim',
'password': u'secret'
}
)
cred.save()
params['organization'] = organization.id
response = put(
reverse('api:credential_detail', kwargs={'version': version, 'pk': cred.pk}),
params,
admin
)
assert response.status_code == 200
cred = Credential.objects.all()[:1].get()
assert cred.inputs['username'] == 'joe'
assert 'password' not in cred.inputs
@pytest.mark.django_db
@pytest.mark.parametrize('relation, related_obj', [
['ad_hoc_commands', AdHocCommand()],
['insights_inventories', Inventory()],
['unifiedjobs', Job()],
['unifiedjobtemplates', JobTemplate()],
['unifiedjobtemplates', InventorySource()],
['projects', Project()],
['workflowjobnodes', WorkflowJobNode()],
])
def test_credential_type_mutability(patch, organization, admin, credentialtype_ssh,
credentialtype_aws, relation, related_obj):
cred = Credential(
credential_type=credentialtype_ssh,
name='Best credential ever',
organization=organization,
inputs={
'username': u'jim',
'password': u'pass'
}
)
cred.save()
related_obj.save()
getattr(cred, relation).add(related_obj)
def _change_credential_type():
return patch(
reverse('api:credential_detail', kwargs={'version': 'v2', 'pk': cred.pk}),
{
'credential_type': credentialtype_aws.pk,
'inputs': {
'username': u'jim',
'password': u'pass'
}
},
admin
)
response = _change_credential_type()
assert response.status_code == 400
expected = ['You cannot change the credential type of the credential, '
'as it may break the functionality of the resources using it.']
assert response.data['credential_type'] == expected
response = patch(
reverse('api:credential_detail', kwargs={'version': 'v2', 'pk': cred.pk}),
{'name': 'Worst credential ever'},
admin
)
assert response.status_code == 200
assert Credential.objects.get(pk=cred.pk).name == 'Worst credential ever'
related_obj.delete()
response = _change_credential_type()
assert response.status_code == 200
@pytest.mark.django_db
def test_vault_credential_type_mutability(patch, organization, admin, credentialtype_ssh,
credentialtype_vault):
cred = Credential(
credential_type=credentialtype_vault,
name='Best credential ever',
organization=organization,
inputs={
'vault_password': u'some-vault',
}
)
cred.save()
jt = JobTemplate()
jt.save()
jt.credentials.add(cred)
def _change_credential_type():
return patch(
reverse('api:credential_detail', kwargs={'version': 'v2', 'pk': cred.pk}),
{
'credential_type': credentialtype_ssh.pk,
'inputs': {
'username': u'jim',
'password': u'pass'
}
},
admin
)
response = _change_credential_type()
assert response.status_code == 400
expected = ['You cannot change the credential type of the credential, '
'as it may break the functionality of the resources using it.']
assert response.data['credential_type'] == expected
response = patch(
reverse('api:credential_detail', kwargs={'version': 'v2', 'pk': cred.pk}),
{'name': 'Worst credential ever'},
admin
)
assert response.status_code == 200
assert Credential.objects.get(pk=cred.pk).name == 'Worst credential ever'
jt.delete()
response = _change_credential_type()
assert response.status_code == 200
@pytest.mark.django_db
def test_cloud_credential_type_mutability(patch, organization, admin, credentialtype_ssh,
credentialtype_aws):
cred = Credential(
credential_type=credentialtype_aws,
name='Best credential ever',
organization=organization,
inputs={
'username': u'jim',
'password': u'pass'
}
)
cred.save()
jt = JobTemplate()
jt.save()
jt.credentials.add(cred)
def _change_credential_type():
return patch(
reverse('api:credential_detail', kwargs={'version': 'v2', 'pk': cred.pk}),
{
'credential_type': credentialtype_ssh.pk,
'inputs': {
'username': u'jim',
'password': u'pass'
}
},
admin
)
response = _change_credential_type()
assert response.status_code == 400
expected = ['You cannot change the credential type of the credential, '
'as it may break the functionality of the resources using it.']
assert response.data['credential_type'] == expected
response = patch(
reverse('api:credential_detail', kwargs={'version': 'v2', 'pk': cred.pk}),
{'name': 'Worst credential ever'},
admin
)
assert response.status_code == 200
assert Credential.objects.get(pk=cred.pk).name == 'Worst credential ever'
jt.delete()
response = _change_credential_type()
assert response.status_code == 200
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'name': 'Best credential ever',
'kind': 'ssh',
'username': 'joe',
'ssh_key_data': '$encrypted$',
}],
['v2', {
'name': 'Best credential ever',
'credential_type': 1,
'inputs': {
'username': 'joe',
'ssh_key_data': '$encrypted$',
}
}]
])
def test_ssh_unlock_needed(put, organization, admin, credentialtype_ssh, version, params):
cred = Credential(
credential_type=credentialtype_ssh,
name='Best credential ever',
organization=organization,
inputs={
'username': u'joe',<|fim▁hole|> 'ssh_key_data': EXAMPLE_ENCRYPTED_PRIVATE_KEY,
'ssh_key_unlock': 'unlock'
}
)
cred.save()
params['organization'] = organization.id
response = put(
reverse('api:credential_detail', kwargs={'version': version, 'pk': cred.pk}),
params,
admin
)
assert response.status_code == 400
assert response.data['inputs']['ssh_key_unlock'] == ['must be set when SSH key is encrypted.']
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'name': 'Best credential ever',
'kind': 'ssh',
'username': 'joe',
'ssh_key_data': '$encrypted$',
'ssh_key_unlock': 'superfluous-key-unlock',
}],
['v2', {
'name': 'Best credential ever',
'credential_type': 1,
'inputs': {
'username': 'joe',
'ssh_key_data': '$encrypted$',
'ssh_key_unlock': 'superfluous-key-unlock',
}
}]
])
def test_ssh_unlock_not_needed(put, organization, admin, credentialtype_ssh, version, params):
cred = Credential(
credential_type=credentialtype_ssh,
name='Best credential ever',
organization=organization,
inputs={
'username': u'joe',
'ssh_key_data': EXAMPLE_PRIVATE_KEY,
}
)
cred.save()
params['organization'] = organization.id
response = put(
reverse('api:credential_detail', kwargs={'version': version, 'pk': cred.pk}),
params,
admin
)
assert response.status_code == 400
assert response.data['inputs']['ssh_key_unlock'] == ['should not be set when SSH key is not encrypted.']
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'name': 'Best credential ever',
'kind': 'ssh',
'username': 'joe',
'ssh_key_data': '$encrypted$',
'ssh_key_unlock': 'new-unlock',
}],
['v2', {
'name': 'Best credential ever',
'credential_type': 1,
'inputs': {
'username': 'joe',
'ssh_key_data': '$encrypted$',
'ssh_key_unlock': 'new-unlock',
}
}]
])
def test_ssh_unlock_with_prior_value(put, organization, admin, credentialtype_ssh, version, params):
cred = Credential(
credential_type=credentialtype_ssh,
name='Best credential ever',
organization=organization,
inputs={
'username': u'joe',
'ssh_key_data': EXAMPLE_ENCRYPTED_PRIVATE_KEY,
'ssh_key_unlock': 'old-unlock'
}
)
cred.save()
params['organization'] = organization.id
response = put(
reverse('api:credential_detail', kwargs={'version': version, 'pk': cred.pk}),
params,
admin
)
assert response.status_code == 200
cred = Credential.objects.all()[:1].get()
assert decrypt_field(cred, 'ssh_key_unlock') == 'new-unlock'
#
# test secret encryption/decryption
#
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'kind': 'ssh',
'username': 'joe',
'password': 'secret',
}],
['v2', {
'credential_type': 1,
'inputs': {
'username': 'joe',
'password': 'secret',
}
}]
])
def test_secret_encryption_on_create(get, post, organization, admin, credentialtype_ssh, version, params):
params['name'] = 'Best credential ever'
params['organization'] = organization.id
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 201
response = get(
reverse('api:credential_list', kwargs={'version': version}),
admin
)
assert response.status_code == 200
assert response.data['count'] == 1
cred = response.data['results'][0]
if version == 'v1':
assert cred['username'] == 'joe'
assert cred['password'] == '$encrypted$'
elif version == 'v2':
assert cred['inputs']['username'] == 'joe'
assert cred['inputs']['password'] == '$encrypted$'
cred = Credential.objects.all()[:1].get()
assert cred.inputs['password'].startswith('$encrypted$UTF8$AES')
assert decrypt_field(cred, 'password') == 'secret'
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {'password': 'secret'}],
['v2', {'inputs': {'username': 'joe', 'password': 'secret'}}]
])
def test_secret_encryption_on_update(get, post, patch, organization, admin, credentialtype_ssh, version, params):
response = post(
reverse('api:credential_list', kwargs={'version': 'v2'}),
{
'name': 'Best credential ever',
'organization': organization.id,
'credential_type': 1,
'inputs': {
'username': 'joe',
}
},
admin
)
assert response.status_code == 201
response = patch(
reverse('api:credential_detail', kwargs={'pk': 1, 'version': version}),
params,
admin
)
assert response.status_code == 200
response = get(
reverse('api:credential_list', kwargs={'version': version}),
admin
)
assert response.status_code == 200
assert response.data['count'] == 1
cred = response.data['results'][0]
if version == 'v1':
assert cred['username'] == 'joe'
assert cred['password'] == '$encrypted$'
elif version == 'v2':
assert cred['inputs']['username'] == 'joe'
assert cred['inputs']['password'] == '$encrypted$'
cred = Credential.objects.all()[:1].get()
assert cred.inputs['password'].startswith('$encrypted$UTF8$AES')
assert decrypt_field(cred, 'password') == 'secret'
@pytest.mark.django_db
@pytest.mark.parametrize('version, params', [
['v1', {
'username': 'joe',
'password': '$encrypted$',
}],
['v2', {
'inputs': {
'username': 'joe',
'password': '$encrypted$',
}
}]
])
def test_secret_encryption_previous_value(patch, organization, admin, credentialtype_ssh, version, params):
cred = Credential(
credential_type=credentialtype_ssh,
name='Best credential ever',
organization=organization,
inputs={
'username': u'jim',
'password': u'secret'
}
)
cred.save()
assert decrypt_field(cred, 'password') == 'secret'
response = patch(
reverse('api:credential_detail', kwargs={'pk': cred.pk, 'version': version}),
params,
admin
)
assert response.status_code == 200
cred = Credential.objects.all()[:1].get()
assert cred.inputs['username'] == 'joe'
assert cred.inputs['password'].startswith('$encrypted$UTF8$AES')
assert decrypt_field(cred, 'password') == 'secret'
@pytest.mark.django_db
def test_custom_credential_type_create(get, post, organization, admin):
credential_type = CredentialType(
kind='cloud',
name='MyCloud',
inputs = {
'fields': [{
'id': 'api_token',
'label': 'API Token',
'type': 'string',
'secret': True
}]
}
)
credential_type.save()
params = {
'name': 'Best credential ever',
'organization': organization.pk,
'credential_type': credential_type.pk,
'inputs': {
'api_token': 'secret'
}
}
response = post(
reverse('api:credential_list', kwargs={'version': 'v2'}),
params,
admin
)
assert response.status_code == 201
response = get(
reverse('api:credential_list', kwargs={'version': 'v2'}),
admin
)
assert response.status_code == 200
assert response.data['count'] == 1
cred = response.data['results'][0]
assert cred['inputs']['api_token'] == '$encrypted$'
cred = Credential.objects.all()[:1].get()
assert cred.inputs['api_token'].startswith('$encrypted$UTF8$AES')
assert decrypt_field(cred, 'api_token') == 'secret'
#
# misc xfail conditions
#
@pytest.mark.parametrize('version, params', [
['v1', {'name': 'Some name', 'username': 'someusername'}],
['v2', {'name': 'Some name', 'credential_type': 1, 'inputs': {'username': 'someusername'}}]
])
@pytest.mark.django_db
def test_create_credential_missing_user_team_org_xfail(post, admin, credentialtype_ssh, version, params):
# Must specify one of user, team, or organization
response = post(
reverse('api:credential_list', kwargs={'version': version}),
params,
admin
)
assert response.status_code == 400<|fim▁end|> | |
<|file_name|>elasticbeanstalk.rs<|end_file_name|><|fim▁begin|>#![cfg(feature = "elasticbeanstalk")]
extern crate rusoto;
use rusoto::elasticbeanstalk::{ElasticBeanstalk, ElasticBeanstalkClient,
DescribeApplicationsMessage};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
#[test]
fn should_describe_applications() {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client =
ElasticBeanstalkClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
let request = DescribeApplicationsMessage::default();
let result = client.describe_applications(&request).unwrap();
println!("{:#?}", result);<|fim▁hole|><|fim▁end|> | } |
<|file_name|>level3_model.py<|end_file_name|><|fim▁begin|>from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import xgboost as xgb
import argparse
from os import path
import os
from hyperopt import fmin, tpe, hp, STATUS_OK, Trials
from utils import *
import pickle
np.random.seed(345345)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--yix', type=int, default=0)
return parser.parse_args()
# functions for xgboost training
def evalF1(preds, dtrain):
from sklearn.metrics import f1_score
labels = dtrain.get_label()
return 'f1-score', f1_score(labels, preds > 0.5)
def fpreproc(dtrain, dtest, param):
label = dtrain.get_label()
ratio = float(np.sum(label == 0)) / np.sum(label == 1)
param['scale_pos_weight'] = ratio
return (dtrain, dtest, param)
# functions for hyperparameters optimization
class Score:
def __init__(self, X, y):
self.dtrain = xgb.DMatrix(X, label=y)
def get_score(self, params):
params['max_depth'] = int(params['max_depth'])
params['min_child_weight'] = int(params['min_child_weight'])
params['num_boost_round'] = int(params['num_boost_round'])
print('Training with params:')
print(params)
cv_result = xgb.cv(params=params,
dtrain=self.dtrain,
num_boost_round=params['num_boost_round'],
nfold=5,
stratified=True,
feval=evalF1,
maximize=True,
fpreproc=fpreproc,
verbose_eval=True)
score = cv_result.ix[params['num_boost_round'] - 1, 0]
print(score)
return {'loss': -score, 'status': STATUS_OK}
def optimize(trials, X, y, max_evals):
space = {
'num_boost_round': hp.quniform('num_boost_round', 10, 200, 10),
'eta': hp.quniform('eta', 0.1, 0.3, 0.1),
'gamma': hp.quniform('gamma', 0, 1, 0.2),
'max_depth': hp.quniform('max_depth', 1, 6, 1),
'min_child_weight': hp.quniform('min_child_weight', 1, 3, 1),
'subsample': hp.quniform('subsample', 0.8, 1, 0.1),
'silent': 1,
'objective': 'binary:logistic'
}
s = Score(X, y)
best = fmin(s.get_score,
space,
algo=tpe.suggest,
trials=trials,
max_evals=max_evals
)
best['max_depth'] = int(best['max_depth'])
best['min_child_weight'] = int(best['min_child_weight'])
best['num_boost_round'] = int(best['num_boost_round'])
del s
return best
def out_fold_pred(params, X, y, reps):
preds = np.zeros((y.shape[0]))
params['silent'] = 1
params['objective'] = 'binary:logistic'
params['scale_pos_weight'] = float(np.sum(y == 0)) / np.sum(y == 1)
for train_ix, test_ix in makeKFold(5, y, reps):
X_train, X_test = X[train_ix, :], X[test_ix, :]
y_train = y[train_ix]
dtrain = xgb.DMatrix(X_train, label=y_train)
dtest = xgb.DMatrix(X_test)
bst = xgb.train(params=params,
dtrain=dtrain,
num_boost_round=params['num_boost_round'],
evals=[(dtrain, 'train')],
feval=evalF1,
maximize=True,
verbose_eval=None)
preds[test_ix] = bst.predict(dtest)
return preds
def get_model(params, X, y):
dtrain = xgb.DMatrix(X, label=y)
params['silent'] = 1
params['objective'] = 'binary:logistic'
params['scale_pos_weight'] = float(np.sum(y == 0)) / np.sum(y == 1)
bst = xgb.train(params=params,
dtrain=dtrain,
num_boost_round=params['num_boost_round'],
evals=[(dtrain, 'train')],
feval=evalF1,
maximize=True,
verbose_eval=None)
return bst
args = parse_args()
data_dir = '../level3-feature/' + str(args.yix)
X_train = np.load(path.join(data_dir, 'X_train.npy'))
X_test = np.load(path.join(data_dir, 'X_test.npy'))
y_train = np.load(path.join(data_dir, 'y_train.npy'))
print(X_train.shape, X_test.shape, y_train.shape)
X_train_ext = np.load('../extra_ftrs/' + str(args.yix) + '/X_train_ext.npy')
X_test_ext = np.load('../extra_ftrs/' + str(args.yix) + '/X_test_ext.npy')
print(X_train_ext.shape, X_test_ext.shape)
X_train = np.hstack((X_train, X_train_ext))
X_test = np.hstack((X_test, X_test_ext))
print('Add Extra')
print(X_train.shape, X_test.shape, y_train.shape)
trials = Trials()
params = optimize(trials, X_train, y_train, 100)
out_fold = out_fold_pred(params, X_train, y_train, 1)
clf = get_model(params, X_train, y_train)
dtest = xgb.DMatrix(X_test)
preds = clf.predict(dtest)
save_dir = '../level3-model-final/' + str(args.yix)
print(save_dir)
if not path.exists(save_dir):
os.makedirs(save_dir)
# save model, parameter, outFold_pred, pred
with open(path.join(save_dir, 'model.pkl'), 'wb') as f_model:
pickle.dump(clf, f_model)<|fim▁hole|> pickle.dump(params, f_param)
np.save(path.join(save_dir, 'pred.npy'), preds)
np.save(path.join(save_dir, 'outFold.npy'), out_fold)<|fim▁end|> |
with open(path.join(save_dir, 'param.pkl'), 'wb') as f_param: |
<|file_name|>app.ts<|end_file_name|><|fim▁begin|>//Question class w/constructor
class Question {
constructor(public ask: string,
public answerChoiceA: string,
public answerChoiceB: string,
public answerChoiceC: string,
public correctAnswer: string,
public points: number = 20) {
}
}
//Question bank with answer choices, correct answer, and initial point values
let q01 = new Question("What is the capital of Texas?", "A. Dallas", "B. Houston", "C. Austin", "C", 20);
let q02 = new Question("What is the opposite of down?", "A. Up", "B. Left", "C. Right", "A", 20);
let q03 = new Question("What is 2+2?", "A. 2", "B. 3", "C. 4", "C", 20);
let q04 = new Question("Blue and yellow makes what?", "A. Green", "B. Brown", "C. Red", "A", 20);
let q05 = new Question("How many sides to a square?", "A. 4", " B. 3", "C. 2", "A", 20);
//Initailize running total score
let quizScore: number = 0;
//Each question has it's own function 1111111111111111111111111111111111111111
function question01() {
//Promopt user for answer to question.
let result01: string = window.prompt(`Question 1: (${q01.points} points)
${q01.ask}
${q01.answerChoiceA}
${q01.answerChoiceB}
${q01.answerChoiceC}`,
`Your answer: A, B, or C (NOT case sensitive)`);
//In-process user answer
let _result01 = result01.toUpperCase();
//Show positive result
if (_result01 === q01.correctAnswer) {
//Increase running total score by current question value
quizScore = quizScore + q01.points;
alert(`That's correct!
You earned (${q01.points}) points.
Total quiz score so far: ${quizScore}`);
}
//Show negative result//
else {
//Reduce question value by 1 and ....
q01.points = q01.points - 1;
alert(`Oops... wrong answer.
Hit "OK" to try again.
Total quiz score so far: ${quizScore}`);
//.... try again
question01();
};
};
//2222222222222222222222222222222222222222222222222222222222222222222222222222
function question02() {
//Promopt user for answer to question
let result02: string = window.prompt(`Question 2: (${q02.points} points)
${q02.ask}
${q02.answerChoiceA}
${q02.answerChoiceB}
${q02.answerChoiceC}`,
`Your answer: A, B, or C (NOT case sensitive)`);
//In-process user answer
let _result02 = result02.toUpperCase();
//Show positive result
if (_result02 === q02.correctAnswer) {
//Increase running total score by current question value
quizScore = quizScore + q02.points;
alert(`That's correct!
You earned (${q02.points}) points.
Total quiz score so far: ${quizScore}`);
}
//Show negative result//
else {
//Reduce question value by 1 and ....
q02.points = q02.points - 1;
alert(`Oops... wrong answer.
Hit "OK" to try again.
Total quiz score so far: ${quizScore}`);
//.... try again
question02();
};
};
//3333333333333333333333333333333333333333333333333333333333333333333333333333
function question03() {
//Promopt user for answer to question
let result03: string = window.prompt(`Question 3: (${q03.points} points)
${q03.ask}
${q03.answerChoiceA}
${q03.answerChoiceB}
${q03.answerChoiceC}`,
`Your answer: A, B, or C (NOT case sensitive)`);
//In-process user answer
let _result03 = result03.toUpperCase();
//Show positive result
if (_result03 === q03.correctAnswer) {
//Increase running total score by current question value
quizScore = quizScore + q03.points;
alert(`That's correct!
You earned (${q03.points}) points.
Total quiz score so far: ${quizScore}`);
}
//Show negative result//
else {
//Reduce question value by 1 and ....
q03.points = q03.points - 1;
alert(`Oops... wrong answer.
Hit "OK" to try again.
Total quiz score so far: ${quizScore}`);
//.... try again
question03();
};
//Function 4444444444444444444444444444444444444444444444444444444444444444
};function question04() {
//Promopt user for answer to question
let result04: string = window.prompt(`Question 4: (${q04.points} points)
${q04.ask}
${q04.answerChoiceA}
${q04.answerChoiceB}
${q04.answerChoiceC}`,
`Your answer: A, B, or C (NOT case sensitive)`);
//In-process user answer
let _result04 = result04.toUpperCase();
//Show positive result
if (_result04 === q04.correctAnswer) {
//Increase running total score by current question value
quizScore = quizScore + q04.points;
alert(`That's correct!
You earned (${q04.points}) points.
Total quiz score so far: ${quizScore}`);
}
//Show negative result//
else {
//Reduce question value by 1 and ....
q04.points = q04.points - 1;
alert(`Oops... wrong answer.
Hit "OK" to try again.
Total quiz score so far: ${quizScore}`);
//.... try again
question04();
};
};
// Function 555555555555555555555555555555555555555555555555555555555555555555
function question05() {
//Promopt user for answer to question
let result05: string = window.prompt(`Question 5: (${q05.points} points)
${q05.ask}
${q05.answerChoiceA}
${q05.answerChoiceB}
${q05.answerChoiceC}`,
`Your answer: A, B, or C (NOT case sensitive)`);
//In-process user answer
let _result05 = result05.toUpperCase();
//Show positive result
if (_result05 === q05.correctAnswer) {
//Increase running total score by current question value
quizScore = quizScore + q05.points;
alert(`That's correct!
You earned (${q05.points}) points.
Total quiz score so far: ${quizScore}`);
}
//Show negative result//
else {
//Reduce question value by 1 and ....
q05.points = q05.points - 1;<|fim▁hole|>
Total quiz score so far: ${quizScore}`);
//.... try again
question05();
};
};
question01();
question02();
question03();
question04();
question05();
alert(`That all folks....
Final quiz score : ${quizScore}`);<|fim▁end|> | alert(`Oops... wrong answer.
Hit "OK" to try again. |
<|file_name|>NoMoreTextException.java<|end_file_name|><|fim▁begin|>/*
* Copyright (c) 2012 M. M. Naseri <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this<|fim▁hole|> * conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*/
package com.agileapes.powerpack.string.exception;
/**
* @author Mohammad Milad Naseri ([email protected])
* @since 1.0 (2012/12/3, 17:47)
*/
public class NoMoreTextException extends DocumentReaderException {
private static final long serialVersionUID = -1822455471711418794L;
public NoMoreTextException() {
}
public NoMoreTextException(String message) {
super(message);
}
}<|fim▁end|> | * software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following |
<|file_name|>test_artificial_128_Logit_MovingAverage_12_12_100.py<|end_file_name|><|fim▁begin|>import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art<|fim▁hole|>
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 12, transform = "Logit", sigma = 0.0, exog_count = 100, ar_order = 12);<|fim▁end|> | |
<|file_name|>Font.cpp<|end_file_name|><|fim▁begin|>// Font.cpp: ActionScript Font handling, for Gnash.
//
// Copyright (C) 2006, 2007, 2008, 2009, 2010 Free Software
// Foundation, Inc
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// Based on the public domain work of Thatcher Ulrich <[email protected]> 2003
#include "smart_ptr.h" // GNASH_USE_GC
#include "Font.h"
#include "log.h"
#include "ShapeRecord.h"
#include "DefineFontTag.h"
#include "FreetypeGlyphsProvider.h"
#include <utility> // for std::make_pair
#include <memory>
namespace gnash {
namespace {
/// Reverse lookup of Glyph in CodeTable.
//
/// Inefficient, which is probably why TextSnapshot was designed like it
/// is.
class CodeLookup
{
public:
CodeLookup(const int glyph) : _glyph(glyph) {}
bool operator()(const std::pair<const boost::uint16_t, int>& p) {
return p.second == _glyph;
}
private:
int _glyph;
};
}
Font::GlyphInfo::GlyphInfo()
:
advance(0)
{}
Font::GlyphInfo::GlyphInfo(std::auto_ptr<SWF::ShapeRecord> glyph,
float advance)
:
glyph(glyph.release()),
advance(advance)
{}
Font::GlyphInfo::GlyphInfo(const GlyphInfo& o)
:
glyph(o.glyph),
advance(o.advance)
{}
Font::Font(std::auto_ptr<SWF::DefineFontTag> ft)
:
_fontTag(ft.release()),
_name(_fontTag->name()),
_unicodeChars(_fontTag->unicodeChars()),
_shiftJISChars(_fontTag->shiftJISChars()),
_ansiChars(_fontTag->ansiChars()),
_italic(_fontTag->italic()),
_bold(_fontTag->bold())
{
if (_fontTag->hasCodeTable()) _embeddedCodeTable = _fontTag->getCodeTable();
}
Font::Font(const std::string& name, bool bold, bool italic)
:
_fontTag(0),
_name(name),
_unicodeChars(false),
_shiftJISChars(false),
_ansiChars(true),
_italic(italic),
_bold(bold)
{
assert(!_name.empty());
}
Font::~Font()
{
}
SWF::ShapeRecord*
Font::get_glyph(int index, bool embedded) const
{
// What to do if embedded is true and this is a
// device-only font?
const GlyphInfoRecords& lookup = (embedded && _fontTag) ?
_fontTag->glyphTable() : _deviceGlyphTable;
if (index >= 0 && (size_t)index < lookup.size()) {
return lookup[index].glyph.get();
}
// TODO: should we log an error here ?
return 0;
}
void
Font::addFontNameInfo(const FontNameInfo& fontName)
{
if (!_displayName.empty() || !_copyrightName.empty())
{
IF_VERBOSE_MALFORMED_SWF(
log_swferror(_("Attempt to set font display or copyright name "
"again. This should mean there is more than one "
"DefineFontName tag referring to the same Font. Don't "
"know what to do in this case, so ignoring."));
);
return;
}
_displayName = fontName.displayName;
_copyrightName = fontName.copyrightName;
}
Font::GlyphInfoRecords::size_type
Font::glyphCount() const
{
assert(_fontTag);
return _fontTag->glyphTable().size();
}
void
Font::setFlags(boost::uint8_t flags)
{
_shiftJISChars = flags & (1 << 6);
_unicodeChars = flags & (1 << 5);
_ansiChars = flags & (1 << 4);
_italic = flags & (1 << 1);
_bold = flags & (1 << 0);
}
void
Font::setCodeTable(std::auto_ptr<CodeTable> table)
{
if (_embeddedCodeTable)
{
IF_VERBOSE_MALFORMED_SWF(
log_swferror(_("Attempt to add an embedded glyph CodeTable to "
"a font that already has one. This should mean there "
"are several DefineFontInfo tags, or a DefineFontInfo "
"tag refers to a font created by DefineFone2 or "
"DefineFont3. Don't know what should happen in this "
"case, so ignoring."));
);
return;
}
_embeddedCodeTable.reset(table.release());
}
void
Font::setName(const std::string& name)
{
_name = name;
}
boost::uint16_t
Font::codeTableLookup(int glyph, bool embedded) const
{
const CodeTable& ctable = (embedded && _embeddedCodeTable) ?
*_embeddedCodeTable : _deviceCodeTable;
CodeTable::const_iterator it = std::find_if(ctable.begin(), ctable.end(),
CodeLookup(glyph));
assert (it != ctable.end());
return it->first;
}
int
Font::get_glyph_index(boost::uint16_t code, bool embedded) const
{
const CodeTable& ctable = (embedded && _embeddedCodeTable) ?
*_embeddedCodeTable : _deviceCodeTable;
int glyph_index = -1;
CodeTable::const_iterator it = ctable.find(code);
if (it != ctable.end()) {
glyph_index = it->second;
return glyph_index;
}
// Try adding an os font, if possible
if (!embedded) {
glyph_index = const_cast<Font*>(this)->add_os_glyph(code);
}
return glyph_index;
}
float
Font::get_advance(int glyph_index, bool embedded) const
{
// What to do if embedded is true and this is a
// device-only font?
const GlyphInfoRecords& lookup = (embedded && _fontTag) ?
_fontTag->glyphTable() : _deviceGlyphTable;
if (glyph_index < 0) {
// Default advance.
return 512.0f;
}
assert(static_cast<size_t>(glyph_index) < lookup.size());
assert(glyph_index >= 0);
return lookup[glyph_index].advance;
}
// Return the adjustment in advance between the given two
// DisplayObjects. Normally this will be 0; i.e. the
float
Font::get_kerning_adjustment(int last_code, int code) const
{
kerning_pair k;
k.m_char0 = last_code;
k.m_char1 = code;
kernings_table::const_iterator it = m_kerning_pairs.find(k);
if (it != m_kerning_pairs.end()) {
float adjustment = it->second;
return adjustment;
}
return 0;
}
size_t
Font::unitsPerEM(bool embed) const
{
// the EM square is 1024 x 1024 for DefineFont up to 2
// and 20 as much for DefineFont3 up
if (embed) {
if ( _fontTag && _fontTag->subpixelFont() ) return 1024 * 20.0;
else return 1024;
}
FreetypeGlyphsProvider* ft = ftProvider();
if (!ft) {
log_error("Device font provider was not initialized, "
"can't get unitsPerEM");
return 0;
}
return ft->unitsPerEM();
}
int
Font::add_os_glyph(boost::uint16_t code)
{
FreetypeGlyphsProvider* ft = ftProvider();
if (!ft) return -1;
<|fim▁hole|> assert(_deviceCodeTable.find(code) == _deviceCodeTable.end());
float advance;
// Get the vectorial glyph
std::auto_ptr<SWF::ShapeRecord> sh = ft->getGlyph(code, advance);
if (!sh.get()) {
log_error("Could not create shape "
"glyph for DisplayObject code %u (%c) with "
"device font %s (%p)", code, code, _name, ft);
return -1;
}
// Find new glyph offset
int newOffset = _deviceGlyphTable.size();
// Add the new glyph id
_deviceCodeTable[code] = newOffset;
_deviceGlyphTable.push_back(GlyphInfo(sh, advance));
return newOffset;
}
bool
Font::matches(const std::string& name, bool bold, bool italic) const
{
return (_bold == bold && _italic == italic && name ==_name);
}
float
Font::leading() const {
return _fontTag ? _fontTag->leading() : 0.0f;
}
FreetypeGlyphsProvider*
Font::ftProvider() const
{
if (_ftProvider.get()) return _ftProvider.get();
if (_name.empty()) {
log_error("No name associated with this font, can't use device "
"fonts (should I use a default one?)");
return 0;
}
_ftProvider = FreetypeGlyphsProvider::createFace(_name, _bold, _italic);
if (!_ftProvider.get()) {
log_error("Could not create a freetype face %s", _name);
return 0;
}
return _ftProvider.get();
}
float
Font::ascent(bool embedded) const
{
if (embedded && _fontTag) return _fontTag->ascent();
FreetypeGlyphsProvider* ft = ftProvider();
if (ft) return ft->ascent();
return 0;
}
float
Font::descent(bool embedded) const
{
if (embedded && _fontTag) return _fontTag->descent();
FreetypeGlyphsProvider* ft = ftProvider();
if (ft) return ft->descent();
return 0;
}
bool
Font::is_subpixel_font() const {
return _fontTag ? _fontTag->subpixelFont() : false;
}
} // namespace gnash
// Local Variables:
// mode: C++
// indent-tabs-mode: t
// End:<|fim▁end|> | |
<|file_name|>base-platform.ts<|end_file_name|><|fim▁begin|>import { ExecuteInCurrentWindow, Inject, mutation, StatefulService } from 'services/core';<|fim▁hole|> TPlatformCapability,
TStartStreamOptions,
TPlatformCapabilityMap,
} from './index';
import { StreamingService } from 'services/streaming';
import { UserService } from 'services/user';
import { HostsService } from 'services/hosts';
import electron from 'electron';
import { IFacebookStartStreamOptions } from './facebook';
import { StreamSettingsService } from '../settings/streaming';
const VIEWER_COUNT_UPDATE_INTERVAL = 60 * 1000;
/**
* Base class for platforms
* Keeps shared code for all platforms
*/
export abstract class BasePlatformService<T extends IPlatformState> extends StatefulService<T> {
static initialState: IPlatformState = {
streamKey: '',
viewersCount: 0,
settings: null,
isPrepopulated: false,
};
@Inject() protected streamingService: StreamingService;
@Inject() protected userService: UserService;
@Inject() protected hostsService: HostsService;
@Inject() protected streamSettingsService: StreamSettingsService;
abstract readonly platform: TPlatform;
abstract capabilities: Set<TPlatformCapability>;
@ExecuteInCurrentWindow()
hasCapability<T extends TPlatformCapability>(capability: T): this is TPlatformCapabilityMap[T] {
return this.capabilities.has(capability);
}
get mergeUrl() {
const host = this.hostsService.streamlabs;
const token = this.userService.apiToken;
return `https://${host}/slobs/merge/${token}/${this.platform}_account`;
}
averageViewers: number;
peakViewers: number;
private nViewerSamples: number;
async afterGoLive(): Promise<void> {
this.averageViewers = 0;
this.peakViewers = 0;
this.nViewerSamples = 0;
// update viewers count
const runInterval = async () => {
if (this.hasCapability('viewerCount')) {
const count = await this.fetchViewerCount();
this.nViewerSamples += 1;
this.averageViewers =
(this.averageViewers * (this.nViewerSamples - 1) + count) / this.nViewerSamples;
this.peakViewers = Math.max(this.peakViewers, count);
this.SET_VIEWERS_COUNT(count);
}
// stop updating if streaming has stopped
if (this.streamingService.views.isMidStreamMode) {
setTimeout(runInterval, VIEWER_COUNT_UPDATE_INTERVAL);
}
};
if (this.hasCapability('viewerCount')) await runInterval();
}
unlink() {
// unlink platform and reload auth state
// const url = `https://${this.hostsService.streamlabs}/api/v5/slobs/unlink/${this.platform}_account`;
// const headers = authorizedHeaders(this.userService.apiToken!);
// const request = new Request(url, { headers });
// return fetch(request)
// .then(handleResponse)
// .then(_ => this.userService.updateLinkedPlatforms());
electron.remote.shell.openExternal(
`https://${this.hostsService.streamlabs}/dashboard#/settings/account-settings`,
);
}
protected syncSettingsWithLocalStorage() {
// save settings to the local storage
const savedSettings: IFacebookStartStreamOptions = JSON.parse(
localStorage.getItem(this.serviceName) as string,
);
if (savedSettings) this.UPDATE_STREAM_SETTINGS(savedSettings);
this.store.watch(
() => this.state.settings,
() => {
localStorage.setItem(this.serviceName, JSON.stringify(this.state.settings));
},
{ deep: true },
);
}
async validatePlatform() {
return EPlatformCallResult.Success;
}
fetchUserInfo() {
return Promise.resolve({});
}
@mutation()
protected SET_VIEWERS_COUNT(viewers: number) {
this.state.viewersCount = viewers;
}
@mutation()
protected SET_STREAM_KEY(key: string) {
this.state.streamKey = key;
}
@mutation()
protected SET_PREPOPULATED(isPrepopulated: boolean) {
this.state.isPrepopulated = isPrepopulated;
}
@mutation()
protected SET_STREAM_SETTINGS(settings: TStartStreamOptions) {
this.state.settings = settings;
}
@mutation()
protected UPDATE_STREAM_SETTINGS(settingsPatch: Partial<TStartStreamOptions>) {
this.state.settings = { ...this.state.settings, ...settingsPatch };
}
}<|fim▁end|> | import {
EPlatformCallResult,
IPlatformState,
TPlatform, |
<|file_name|>RealmList.cpp<|end_file_name|><|fim▁begin|>/*
* This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/** \file
\ingroup realmd
*/
#include "Common.h"
#include "RealmList.h"
#include "AuthCodes.h"
#include "Util.h" // for Tokens typedef
#include "Policies/Singleton.h"
#include "Database/DatabaseEnv.h"
INSTANTIATE_SINGLETON_1(RealmList);
extern DatabaseType LoginDatabase;
// will only support WoW 1.12.1/1.12.2/1.12.3 , WoW:TBC 2.4.3 and official release for WoW:WotLK and later, client builds 10505, 8606, 6141, 6005, 5875
// if you need more from old build then add it in cases in realmd sources code
// list sorted from high to low build and first build used as low bound for accepted by default range (any > it will accepted by realmd at least)
static RealmBuildInfo ExpectedRealmdClientBuilds[] =
{
{12340, 3, 3, 5, 'a'}, // highest supported build, also auto accept all above for simplify future supported builds testing
{11723, 3, 3, 3, 'a'},
{11403, 3, 3, 2, ' '},
{11159, 3, 3, 0, 'a'},
{10505, 3, 2, 2, 'a'},
{8606, 2, 4, 3, ' '},
{6141, 1, 12, 3, ' '},
{6005, 1, 12, 2, ' '},
{5875, 1, 12, 1, ' '},
{0, 0, 0, 0, ' '} // terminator
};
RealmBuildInfo const* FindBuildInfo(uint16 _build)
{
// first build is low bound of always accepted range
if (_build >= ExpectedRealmdClientBuilds[0].build)
return &ExpectedRealmdClientBuilds[0];
// continue from 1 with explicit equal check
for (int i = 1; ExpectedRealmdClientBuilds[i].build; ++i)
if (_build == ExpectedRealmdClientBuilds[i].build)
return &ExpectedRealmdClientBuilds[i];
// none appropriate build
return nullptr;
}
RealmList::RealmList() : m_UpdateInterval(0), m_NextUpdateTime(time(nullptr))
{
}
RealmList& sRealmList
{
static RealmList realmlist;
return realmlist;
}
/// Load the realm list from the database
void RealmList::Initialize(uint32 updateInterval)
{
m_UpdateInterval = updateInterval;
///- Get the content of the realmlist table in the database
UpdateRealms(true);
}
void RealmList::UpdateRealm(uint32 ID, const std::string& name, const std::string& address, uint32 port, uint8 icon, RealmFlags realmflags, uint8 timezone, AccountTypes allowedSecurityLevel, float popu, const std::string& builds)
{
///- Create new if not exist or update existed
Realm& realm = m_realms[name];
realm.m_ID = ID;
realm.icon = icon;
<|fim▁hole|> realm.allowedSecurityLevel = allowedSecurityLevel;
realm.populationLevel = popu;
Tokens tokens = StrSplit(builds, " ");
Tokens::iterator iter;
for (iter = tokens.begin(); iter != tokens.end(); ++iter)
{
uint32 build = atol((*iter).c_str());
realm.realmbuilds.insert(build);
}
uint16 first_build = !realm.realmbuilds.empty() ? *realm.realmbuilds.begin() : 0;
realm.realmBuildInfo.build = first_build;
realm.realmBuildInfo.major_version = 0;
realm.realmBuildInfo.minor_version = 0;
realm.realmBuildInfo.bugfix_version = 0;
realm.realmBuildInfo.hotfix_version = ' ';
if (first_build)
if (RealmBuildInfo const* bInfo = FindBuildInfo(first_build))
if (bInfo->build == first_build)
realm.realmBuildInfo = *bInfo;
///- Append port to IP address.
std::ostringstream ss;
ss << address << ":" << port;
realm.address = ss.str();
}
void RealmList::UpdateIfNeed()
{
// maybe disabled or updated recently
if (!m_UpdateInterval || m_NextUpdateTime > time(nullptr))
return;
m_NextUpdateTime = time(nullptr) + m_UpdateInterval;
// Clears Realm list
m_realms.clear();
// Get the content of the realmlist table in the database
UpdateRealms(false);
}
void RealmList::UpdateRealms(bool init)
{
DETAIL_LOG("Updating Realm List...");
//// 0 1 2 3 4 5 6 7 8 9
QueryResult* result = LoginDatabase.Query("SELECT id, name, address, port, icon, realmflags, timezone, allowedSecurityLevel, population, realmbuilds FROM realmlist WHERE (realmflags & 1) = 0 ORDER BY name");
///- Circle through results and add them to the realm map
if (result)
{
do
{
Field* fields = result->Fetch();
uint32 Id = fields[0].GetUInt32();
std::string name = fields[1].GetCppString();
uint8 realmflags = fields[5].GetUInt8();
uint8 allowedSecurityLevel = fields[7].GetUInt8();
if (realmflags & ~(REALM_FLAG_OFFLINE | REALM_FLAG_NEW_PLAYERS | REALM_FLAG_RECOMMENDED | REALM_FLAG_SPECIFYBUILD))
{
sLog.outError("Realm (id %u, name '%s') can only be flagged as OFFLINE (mask 0x02), NEWPLAYERS (mask 0x20), RECOMMENDED (mask 0x40), or SPECIFICBUILD (mask 0x04) in DB", Id, name.c_str());
realmflags &= (REALM_FLAG_OFFLINE | REALM_FLAG_NEW_PLAYERS | REALM_FLAG_RECOMMENDED | REALM_FLAG_SPECIFYBUILD);
}
UpdateRealm(
Id, name, fields[2].GetCppString(), fields[3].GetUInt32(),
fields[4].GetUInt8(), RealmFlags(realmflags), fields[6].GetUInt8(),
(allowedSecurityLevel <= SEC_ADMINISTRATOR ? AccountTypes(allowedSecurityLevel) : SEC_ADMINISTRATOR),
fields[8].GetFloat(), fields[9].GetCppString());
if (init)
sLog.outString("Added realm id %u, name '%s'", Id, name.c_str());
}
while (result->NextRow());
delete result;
}
}<|fim▁end|> | realm.realmflags = realmflags;
realm.timezone = timezone;
|
<|file_name|>base.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import json
import logging
import platform
from os.path import abspath
from django.utils.functional import lazy
import dj_database_url
from decouple import Csv, config
from pathlib import Path
from .static_media import PIPELINE_CSS, PIPELINE_JS # noqa
# ROOT path of the project. A pathlib.Path object.
ROOT_PATH = Path(__file__).resolve().parents[2]
ROOT = str(ROOT_PATH)
def path(*args):
return abspath(str(ROOT_PATH.joinpath(*args)))
# Is this a dev instance?
DEV = config('DEV', cast=bool, default=False)
PROD = config('PROD', cast=bool, default=False)
DEBUG = config('DEBUG', cast=bool, default=False)
# Production uses PostgreSQL, but Sqlite should be sufficient for local development.
db_url = config('DATABASE_URL', default='sqlite:///bedrock.db')
DATABASES = {
# leave 'default' empty so that Django will start even
# if it can't connect to the DB at boot time
'default': {},
'bedrock': dj_database_url.parse(db_url)
}
if db_url.startswith('sqlite'):
# no server, can use 'default'
DATABASES['default'] = DATABASES['bedrock']
# leave the config in 'bedrock' as well so scripts
# hardcoded for 'bedrock' will continue to work
else:
# settings specific to db server environments
DATABASES['bedrock']['CONN_MAX_AGE'] = None
DATABASE_ROUTERS = ['bedrock.base.database.BedrockRouter']
CACHES = config(
'CACHES',
cast=json.loads,
default=json.dumps(
{'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'translations'}}))
# in case django-pylibmc is in use
PYLIBMC_MIN_COMPRESS_LEN = 150 * 1024
PYLIBMC_COMPRESS_LEVEL = 1 # zlib.Z_BEST_SPEED
# Logging
LOG_LEVEL = config('LOG_LEVEL', cast=int, default=logging.INFO)
HAS_SYSLOG = True
SYSLOG_TAG = "http_app_bedrock"<|fim▁hole|>CEF_VENDOR = 'Mozilla'
CEF_VERSION = '0'
CEF_DEVICE_VERSION = '0'
# Internationalization.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = config('TIME_ZONE', default='America/Los_Angeles')
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
USE_TZ = True
# just here so Django doesn't complain
TEST_RUNNER = 'django.test.runner.DiscoverRunner'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-US'
# Use Ship It as the source for product_details
PROD_DETAILS_URL = config('PROD_DETAILS_URL',
default='https://product-details.mozilla.org/1.0/')
# Tells the product_details module where to find our local JSON files.
# This ultimately controls how LANGUAGES are constructed.
PROD_DETAILS_CACHE_NAME = 'product-details'
PROD_DETAILS_CACHE_TIMEOUT = 60 * 15 # 15 min
default_pdstorage = 'PDDatabaseStorage' if PROD else 'PDFileStorage'
PROD_DETAILS_STORAGE = config('PROD_DETAILS_STORAGE',
default='product_details.storage.' + default_pdstorage)
# Accepted locales
PROD_LANGUAGES = ('ach', 'af', 'an', 'ar', 'as', 'ast', 'az', 'be', 'bg',
'bn-BD', 'bn-IN', 'br', 'brx', 'bs', 'ca', 'cak', 'cs',
'cy', 'da', 'de', 'dsb', 'ee', 'el', 'en-GB', 'en-US',
'en-ZA', 'eo', 'es-AR', 'es-CL', 'es-ES', 'es-MX', 'et',
'eu', 'fa', 'ff', 'fi', 'fr', 'fy-NL', 'ga-IE', 'gd',
'gl', 'gn', 'gu-IN', 'ha', 'he', 'hi-IN', 'hr', 'hsb',
'hu', 'hy-AM', 'id', 'ig', 'is', 'it', 'ja', 'ja-JP-mac',
'ka', 'kk', 'km', 'kn', 'ko', 'lij', 'ln', 'lt', 'ltg',
'lv', 'mai', 'mk', 'ml', 'mr', 'ms', 'my', 'nb-NO', 'nl',
'nn-NO', 'oc', 'or', 'pa-IN', 'pl', 'pt-BR', 'pt-PT',
'rm', 'ro', 'ru', 'sat', 'si', 'sk', 'sl', 'son', 'sq',
'sr', 'sv-SE', 'sw', 'ta', 'te', 'th', 'tr', 'uk', 'ur',
'uz', 'vi', 'wo', 'xh', 'yo', 'zh-CN', 'zh-TW', 'zu')
LOCALES_PATH = ROOT_PATH / 'locale'
default_locales_repo = 'www.mozilla.org' if DEV else 'bedrock-l10n'
default_locales_repo = 'https://github.com/mozilla-l10n/{}'.format(default_locales_repo)
LOCALES_REPO = config('LOCALES_REPO', default=default_locales_repo)
def get_dev_languages():
try:
return [lang.name for lang in LOCALES_PATH.iterdir()
if lang.is_dir() and lang.name != 'templates']
except OSError:
# no locale dir
return list(PROD_LANGUAGES)
DEV_LANGUAGES = get_dev_languages()
DEV_LANGUAGES.append('en-US')
# Map short locale names to long, preferred locale names. This
# will be used in urlresolvers to determine the
# best-matching locale from the user's Accept-Language header.
CANONICAL_LOCALES = {
'en': 'en-US',
'es': 'es-ES',
'ja-jp-mac': 'ja',
'no': 'nb-NO',
'pt': 'pt-BR',
'sv': 'sv-SE',
'zh-hant': 'zh-TW', # Bug 1263193
'zh-hant-tw': 'zh-TW', # Bug 1263193
}
# Unlocalized pages are usually redirected to the English (en-US) equivalent,
# but sometimes it would be better to offer another locale as fallback. This map
# specifies such cases.
FALLBACK_LOCALES = {
'es-AR': 'es-ES',
'es-CL': 'es-ES',
'es-MX': 'es-ES',
}
def lazy_lang_url_map():
from django.conf import settings
langs = settings.DEV_LANGUAGES if settings.DEV else settings.PROD_LANGUAGES
return {i.lower(): i for i in langs}
# Override Django's built-in with our native names
def lazy_langs():
from django.conf import settings
from product_details import product_details
langs = DEV_LANGUAGES if settings.DEV else settings.PROD_LANGUAGES
return {lang.lower(): product_details.languages[lang]['native']
for lang in langs if lang in product_details.languages}
LANGUAGE_URL_MAP = lazy(lazy_lang_url_map, dict)()
LANGUAGES = lazy(lazy_langs, dict)()
FEED_CACHE = 3900
DOTLANG_CACHE = 600
DOTLANG_FILES = ['main', 'download_button']
# Paths that don't require a locale code in the URL.
# matches the first url component (e.g. mozilla.org/gameon/)
SUPPORTED_NONLOCALES = [
# from redirects.urls
'media',
'static',
'certs',
'images',
'contribute.json',
'credits',
'gameon',
'rna',
'robots.txt',
'telemetry',
'webmaker',
'contributor-data',
'healthz',
'2004',
'2005',
'2006',
'keymaster',
'microsummaries',
'xbl',
]
ALLOWED_HOSTS = config(
'ALLOWED_HOSTS', cast=Csv(),
default='www.mozilla.org,www.ipv6.mozilla.org,www.allizom.org')
# The canonical, production URL without a trailing slash
CANONICAL_URL = 'https://www.mozilla.org'
# Make this unique, and don't share it with anybody.
SECRET_KEY = config('SECRET_KEY', default='ssssshhhhh')
MEDIA_URL = config('MEDIA_URL', default='/user-media/')
MEDIA_ROOT = config('MEDIA_ROOT', default=path('media'))
STATIC_URL = config('STATIC_URL', default='/media/')
STATIC_ROOT = config('STATIC_ROOT', default=path('static'))
STATICFILES_STORAGE = ('pipeline.storage.NonPackagingPipelineStorage' if DEBUG else
'bedrock.base.storage.ManifestPipelineStorage')
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'pipeline.finders.CachedFileFinder',
'pipeline.finders.PipelineFinder',
)
STATICFILES_DIRS = (
path('media'),
)
PIPELINE = {
'STYLESHEETS': PIPELINE_CSS,
'JAVASCRIPT': PIPELINE_JS,
'DISABLE_WRAPPER': True,
'SHOW_ERRORS_INLINE': False,
'COMPILERS': (
'pipeline.compilers.less.LessCompiler',
),
'LESS_BINARY': config('PIPELINE_LESS_BINARY',
default=path('node_modules', 'less', 'bin', 'lessc')),
'LESS_ARGUMENTS': config('PIPELINE_LESS_ARGUMENTS', default='-s'),
'JS_COMPRESSOR': 'pipeline.compressors.uglifyjs.UglifyJSCompressor',
'UGLIFYJS_BINARY': config('PIPELINE_UGLIFYJS_BINARY',
default=path('node_modules', 'uglify-js', 'bin', 'uglifyjs')),
'CSS_COMPRESSOR': 'pipeline.compressors.cssmin.CSSMinCompressor',
'CSSMIN_BINARY': config('PIPELINE_CSSMIN_BINARY',
default=path('node_modules', 'cssmin', 'bin', 'cssmin')),
'PIPELINE_ENABLED': config('PIPELINE_ENABLED', not DEBUG, cast=bool),
'PIPELINE_COLLECTOR_ENABLED': config('PIPELINE_COLLECTOR_ENABLED', not DEBUG, cast=bool),
}
WHITENOISE_ROOT = config('WHITENOISE_ROOT', default=path('root_files'))
WHITENOISE_MAX_AGE = 6 * 60 * 60 # 6 hours
PROJECT_MODULE = 'bedrock'
ROOT_URLCONF = 'bedrock.urls'
# Tells the extract script what files to look for L10n in and what function
# handles the extraction.
PUENTE = {
'BASE_DIR': ROOT,
'PROJECT': 'Bedrock',
'MSGID_BUGS_ADDRESS': 'https://bugzilla.mozilla.org/enter_bug.cgi?'
'product=www.mozilla.org&component=L10N',
'DOMAIN_METHODS': {
'django': [
('bedrock/**.py', 'lib.l10n_utils.extract.extract_python'),
('bedrock/**/templates/**.html', 'lib.l10n_utils.extract.extract_jinja2'),
('bedrock/**/templates/**.js', 'lib.l10n_utils.extract.extract_jinja2'),
('bedrock/**/templates/**.jsonp', 'lib.l10n_utils.extract.extract_jinja2'),
],
}
}
HOSTNAME = platform.node()
DEIS_APP = config('DEIS_APP', default=None)
DEIS_DOMAIN = config('DEIS_DOMAIN', default=None)
ENABLE_HOSTNAME_MIDDLEWARE = config('ENABLE_HOSTNAME_MIDDLEWARE',
default=bool(DEIS_APP), cast=bool)
ENABLE_VARY_NOCACHE_MIDDLEWARE = config('ENABLE_VARY_NOCACHE_MIDDLEWARE',
default=True, cast=bool)
# set this to enable basic auth for the entire site
# e.g. BASIC_AUTH_CREDS="thedude:thewalrus"
BASIC_AUTH_CREDS = config('BASIC_AUTH_CREDS', default=None)
MIDDLEWARE_CLASSES = [
'sslify.middleware.SSLifyMiddleware',
'bedrock.mozorg.middleware.MozorgRequestTimingMiddleware',
'django_statsd.middleware.GraphiteMiddleware',
'corsheaders.middleware.CorsMiddleware',
'bedrock.mozorg.middleware.VaryNoCacheMiddleware',
'bedrock.base.middleware.BasicAuthMiddleware',
# must come before LocaleURLMiddleware
'bedrock.redirects.middleware.RedirectsMiddleware',
'bedrock.tabzilla.middleware.TabzillaLocaleURLMiddleware',
'commonware.middleware.RobotsTagHeader',
'bedrock.mozorg.middleware.ClacksOverheadMiddleware',
'bedrock.mozorg.middleware.HostnameMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'bedrock.mozorg.middleware.CacheMiddleware',
'dnt.middleware.DoNotTrackMiddleware',
]
INSTALLED_APPS = (
'cronjobs', # for ./manage.py cron * cmd line tasks
# Django contrib apps
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.staticfiles',
'django.contrib.messages',
# Third-party apps, patches, fixes
'commonware.response.cookies',
# L10n
'puente', # for ./manage.py extract
'product_details',
# third-party apps
'django_jinja_markdown',
'django_statsd',
'pagedown',
'rest_framework',
'pipeline',
'localflavor',
'django_jinja',
# Local apps
'bedrock.base',
'bedrock.lightbeam',
'bedrock.firefox',
'bedrock.foundation',
'bedrock.gigabit',
'bedrock.grants',
'bedrock.infobar',
'bedrock.legal',
'bedrock.mozorg',
'bedrock.newsletter',
'bedrock.persona',
'bedrock.press',
'bedrock.privacy',
'bedrock.research',
'bedrock.styleguide',
'bedrock.tabzilla',
'bedrock.teach',
'bedrock.externalfiles',
'bedrock.security',
'bedrock.events',
'bedrock.releasenotes',
'bedrock.thunderbird',
'bedrock.shapeoftheweb',
# last so that redirects here will be last
'bedrock.redirects',
# libs
'django_extensions',
'lib.l10n_utils',
'captcha',
'rna',
)
# Must match the list at CloudFlare if the
# VaryNoCacheMiddleware is enabled. The home
# page is exempt by default.
VARY_NOCACHE_EXEMPT_URL_PREFIXES = (
'/plugincheck/',
'/firefox/',
'/contribute/',
'/about/',
'/contact/',
'/thunderbird/',
'/newsletter/',
'/privacy/',
'/foundation/',
'/teach/',
'/gigabit/',
'/lightbeam/',
)
# Sessions
#
# By default, be at least somewhat secure with our session cookies.
SESSION_COOKIE_HTTPONLY = not DEBUG
SESSION_COOKIE_SECURE = not DEBUG
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
LOCALE_PATHS = (
str(LOCALES_PATH),
)
TEMPLATES = [
{
'BACKEND': 'django_jinja.backend.Jinja2',
'DIRS': LOCALE_PATHS,
'APP_DIRS': True,
'OPTIONS': {
'match_extension': None,
'undefined': 'jinja2.Undefined',
'finalize': lambda x: x if x is not None else '',
'translation_engine': 'lib.l10n_utils.template',
'newstyle_gettext': False,
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.media',
'django.template.context_processors.request',
'django.contrib.messages.context_processors.messages',
'bedrock.base.context_processors.i18n',
'bedrock.base.context_processors.globals',
'bedrock.mozorg.context_processors.canonical_path',
'bedrock.mozorg.context_processors.contrib_numbers',
'bedrock.mozorg.context_processors.current_year',
'bedrock.mozorg.context_processors.funnelcake_param',
'bedrock.mozorg.context_processors.facebook_locale',
'bedrock.firefox.context_processors.latest_firefox_versions',
],
'extensions': [
'jinja2.ext.do',
'jinja2.ext.with_',
'jinja2.ext.loopcontrols',
'jinja2.ext.autoescape',
'django_jinja.builtins.extensions.CsrfExtension',
'django_jinja.builtins.extensions.StaticFilesExtension',
'django_jinja.builtins.extensions.DjangoFiltersExtension',
'lib.l10n_utils.template.i18n',
'lib.l10n_utils.template.l10n_blocks',
'lib.l10n_utils.template.lang_blocks',
'django_jinja_markdown.extensions.MarkdownExtension',
'pipeline.jinja2.PipelineExtension',
],
}
},
]
FEEDS = {
'mozilla': 'https://blog.mozilla.org/feed/'
}
EVENTS_ICAL_FEEDS = (
'https://reps.mozilla.org/events/period/future/ical/',
'https://www.google.com/calendar/ical/mozilla.com_l9g7ie050ngr3g4qv6bgiinoig'
'%40group.calendar.google.com/public/basic.ics',
)
# Twitter accounts to retrieve tweets with the API
TWITTER_ACCOUNTS = (
'firefox',
'firefox_es',
'firefoxbrasil',
'mozstudents',
)
# Add optional parameters specific to accounts here
# e.g. 'firefox': {'exclude_replies': False}
TWITTER_ACCOUNT_OPTS = {}
TWITTER_APP_KEYS = config('TWITTER_APP_KEYS', cast=json.loads, default='{}')
# Contribute numbers
# TODO: automate these
CONTRIBUTE_NUMBERS = {
'num_mozillians': 10554,
'num_languages': 87,
}
BASKET_URL = config('BASKET_URL', default='https://basket.mozilla.org')
BASKET_API_KEY = config('BASKET_API_KEY', default='')
BASKET_TIMEOUT = config('BASKET_TIMEOUT', cast=int, default=10)
# This prefixes /b/ on all URLs generated by `reverse` so that links
# work on the dev site while we have a mix of Python/PHP
FORCE_SLASH_B = False
# reCAPTCHA keys
RECAPTCHA_PUBLIC_KEY = config('RECAPTCHA_PUBLIC_KEY', default='')
RECAPTCHA_PRIVATE_KEY = config('RECAPTCHA_PRIVATE_KEY', default='')
RECAPTCHA_USE_SSL = config('RECAPTCHA_USE_SSL', cast=bool, default=True)
# Use a message storage mechanism that doesn't need a database.
# This can be changed to use session once we do add a database.
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
def lazy_email_backend():
'Needed in case DEBUG is enabled in local.py instead of environment variable'
from django.conf import settings
return ('django.core.mail.backends.console.EmailBackend' if settings.DEBUG else
'django.core.mail.backends.smtp.EmailBackend')
EMAIL_BACKEND = config('EMAIL_BACKEND', default=lazy(lazy_email_backend, str)())
EMAIL_HOST = config('EMAIL_HOST', default='localhost')
EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int)
EMAIL_USE_TLS = config('EMAIL_USE_TLS', default=False, cast=bool)
EMAIL_SUBJECT_PREFIX = config('EMAIL_SUBJECT_PREFIX', default='[bedrock] ')
EMAIL_HOST_USER = config('EMAIL_HOST_USER', default='')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD', default='')
AURORA_STUB_INSTALLER = False
# special value that means all locales are enabled.
STUB_INSTALLER_ALL = '__ALL__'
# values should be a list of lower case locales per platform for which a
# stub installer is available. Hopefully this can all be moved to bouncer.
STUB_INSTALLER_LOCALES = {
'win': STUB_INSTALLER_ALL,
'osx': [],
'linux': [],
}
# Google Analytics
GA_ACCOUNT_CODE = ''
# Files from The Web[tm]
EXTERNAL_FILES = {
'credits': {
'url': 'https://raw.githubusercontent.com/mozilla/community-data/master/credits/names.csv',
'type': 'bedrock.mozorg.credits.CreditsFile',
'name': 'credits.csv',
},
'forums': {
'url': 'https://raw.githubusercontent.com/mozilla/community-data/master/forums/raw-ng-list.txt',
'type': 'bedrock.mozorg.forums.ForumsFile',
'name': 'forums.txt',
},
}
# Facebook Like button supported locales
# https://www.facebook.com/translations/FacebookLocales.xml
FACEBOOK_LIKE_LOCALES = ['af_ZA', 'ar_AR', 'az_AZ', 'be_BY', 'bg_BG',
'bn_IN', 'bs_BA', 'ca_ES', 'cs_CZ', 'cy_GB',
'da_DK', 'de_DE', 'el_GR', 'en_GB', 'en_PI',
'en_UD', 'en_US', 'eo_EO', 'es_ES', 'es_LA',
'et_EE', 'eu_ES', 'fa_IR', 'fb_LT', 'fi_FI',
'fo_FO', 'fr_CA', 'fr_FR', 'fy_NL', 'ga_IE',
'gl_ES', 'he_IL', 'hi_IN', 'hr_HR', 'hu_HU',
'hy_AM', 'id_ID', 'is_IS', 'it_IT', 'ja_JP',
'ka_GE', 'km_KH', 'ko_KR', 'ku_TR', 'la_VA',
'lt_LT', 'lv_LV', 'mk_MK', 'ml_IN', 'ms_MY',
'nb_NO', 'ne_NP', 'nl_NL', 'nn_NO', 'pa_IN',
'pl_PL', 'ps_AF', 'pt_BR', 'pt_PT', 'ro_RO',
'ru_RU', 'sk_SK', 'sl_SI', 'sq_AL', 'sr_RS',
'sv_SE', 'sw_KE', 'ta_IN', 'te_IN', 'th_TH',
'tl_PH', 'tr_TR', 'uk_UA', 'vi_VN', 'zh_CN',
'zh_HK', 'zh_TW']
# Prefix for media. No trailing slash.
# e.g. '//mozorg.cdn.mozilla.net'
CDN_BASE_URL = config('CDN_BASE_URL', default='')
# Used on the newsletter preference center, included in the "interests" section.
OTHER_NEWSLETTERS = [
'firefox-desktop',
'mobile',
'os',
'firefox-ios',
'mozilla-general',
'firefox-os',
]
# Regional press blogs map to locales
PRESS_BLOG_ROOT = 'https://blog.mozilla.org/'
PRESS_BLOGS = {
'de': 'press-de/',
'en-GB': 'press-uk/',
'en-US': 'press/',
'es-AR': 'press-latam/',
'es-CL': 'press-latam/',
'es-ES': 'press-es/',
'es-MX': 'press-latam/',
'fr': 'press-fr/',
'it': 'press-it/',
'pl': 'press-pl/',
}
FXOS_PRESS_BLOG_LINKS = {
'en': 'https://blog.mozilla.org/press/category/firefox-os/',
'de': 'https://blog.mozilla.org/press-de/category/firefox-os/',
'es-ES': 'https://blog.mozilla.org/press-es/category/firefox-os/',
'es': 'https://blog.mozilla.org/press-latam/category/firefox-os/',
'fr': 'https://blog.mozilla.org/press-fr/category/firefox-os/',
'it': 'https://blog.mozilla.org/press-it/category/firefox-os/',
'pb-BR': 'https://blog.mozilla.org/press-br/category/firefox-os/',
'pl': 'https://blog.mozilla.org/press-pl/category/firefox-os/',
}
MOBILIZER_LOCALE_LINK = {
'en-US': 'https://wiki.mozilla.org/FirefoxOS/Community/Mobilizers',
'hu': 'https://www.facebook.com/groups/mobilizerhungary/',
'pt-BR': 'https://wiki.mozilla.org/Mobilizers/MobilizerBrasil/',
'pl': 'https://wiki.mozilla.org/Mobilizers/MobilizerPolska/',
'gr': 'https://wiki.mozilla.org/Mobilizer/MobilizerGreece/',
'cs': 'https://wiki.mozilla.org/Mobilizer/MobilizerCzechRepublic/'
}
DONATE_LINK = ('https://donate.mozilla.org/{locale}/?presets={presets}'
'&amount={default}&ref=EOYFR2015&utm_campaign=EOYFR2015'
'&utm_source=mozilla.org&utm_medium=referral&utm_content={source}'
'¤cy={currency}')
DONATE_PARAMS = {
'en-US': {
'currency': 'usd',
'presets': '100,50,25,15',
'default': '50'
},
'an': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'as': {
'currency': 'inr',
'presets': '1000,500,250,150',
'default': '500'
},
'ast': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'brx': {
'currency': 'inr',
'presets': '1000,500,250,150',
'default': '500'
},
'ca': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'cs': {
'currency': 'czk',
'presets': '400,200,100,55',
'default': '200'
},
'cy': {
'currency': 'gbp',
'presets': '20,10,5,3',
'default': '10'
},
'da': {
'currency': 'dkk',
'presets': '160,80,40,20',
'default': '80'
},
'de': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'dsb': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'el': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'en-GB': {
'currency': 'gbp',
'presets': '20,10,5,3',
'default': '10'
},
'es-ES': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'es-MX': {
'currency': 'mxn',
'presets': '240,120,60,35',
'default': '120'
},
'eo': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'et': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'eu': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'fi': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'fr': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'fy-NL': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'ga-IE': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'gd': {
'currency': 'gbp',
'presets': '20,10,5,3',
'default': '10'
},
'gl': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'gu-IN': {
'currency': 'inr',
'presets': '1000,500,250,150',
'default': '500'
},
'he': {
'currency': 'ils',
'presets': '60,30,15,9',
'default': '30'
},
'hi-IN': {
'currency': 'inr',
'presets': '1000,500,250,150',
'default': '500'
},
'hsb': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'hu': {
'currency': 'huf',
'presets': '4000,2000,1000,600',
'default': '2000'
},
'id': {
'currency': 'idr',
'presets': '270000,140000,70000,40000',
'default': '140000'
},
'in': {
'currency': 'inr',
'presets': '1000,500,250,150',
'default': '500'
},
'it': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'ja': {
'currency': 'jpy',
'presets': '1600,800,400,250',
'default': '800'
},
'ja-JP': {
'currency': 'jpy',
'presets': '1600,800,400,250',
'default': '800'
},
'ja-JP-mac': {
'currency': 'jpy',
'presets': '1600,800,400,250',
'default': '800'
},
'kn': {
'currency': 'inr',
'presets': '1000,500,250,150',
'default': '500'
},
'lij': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'lt': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'lv': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'ml': {
'currency': 'inr',
'presets': '1000,500,250,150',
'default': '500'
},
'mr': {
'currency': 'inr',
'presets': '1000,500,250,150',
'default': '500'
},
'nb-NO': {
'currency': 'nok',
'presets': '160,80,40,20',
'default': '80'
},
'nn-NO': {
'currency': 'nok',
'presets': '160,80,40,20',
'default': '80'
},
'nl': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'or': {
'currency': 'inr',
'presets': '1000,500,250,150',
'default': '500'
},
'pa-IN': {
'currency': 'inr',
'presets': '1000,500,250,150',
'default': '500'
},
'pl': {
'currency': 'pln',
'presets': '80,40,20,10',
'default': '40'
},
'pt-BR': {
'currency': 'brl',
'presets': '375,187,90,55',
'default': '187'
},
'pt-PT': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'ru': {
'currency': 'rub',
'presets': '1000,500,250,140',
'default': '500'
},
'sat': {
'currency': 'inr',
'presets': '1000,500,250,150',
'default': '500'
},
'sk': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'sl': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'sv-SE': {
'currency': 'sek',
'presets': '160,80,40,20',
'default': '80'
},
'sr': {
'currency': 'eur',
'presets': '100,50,25,15',
'default': '50'
},
'ta': {
'currency': 'inr',
'presets': '1000,500,250,150',
'default': '500'
},
'te': {
'currency': 'inr',
'presets': '1000,500,250,150',
'default': '500'
},
'th': {
'currency': 'thb',
'presets': '500,250,125,75',
'default': '250'
},
}
# Official Firefox Twitter accounts
FIREFOX_TWITTER_ACCOUNTS = {
'en-US': 'https://twitter.com/firefox',
'es-ES': 'https://twitter.com/firefox_es',
'pt-BR': 'https://twitter.com/firefoxbrasil',
}
# Twitter accounts to display on homepage per locale
HOMEPAGE_TWITTER_ACCOUNTS = {
'en-US': 'firefox',
'es-AR': 'firefox_es',
'es-CL': 'firefox_es',
'es-ES': 'firefox_es',
'es-MX': 'firefox_es',
'pt-BR': 'firefoxbrasil',
}
# Mapbox token for spaces and communities pages
MAPBOX_TOKEN = config('MAPBOX_TOKEN', default='mozilla-webprod.ijaeac5j')
MAPBOX_ACCESS_TOKEN = config(
'MAPBOX_ACCESS_TOKEN',
default='pk.eyJ1IjoibW96aWxsYS13ZWJwcm9kIiwiYSI6Ii0xYVEtTW8ifQ.3ikA2IgKATeXStfC5wKDaQ')
# Tabzilla Information Bar default options
TABZILLA_INFOBAR_OPTIONS = 'update translation'
# Optimize.ly project code
OPTIMIZELY_PROJECT_ID = config('OPTIMIZELY_PROJECT_ID', default='')
# Fx Accounts iframe source
FXA_IFRAME_SRC = config('FXA_IFRAME_SRC',
default='https://accounts.firefox.com/')
# Bug 1264843: embed FxA server in China within Fx China repack
FXA_IFRAME_SRC_MOZILLAONLINE = config('FXA_IFRAME_SRC_MOZILLAONLINE',
default='https://accounts.firefox.com.cn/')
# Google Play and Apple App Store settings
from .appstores import (GOOGLE_PLAY_FIREFOX_LINK, # noqa
GOOGLE_PLAY_FIREFOX_LINK_MOZILLAONLINE, # noqa
APPLE_APPSTORE_FIREFOX_LINK, APPLE_APPSTORE_COUNTRY_MAP)
# Locales that should display the 'Send to Device' widget
SEND_TO_DEVICE_LOCALES = ['de', 'en-GB', 'en-US', 'en-ZA',
'es-AR', 'es-CL', 'es-ES', 'es-MX',
'fr', 'id', 'pl', 'pt-BR', 'ru']
RNA_SYNC_URL = config('RNA_SYNC_URL',
default='https://nucleus.mozilla.org/rna/sync/')
MOFO_SECURITY_ADVISORIES_PATH = config('MOFO_SECURITY_ADVISORIES_PATH',
default=path('mofo_security_advisories'))
MOFO_SECURITY_ADVISORIES_REPO = 'https://github.com/mozilla/foundation-security-advisories.git'
CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/([a-zA-Z-]+/)?(shapeoftheweb|newsletter)/'
LOGGING = {
'root': {
'level': 'WARNING',
},
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(message)s'
},
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
}
},
'loggers': {
'django.db.backends': {
'level': 'ERROR',
'handlers': ['console'],
'propagate': False,
},
},
}
PASSWORD_HASHERS = ['django.contrib.auth.hashers.PBKDF2PasswordHasher']
REST_FRAMEWORK = {
# Use hyperlinked styles by default.
# Only used if the `serializer_class` attribute is not set on a view.
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rna.serializers.HyperlinkedModelSerializerWithPkField',
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_FILTER_BACKENDS': ('rna.filters.TimestampedFilterBackend',)
}
FIREFOX_OS_FEEDS = (
('de', 'https://blog.mozilla.org/press-de/category/firefox-os/feed/'),
('en-US', 'https://blog.mozilla.org/blog/category/firefox-os/feed/'),
('es-ES', 'https://blog.mozilla.org/press-es/category/firefox-os/feed/'),
('es', 'https://blog.mozilla.org/press-latam/category/firefox-os/feed/'),
('fr', 'https://blog.mozilla.org/press-fr/category/firefox-os/feed/'),
('it', 'https://blog.mozilla.org/press-it/category/firefox-os/feed/'),
('pl', 'https://blog.mozilla.org/press-pl/category/firefox-os/feed/'),
('pt-BR', 'https://blog.mozilla.org/press-br/category/firefox-os/feed/'),
)
FIREFOX_OS_FEED_LOCALES = [feed[0] for feed in FIREFOX_OS_FEEDS]
TABLEAU_DB_URL = config('TABLEAU_DB_URL', default=None)
ADMINS = MANAGERS = config('ADMINS', cast=json.loads,
default='[]')
GTM_CONTAINER_ID = config('GTM_CONTAINER_ID', default='')
GMAP_API_KEY = config('GMAP_API_KEY', default='')
HMAC_KEYS = config('HMAC_KEYS', cast=json.loads, default='{}')
STATSD_CLIENT = config('STATSD_CLIENT', default='django_statsd.clients.normal')
STATSD_HOST = config('STATSD_HOST', default='127.0.0.1')
STATSD_PORT = config('STATSD_PORT', cast=int, default=8125)
STATSD_PREFIX = config('STATSD_PREFIX', default='bedrock')
SSLIFY_DISABLE = config('DISABLE_SSL', default=True, cast=bool)
if not SSLIFY_DISABLE:
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SSLIFY_DISABLE_FOR_REQUEST = [
lambda request: request.get_full_path() == '/healthz/'
]
NEWRELIC_BROWSER_LICENSE_KEY = config('NEWRELIC_BROWSER_LICENSE_KEY', default='')
NEWRELIC_APP_ID = config('NEWRELIC_APP_ID', default='')
FIREFOX_MOBILE_SYSREQ_URL = 'https://support.mozilla.org/kb/will-firefox-work-my-mobile-device'
B2G_DROID_URL = 'https://d2yw7jilxa8093.cloudfront.net/B2GDroid-mozilla-central-nightly-latest.apk'
MOZILLA_LOCATION_SERVICES_KEY = 'ec4d0c4b-b9ac-4d72-9197-289160930e14'
DEAD_MANS_SNITCH_URL = config('DEAD_MANS_SNITCH_URL', default=None)<|fim▁end|> | LOGGING_CONFIG = None
# CEF Logging
CEF_PRODUCT = 'Bedrock' |
<|file_name|>signals.py<|end_file_name|><|fim▁begin|>#from actstream import action
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.core.exceptions import ObjectDoesNotExist
from django.dispatch import receiver
from profiles.models import Organisation, OrganisationGroup, UserProfile
UserModel = get_user_model()
@receiver(post_save, sender=UserModel)
def create_user_profile(sender, instance, created, **kwargs):
"""
Create a new profile for the newly registered user
"""
try:
shroom = instance.shroom
pass
except ObjectDoesNotExist:
if created:
UserProfile.objects.create(user=instance)
@receiver(post_save, sender=Organisation)
def create_organisation_group(sender, instance, created, **kwargs):
"""<|fim▁hole|> """
if created:
OrganisationGroup.objects.create(organisation=instance, name=instance.full_name)<|fim▁end|> | Create a new organisation group for the new Organisation |
<|file_name|>MoviesImplWrapper.java<|end_file_name|><|fim▁begin|>package any.ejbtest;
import com.dms.Discriminated;
import java.util.List;
/**
* MoviesImplEjb, 02.03.2015
*
* Copyright (c) 2014 Marius Dinu. All rights reserved.
*
* @author mdinu
* @version $Id$
*/
//@Named
@Discriminated(isResultAggregated = true)<|fim▁hole|> private Movies movies;
public void setMovies(Movies movies) {
this.movies = movies;
}
public Movies getMovies() {
return movies;
}
@Override
public void addMovie(Movie movie) throws Exception {
movies.addMovie(movie);
}
@Override
public void deleteMovie(Movie movie) throws Exception {
movies.deleteMovie(movie);
}
@Override
public List<Movie> getAllMovies() throws Exception {
return movies.getAllMovies();
}
}<|fim▁end|> | public class MoviesImplWrapper implements Movies {
|
<|file_name|>integration_test.rs<|end_file_name|><|fim▁begin|>mod cli;
#[test]<|fim▁hole|>fn cli_help() {
let out = cli::run(vec!["--help"]).expect("--help failed");
assert_eq!(out.status, 0);
assert!(out.stdout.len() > 0);
assert!(out.stdout.contains("USAGE"));
assert!(out.stderr.is_empty());
}<|fim▁end|> | |
<|file_name|>if-branch-types.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn main() {
let x = if true { 10i } else { 10u };
//~^ ERROR if and else have incompatible types: expected `int` but found `uint`
}<|fim▁end|> | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at |
<|file_name|>logger.py<|end_file_name|><|fim▁begin|>import logging
def init_logger():<|fim▁hole|> formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
logger = logging.getLogger('redberry')
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setFormatter(formatter)
logger.addHandler(console)<|fim▁end|> | |
<|file_name|>reaction.rs<|end_file_name|><|fim▁begin|>use data_sef::*;
use ion::Ion;
use molecule::Molecule;
use trait_element::Element;
use trait_properties::Properties;
use trait_reaction::Reaction;
use types::*;
use std::collections::HashMap;
use std::hash::*;
use std::mem;
use std::ops::*;
#[derive(Debug, Eq, PartialEq, Clone, Hash)]
/// An elementair reaction (not containing ions)
pub struct ElemReaction<E: Element> {
/// The left-hand-side
pub lhs: ReactionSide<E>,
/// The right-hand-side
pub rhs: ReactionSide<E>,
// If it's an equilibrium
pub is_equilibrium: bool,
}
#[derive(Debug, Eq, PartialEq, Clone, Hash)]
/// A side of a reaction
pub struct ReactionSide<E: Element> {
/// The compounds of this side
pub compounds: Vec<ReactionCompound<E>>,
}
#[derive(Debug, Eq, Clone)]
/// A reaction compound
pub struct ReactionCompound<E: Element> {
/// The element it uses
pub element: E,
/// The amount of moles needed
pub amount: u16,
}
impl<E: Element> ElemReaction<E> {
/// Convert a string representation of an elementary reaction into one
pub fn ion_from_string(string: &str) -> Option<ElemReaction<Ion>> {
let mut token = String::new();
let mut lhs = None;
let mut rhs = None;
let mut is_equilibrium = false;
for c in string.chars() {
if c == '<' || c == '>' || c == '⇌' || c == '→' {
if lhs == None {
lhs = ReactionSide::<Ion>::ion_from_string(&token);
token = String::new();
}
// NOTE: No support for backwards-only reactions
if c == '<' || c == '⇌' {
is_equilibrium = true;
}
continue;
}
token.push(c);
}
if !token.is_empty() {
rhs = ReactionSide::<Ion>::ion_from_string(&token);
}
if let (Some(lhs), Some(rhs)) = (lhs, rhs) {
Some(ElemReaction {
lhs,
rhs,
is_equilibrium,
})
} else {
None
}
}
/// Convert a string representation of a reaction into one
pub fn molecule_from_string(string: &str) -> Option<ElemReaction<Molecule>> {
let mut token = String::new();
let mut lhs = None;
let mut rhs = None;
let mut is_equilibrium = false;
for c in string.chars() {
if c == '<' || c == '>' || c == '⇌' || c == '→' {
if lhs == None {
lhs = ReactionSide::<Molecule>::molecule_from_string(&token);
token = String::new();
}
if c == '<' || c == '⇌' {
is_equilibrium = true;
}
continue;
}
token.push(c);<|fim▁hole|>
if !token.is_empty() {
rhs = ReactionSide::<Molecule>::molecule_from_string(&token);
}
if let (Some(lhs), Some(rhs)) = (lhs, rhs) {
Some(ElemReaction {
lhs,
rhs,
is_equilibrium,
})
} else {
None
}
}
/// Get the sign of the equation ( → or ⇌ ), depending whether it is an equilibrium or not
#[cfg(not(feature = "no_utf"))]
pub fn reaction_sign(&self) -> &str {
if self.is_equilibrium {
" ⇌ "
} else {
" → "
}
}
#[cfg(feature = "no_utf")]
pub fn reaction_sign(&self) -> &str {
if self.is_equilibrium {
" <> "
} else {
" -> "
}
}
/// Swap the equation
pub fn swap(mut self) -> Self {
mem::swap(&mut self.lhs, &mut self.rhs);
self
}
}
impl<E: Element> ReactionSide<E> {
/// Convert a string representation of a reactionside into one
pub fn ion_from_string(symbol: &str) -> Option<ReactionSide<Ion>> {
let mut compounds = vec![];
let mut token = String::new();
let mut was_whitespace = false;
for c in symbol.chars() {
if is_whitespace!(c) {
was_whitespace = true;
continue;
}
if c == '+' && was_whitespace {
if let Some(compound) = ReactionCompound::<Ion>::ion_from_string(&token) {
compounds.push(compound);
} else {
println!("Failed to parse ion '{}'", &token);
}
token = String::new();
} else {
token.push(c);
}
was_whitespace = false;
}
if !token.is_empty() {
if let Some(compound) = ReactionCompound::<Ion>::ion_from_string(&token) {
compounds.push(compound);
} else {
println!("Failed to parse ion '{}'", &token);
}
}
if !compounds.is_empty() {
Some(ReactionSide { compounds })
} else {
None
}
}
/// Convert a string representation of a reactionside into one
pub fn molecule_from_string(symbol: &str) -> Option<ReactionSide<Molecule>> {
let mut compounds = vec![];
let mut token = String::new();
for c in symbol.chars() {
if is_whitespace!(c) {
continue;
}
if c == '+' {
if let Some(compound) = ReactionCompound::<Molecule>::molecule_from_string(&token) {
compounds.push(compound);
}
token = String::new();
continue;
}
token.push(c);
}
if !token.is_empty() {
if let Some(compound) = ReactionCompound::<Molecule>::molecule_from_string(&token) {
compounds.push(compound);
}
}
if !compounds.is_empty() {
Some(ReactionSide { compounds })
} else {
None
}
}
/// Calculate the total charge of this reaction side
pub fn total_charge(&self) -> AtomCharge {
let mut total_charge = AtomCharge::from(0);
for compound in &self.compounds {
if let Some(charge) = compound.element.get_charge() {
total_charge += charge;
}
}
total_charge
}
/// Calculate the energy this side has
pub fn energy(&self) -> Energy {
let mut energy = 0.0;
for compound in &self.compounds {
let sef = get_sef(&compound.element.clone().get_ion().unwrap());
if sef.is_some() {
energy += EnergyType::from(SEFType::from(sef.unwrap()))
* EnergyType::from(compound.amount);
} else {
let mol = compound.element.clone().get_molecule().unwrap();
let is_diatomic = mol.is_diatomic();
let is_monoatomic = mol.compounds.len() == 1 && mol.compounds[0].amount == 1;
if !is_diatomic && !is_monoatomic {
println!(
"Failed to get SEF for compound {}, assuming 0",
compound.symbol()
);
}
}
}
Energy::from(energy)
}
/// Calculate the total amount of atoms this side contains
pub fn total_atoms(&self, include_electrons: bool) -> HashMap<AtomNumber, u16> {
let mut atoms: HashMap<AtomNumber, u16> = HashMap::new();
// for molecule_compound in self.compounds:
for reaction_compound in &self.compounds {
if let Some(molecule) = reaction_compound.element.clone().get_molecule() {
for molecule_compound in &molecule.compounds {
let atom_number = molecule_compound.atom.number.clone();
if !include_electrons && atom_number == AtomNumber::from(0) {
// Ignore electrons in the atom count
continue;
}
let mut amount;
if let Some(&old_amount) = atoms.get(&atom_number) {
amount = old_amount;
} else {
amount = 0;
}
amount += u16::from(molecule_compound.amount) * reaction_compound.amount;
atoms.insert(atom_number, amount);
}
}
}
atoms
}
}
impl<E: Element> ReactionCompound<E> {
/// Convert a string representation of a reaction compound into one
pub fn ion_from_string(symbol: &str) -> Option<ReactionCompound<Ion>> {
let mut amount: u16 = 0;
let mut element = None;
let mut set_amount = true;
let mut token = String::new();
for c in symbol.chars() {
if set_amount && is_number!(c) {
amount *= 10;
amount += u16::from(to_number!(c));
continue;
} else {
set_amount = false;
}
token.push(c);
}
if !token.is_empty() {
element = Ion::from_string(&token);
}
if amount == 0 {
amount = 1;
}
if let Some(element) = element {
Some(ReactionCompound { amount, element })
} else {
None
}
}
/// Convert a string representation of a reaction compound into one
pub fn molecule_from_string(symbol: &str) -> Option<ReactionCompound<Molecule>> {
let mut amount: u16 = 0;
let mut element = None;
let mut set_amount = true;
let mut token = String::new();
for c in symbol.chars() {
if set_amount && is_number!(c) {
amount *= 10;
amount += u16::from(to_number!(c));
continue;
} else {
set_amount = false;
}
token.push(c);
}
if !token.is_empty() {
element = Molecule::from_string(&token);
}
if amount == 0 {
amount = 1;
}
if let Some(element) = element {
Some(ReactionCompound { amount, element })
} else {
None
}
}
}
impl<E: Element> Reaction<E> for ElemReaction<E> {
/// NOTE: This function is still a WIP!
fn equalise(&self) -> bool {
println!("#### The equalise function is not yet ready.");
let total_left = self.lhs.total_atoms(false);
let total_right = self.rhs.total_atoms(false);
// If both sides are already equal, do nothing
if total_left == total_right {
return true;
}
for (atom_number, l_amount) in total_left {
let r_amount: u16;
match total_right.get(&atom_number) {
Some(&x) => r_amount = x,
None => r_amount = 0,
}
if r_amount == 0 {
println!("It's impossible to make this reaction work: {}", self);
return false;
}
if l_amount != r_amount {
let difference = {
if l_amount > r_amount {
l_amount - r_amount
} else {
r_amount - l_amount
}
};
if difference > 0 {
// Increase right side
println!("[right] We know what to do, but it's just not implemented yet.");
} else {
// Increase left side
println!("[left] We know what to do, but it's just not implemented yet.");
}
}
}
// NOTE: true only for debugging
true
}
fn is_valid(&self) -> bool {
self.lhs.total_atoms(false) == self.rhs.total_atoms(false)
&& self.lhs.total_charge() == self.lhs.total_charge()
}
fn energy_cost(&self) -> Energy {
self.rhs.energy() - self.lhs.energy()
}
fn elem_reaction(&self) -> ElemReaction<E> {
self.clone()
}
}
impl<E: Element> Add for ReactionSide<E> {
type Output = ReactionSide<E>;
/// Adding two ReactionSide's adds their compounds
fn add(self, mut rhs: ReactionSide<E>) -> ReactionSide<E> {
let mut compounds = self.compounds.clone();
compounds.append(&mut rhs.compounds);
ReactionSide { compounds }
}
}
impl<E: Element> Mul<u16> for ReactionSide<E> {
type Output = ReactionSide<E>;
/// Multiplying a ReactionSide with a number
/// multiplies the amount of all compounds of that side
fn mul(self, rhs: u16) -> ReactionSide<E> {
let mut compounds = self.compounds.clone();
for compound in &mut compounds {
compound.amount *= rhs;
}
ReactionSide { compounds }
}
}
impl<E: Element> PartialEq for ReactionCompound<E> {
/// Two ReactionCompound's are equal if their elements are equal
fn eq(&self, rhs: &ReactionCompound<E>) -> bool {
self.element == rhs.element
}
}
impl<E: Element> Hash for ReactionCompound<E> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.element.hash(state);
}
}
impl<E: Element> Properties for ElemReaction<E> {
fn symbol(&self) -> String {
let mut symbol = String::new();
symbol += &self.lhs.symbol();
symbol += self.reaction_sign();
symbol += &self.rhs.symbol();
symbol += " [";
symbol += &format!("{:.3}", &self.energy_cost());
symbol += " J]";
symbol
}
fn name(&self) -> String {
let mut name = String::new();
name += &self.lhs.name();
name += self.reaction_sign();
name += &self.rhs.name();
name += " [";
name += &format!("{:.3}", &self.energy_cost());
name += " J]";
name
}
fn mass(&self) -> AtomMass {
// Law of Conservation of Mass
AtomMass::from(0.0)
}
fn is_diatomic(&self) -> bool {
// Reactions can't be diatomic
false
}
}
impl<E: Element> Properties for ReactionSide<E> {
fn symbol(&self) -> String {
let mut symbol = String::new();
let mut first = true;
for reaction_compound in &self.compounds {
if !first {
symbol += " + ";
}
first = false;
symbol += &reaction_compound.symbol();
}
symbol
}
fn name(&self) -> String {
let mut name = String::new();
let mut first = true;
for reaction_compound in &self.compounds {
if !first {
name += " + ";
}
first = false;
name += &reaction_compound.name();
}
name
}
fn mass(&self) -> AtomMass {
let mut mass = AtomMass::from(0.0);
for reaction_compound in &self.compounds {
mass += reaction_compound.mass();
}
mass
}
fn is_diatomic(&self) -> bool {
// Reactions can't be diatomic
false
}
}
impl<E: Element> Properties for ReactionCompound<E> {
fn symbol(&self) -> String {
let mut symbol = String::new();
if self.amount > 1 {
symbol += &self.amount.to_string();
}
symbol += &self.element.symbol();
symbol
}
fn name(&self) -> String {
let mut name = String::new();
if self.amount > 1 {
name += &self.amount.to_string();
name += " ";
}
name += &self.element.name();
name
}
fn mass(&self) -> AtomMass {
self.element.mass() * (AtomMassType::from(self.amount))
}
fn is_diatomic(&self) -> bool {
self.element.is_diatomic()
}
}
impl<E: Element> Element for ReactionCompound<E> {
fn get_charge(&self) -> Option<AtomCharge> {
self.element.get_charge()
}
fn get_molecule(self) -> Option<Molecule> {
self.element.get_molecule()
}
fn get_ion(self) -> Option<Ion> {
self.element.get_ion()
}
}<|fim▁end|> | } |
<|file_name|>index.tsx<|end_file_name|><|fim▁begin|>import React from 'react';
import styled from '@emotion/styled';
import space from 'app/styles/space';
import {getListSymbolStyle, listSymbol} from './utils';
type Props = {
children: Array<React.ReactElement>;
symbol?: keyof typeof listSymbol | React.ReactElement;
className?: string;
};
const List = styled(({children, className, symbol, ...props}: Props) => {
const getWrapperComponent = () => {
switch (symbol) {
case 'numeric':
case 'colored-numeric':
return 'ol';
default:
return 'ul';<|fim▁hole|> };
const Wrapper = getWrapperComponent();
return (
<Wrapper className={className} {...props}>
{!symbol || typeof symbol === 'string'
? children
: React.Children.map(children, child => {
if (!React.isValidElement(child)) {
return child;
}
return React.cloneElement(child as React.ReactElement, {
symbol,
});
})}
</Wrapper>
);
})`
margin: 0;
padding: 0;
list-style: none;
display: grid;
grid-gap: ${space(0.5)};
${p =>
typeof p.symbol === 'string' &&
listSymbol[p.symbol] &&
getListSymbolStyle(p.theme, p.symbol)}
`;
export default List;<|fim▁end|> | } |
<|file_name|>RunCommand.java<|end_file_name|><|fim▁begin|><|fim▁hole|> * Copyright (C) 2015. Chris Lutte
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.relicum.ipsum.Menus;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import com.relicum.ipsum.Conversations.MMPlayer;
/**
* Name: RunCommand.java Created: 21 January 2015
*
* @author Relicum
* @version 0.0.1
*/
public class RunCommand implements Perform {
private List<String> commands;
@Getter
private boolean useConsole;
@Getter
private MMPlayer player;
public RunCommand() {
this.commands = new ArrayList<>();
}
@Override
public void addCommand(String cmd) {
commands.add(cmd);
}
@Override
public List<String> getCommands() {
return commands;
}
@Override
public void setUseConsole(boolean use) {
Validate.notNull(use);
this.useConsole = use;
}
@Override
public void addPlayer(MMPlayer player) {
Validate.notNull(player);
this.player = player;
}
@Override
public void perform() {
for (String cmd : commands) {
if (useConsole)
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), cmd.replaceAll("\\\\", ""));
else
this.player.performCommand(cmd.replaceAll("\\\\", "/"));
}
}
}<|fim▁end|> | /*
* Ipsum is a rapid development API for Minecraft, developer by Relicum |
<|file_name|>TravelRecommendation_faster.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
"""
Copyright 2015 Ericsson AB
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
import numpy
import math
import datetime
import requests
import json
import re
from operator import itemgetter
from bson.objectid import ObjectId
from pyspark import SparkContext, SparkConf
from pymongo import MongoClient
from pyspark.mllib.clustering import KMeans, KMeansModel
from numpy import array
from math import sqrt
from geopy.distance import vincenty
# Weights
W_1 = 1.2
W_2 = .8
DISTANCE_THRESHOLD = 0.3
NUM_OF_IT = 8
MIN_LATITUDE = 59.78
MAX_LATITUDE = 59.92
MIN_LONGITUDE = 17.53
MAX_LONGITUDE = 17.75
MIN_COORDINATE = -13750
MAX_COORDINATE = 13750
CIRCLE_CONVERTER = math.pi / 43200
NUMBER_OF_RECOMMENDATIONS = 5
client2 = MongoClient('130.238.15.114')
db2 = client2.monad1
client3 = MongoClient('130.238.15.114')
db3 = client3.monad1
start = datetime.datetime.now()
dontGoBehind = 0
def time_approximation(lat1, lon1, lat2, lon2):
point1 = (lat1, lon1)
point2 = (lat2, lon2)
distance = vincenty(point1, point2).kilometers
return int(round(distance / 10 * 60))
def retrieve_requests():
TravelRequest = db2.TravelRequest
return TravelRequest
def populate_requests(TravelRequest):
results = db2.TravelRequest.find()
for res in results:
dist = time_approximation(res['startPositionLatitude'],
res['startPositionLongitude'],
res['endPositionLatitude'],
res['endPositionLongitude'])
if res['startTime'] == "null":
users.append((res['userID'],(res['startPositionLatitude'],
res['startPositionLongitude'], res['endPositionLatitude'],
res['endPositionLongitude'],
(res['endTime'] - datetime.timedelta(minutes = dist)).time(),
(res['endTime']).time())))
elif res['endTime'] == "null":
users.append((res['userID'],(res['startPositionLatitude'],
res['startPositionLongitude'], res['endPositionLatitude'],
res['endPositionLongitude'], (res['startTime']).time(),
(res['startTime'] + datetime.timedelta(minutes = dist)).time())))
else:
users.append((res['userID'],(res['startPositionLatitude'],
res['startPositionLongitude'], res['endPositionLatitude'],
res['endPositionLongitude'], (res['startTime']).time(),
(res['endTime']).time())))
def get_today_timetable():
TimeTable = db2.TimeTable
first = datetime.datetime.today()
first = first.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
route = TimeTable.find({'date': {'$gte': first}})
return route
def populate_timetable():
route = get_today_timetable()
waypoints = []
for res in route:
for res1 in res['timetable']:
for res2 in db2.BusTrip.find({'_id': res1}):
for res3 in res2['trajectory']:
for res4 in db2.BusStop.find({'_id':res3['busStop']}):
waypoints.append((res3['time'],res4['latitude'],
res4['longitude'], res4['name']))
routes.append((res1, waypoints))
waypoints = []
def iterator(waypoints):
Waypoints = []
for res in waypoints:
Waypoints.append((lat_normalizer(res[1]), lon_normalizer(res[2]),
time_normalizer(to_coordinates(to_seconds(res[0]))[0]),
time_normalizer(to_coordinates(to_seconds(res[0]))[1]),
res[3]))
return Waypoints
# Converting time object to seconds
def to_seconds(dt):
total_time = dt.hour * 3600 + dt.minute * 60 + dt.second
return total_time
# Mapping seconds value to (x, y) coordinates
def to_coordinates(secs):
angle = float(secs) * CIRCLE_CONVERTER
x = 13750 * math.cos(angle)
y = 13750 * math.sin(angle)
return x, y
# Normalization functions
def time_normalizer(value):
new_value = float((float(value) - MIN_COORDINATE) /
(MAX_COORDINATE - MIN_COORDINATE))
return new_value /2
def lat_normalizer(value):
new_value = float((float(value) - MIN_LATITUDE) /
(MAX_LATITUDE - MIN_LATITUDE))
return new_value
def lon_normalizer(value):
new_value = float((float(value) - MIN_LONGITUDE) /
(MAX_LONGITUDE - MIN_LONGITUDE))
return new_value
# Function that implements the kmeans algorithm to group users requests
def kmeans(iterations, theRdd):
def error(point):
center = clusters.centers[clusters.predict(point)]
return sqrt(sum([x**2 for x in (point - center)]))
clusters = KMeans.train(theRdd, iterations, maxIterations=10,
runs=10, initializationMode="random")
WSSSE = theRdd.map(lambda point: error(point)).reduce(lambda x, y: x + y)
return WSSSE, clusters
# Function that runs iteratively the kmeans algorithm to find the best number
# of clusters to group the user's request
def optimalk(theRdd):
results = []
for i in range(NUM_OF_IT):
results.append(kmeans(i+1, theRdd)[0])
optimal = []
for i in range(NUM_OF_IT-1):
optimal.append(results[i] - results[i+1])
optimal1 = []
for i in range(NUM_OF_IT-2):
optimal1.append(optimal[i] - optimal[i+1])
return (optimal1.index(max(optimal1)) + 2)
def back_to_coordinates(lat, lon):
new_lat = (lat * (MAX_LATITUDE - MIN_LATITUDE)) + MIN_LATITUDE
new_lon = (lon * (MAX_LONGITUDE - MIN_LONGITUDE)) + MIN_LONGITUDE
return new_lat, new_lon
def nearest_stops(lat, lon, dist):
stops = []
url = "http://130.238.15.114:9998/get_nearest_stops_from_coordinates"
data = {'lon': lon, 'lat': lat, 'distance': dist}
headers = {'Content-type': 'application/x-www-form-urlencoded'}
answer = requests.post(url, data = data, headers = headers)
p = re.compile("(u'\w*')")
answer = p.findall(answer.text)
answer = [x.encode('UTF8') for x in answer]
answer = [x[2:-1] for x in answer]
answer = list(set(answer))
return answer
# The function that calculate the distance from the given tuple to all the
# cluster centroids and returns the minimum disstance
def calculate_distance_departure(tup1):
dist_departure = []
pos_departure = []
cent_num = 0
for i in selected_centroids:
position = -1
min_value = 1000
min_position = 0
centroid_departure = (i[0]*W_1, i[1]*W_1,i[4]*W_2, i[5]*W_2)
centroid_departure = numpy.array(centroid_departure)
trajectory = []
for l in range(len(tup1)-1):
position = position + 1
if(tup1[l][4] in nearest_stops_dep[cent_num]):
current_stop = (numpy.array(tup1[l][:4])
* numpy.array((W_1,W_1,W_2,W_2)))
distance = numpy.linalg.norm(centroid_departure - current_stop)
if (distance < min_value):
min_value = distance
min_position = position
result = min_value
dist_departure.append(result)
pos_departure.append(min_position)
cent_num += 1
return {"dist_departure":dist_departure,"pos_departure":pos_departure}
def calculate_distance_arrival(tup1,pos_departure):
dist_arrival = []
pos_arrival = []
counter=-1
cent_num = 0
for i in selected_centroids:
min_value = 1000
min_position = 0
centroid_arrival = (i[2]*W_1, i[3]*W_1, i[6]*W_2, i[7]*W_2)
centroid_arrival = numpy.array(centroid_arrival)
counter = counter + 1
position = pos_departure[counter]
for l in range(pos_departure[counter]+1, len(tup1)):
position = position + 1
if(tup1[l][4] in nearest_stops_arr[cent_num]):
current_stop = (numpy.array(tup1[l][:4])
* numpy.array((W_1,W_1,W_2,W_2)))
distance = numpy.linalg.norm(centroid_arrival - current_stop)
if (distance < min_value):
min_value = distance
min_position = position
result = min_value
dist_arrival.append(result)
pos_arrival.append(min_position)
cent_num += 1
return {"dist_arrival":dist_arrival,"pos_arrival":pos_arrival}
def remove_duplicates(alist):
return list(set(map(lambda (w, x, y, z): (w, y, z), alist)))
def recommendations_to_return(alist):
for rec in alist:
trip = db2.BusTrip.find_one({'_id': rec[0]})
traj = trip['trajectory'][rec[2]:rec[3]+1]
trajectory = []
names_only = []
for stop in traj:
name_and_time = (db2.BusStop.find_one({"_id": stop['busStop']})
['name']), stop['time']
trajectory.append(name_and_time)
names_only.append(name_and_time[0])
busid = 1.0
line = trip['line']
result = (int(line), int(busid), names_only[0], names_only[-1],
names_only, trajectory[0][1], trajectory[-1][1], rec[0])
to_return.append(result)
def recommendations_to_db(user, alist):
rec_list = []
for item in to_return:
o_id = ObjectId()
line = item[0]
bus_id = item[1]
start_place = item[2]
end_place = item[3]
start_time = item[5]
end_time = item[6]
bus_trip_id = item[7]
request_time = "null"
feedback = -1
request_id = "null"
next_trip = "null"
booked = False
trajectory = item[4]
new_user_trip = {
"_id":o_id,
"userID" : user,
"line" : line,
"busID" : bus_id,
"startBusStop" : start_place,
"endBusStop" : end_place,
"startTime" : start_time,
"busTripID" : bus_trip_id,
"endTime" : end_time,
"feedback" : feedback,
"trajectory" : trajectory,
"booked" : booked
}
new_recommendation = {
"userID": user,
"userTrip": o_id
}
db3.UserTrip.insert(new_user_trip)
db3.TravelRecommendation.insert(new_recommendation)
def empty_past_recommendations():
db3.TravelRecommendation.drop()
if __name__ == "__main__":
user_ids = []
users = []
routes = []
user_ids = []
sc = SparkContext()
populate_timetable()
my_routes = sc.parallelize(routes, 8)
my_routes = my_routes.map(lambda (x,y): (x, iterator(y))).cache()
req = retrieve_requests()
populate_requests(req)
start = datetime.datetime.now()
initial_rdd = sc.parallelize(users, 4).cache()
user_ids_rdd = (initial_rdd.map(lambda (x,y): (x,1))
.reduceByKey(lambda a, b: a + b)
.collect())
'''
for user in user_ids_rdd:
user_ids.append(user[0])
'''
empty_past_recommendations()
user_ids = []
user_ids.append(1)
for userId in user_ids:
userId = 1
recommendations = []
transition = []
final_recommendation = []
selected_centroids = []
routes_distances = []
to_return = []
nearest_stops_dep = []
nearest_stops_arr = []
my_rdd = (initial_rdd.filter(lambda (x,y): x == userId)
.map(lambda (x,y): y)).cache()
my_rdd = (my_rdd.map(lambda x: (x[0], x[1], x[2], x[3],
to_coordinates(to_seconds(x[4])),
to_coordinates(to_seconds(x[5]))))
.map(lambda (x1, x2, x3, x4, (x5, x6), (x7, x8)):
(lat_normalizer(x1), lon_normalizer(x2),<|fim▁hole|> time_normalizer(x7), time_normalizer(x8))))
selected_centroids = kmeans(4, my_rdd)[1].centers
for i in range(len(selected_centroids)):
cent_lat, cent_long = back_to_coordinates(selected_centroids[i][0],
selected_centroids[i][1])
nearest_stops_dep.append(nearest_stops(cent_lat, cent_long, 200))
cent_lat, cent_long = back_to_coordinates(selected_centroids[i][2],
selected_centroids[i][3])
nearest_stops_arr.append(nearest_stops(cent_lat, cent_long, 200))
routes_distances = my_routes.map(lambda x: (x[0],
calculate_distance_departure(x[1])['dist_departure'],
calculate_distance_arrival(x[1],
calculate_distance_departure(x[1])['pos_departure'])['dist_arrival'],
calculate_distance_departure(x[1])['pos_departure'],
calculate_distance_arrival(x[1],
calculate_distance_departure(x[1])['pos_departure'])['pos_arrival']))
for i in range(len(selected_centroids)):
sort_route = (routes_distances.map(lambda (v, w, x, y, z):
(v, w[i] + x[i], y[i], z[i]))
.sortBy(lambda x:x[1]))
final_recommendation.append((sort_route
.take(NUMBER_OF_RECOMMENDATIONS)))
for sug in final_recommendation:
for i in range(len(sug)):
temp = []
for j in range(len(sug[i])):
temp.append(sug[i][j])
recommendations.append(temp)
recommendations.sort(key=lambda x: x[1])
recommendations_final = []
for rec in recommendations:
if abs(rec[2] - rec[3]) > 1 and rec[1] < DISTANCE_THRESHOLD:
recommendations_final.append(rec)
recommendations = recommendations_final[:10]
recommendations_to_return(recommendations)
recommendations_to_db(userId, to_return)<|fim▁end|> | lat_normalizer(x3), lon_normalizer(x4),
time_normalizer(x5), time_normalizer(x6), |
<|file_name|>kernel_darwin.go<|end_file_name|><|fim▁begin|>//go:build darwin
// +build darwin
// Package kernel provides helper function to get, parse and compare kernel
// versions for different platforms.
package kernel // import "github.com/docker/docker/pkg/parsers/kernel"
import (
"fmt"
"os/exec"
"strings"
)<|fim▁hole|>// GetKernelVersion gets the current kernel version.
func GetKernelVersion() (*VersionInfo, error) {
osName, err := getSPSoftwareDataType()
if err != nil {
return nil, err
}
release, err := getRelease(osName)
if err != nil {
return nil, err
}
return ParseRelease(release)
}
// getRelease uses `system_profiler SPSoftwareDataType` to get OSX kernel version
func getRelease(osName string) (string, error) {
var release string
data := strings.Split(osName, "\n")
for _, line := range data {
if !strings.Contains(line, "Kernel Version") {
continue
}
// It has the format like ' Kernel Version: Darwin 14.5.0'
content := strings.SplitN(line, ":", 2)
if len(content) != 2 {
return "", fmt.Errorf("Kernel Version is invalid")
}
prettyNames := strings.SplitN(strings.TrimSpace(content[1]), " ", 2)
if len(prettyNames) != 2 {
return "", fmt.Errorf("Kernel Version needs to be 'Darwin x.x.x' ")
}
release = prettyNames[1]
}
return release, nil
}
func getSPSoftwareDataType() (string, error) {
cmd := exec.Command("system_profiler", "SPSoftwareDataType")
osName, err := cmd.Output()
if err != nil {
return "", err
}
return string(osName), nil
}<|fim▁end|> | |
<|file_name|>clear_posts_same.py<|end_file_name|><|fim▁begin|><|fim▁hole|># -*- coding: utf-8 -*-
# __author__ = chenchiyuan
from __future__ import division, unicode_literals, print_function
from django.core.management import BaseCommand
from applications.posts.models import Post
class Command(BaseCommand):
def handle(self, *args, **options):
posts = Post.objects.all()
delete_ids = []
for post in posts:
print(post.title)
if post.title < 4:
continue
check_posts = Post.objects.filter(title=post.title).order_by('-rating')
dirty_ids = check_posts[1:].values_list("id", flat=True)
delete_ids.extend(dirty_ids)
Post.objects.filter(id__in=list(set(delete_ids))).delete()<|fim▁end|> | |
<|file_name|>exceptions.py<|end_file_name|><|fim▁begin|><|fim▁hole|>class MailgunException(Exception):
pass<|fim▁end|> | |
<|file_name|>myLibs.js<|end_file_name|><|fim▁begin|><|fim▁hole|> this.add = function(id, value){
if( id )
this.client[id] = value;
else
throw "Não da pra adicionar um valor [ " + id + " ] ao dicionario hash;";
}
this.remove = function(id){
delete this.client[id];
}
this.clear = function(){
delete this.client;
this.client = {};
}
this.length = function(){
return Object.keys( this.client ).length;
}
this.get = function(id){
return this.client[id];
}
this.find = function(id){
if (this.client[id] == undefined)
return false
else
return true;
}
this.getAll = function(){
return Object.values(this.client);
}
this.broadcast = function(evt, msg){
for (var key in this.client) {
this.client[key].socket.emit(evt, msg);
}
}
this.getData = function(id){
return this.client[id].data;
}
this.getAllData = function(evt, msg){
var array = [];
for (var key in this.client) {
array.push( this.client[key].data );
}
return array;
}
this.getAllDataObj = function(evt, msg){
var obj = {};
for (var key in this.client) {
obj[key] = this.client[key].data;
}
return obj;
}
this.clone = function(){
var list = new ConnectionList();
for (var key in this.client) {
list.add( key, this.client[key] );
}
return list;
}
}
module.exports = ConnectionList;<|fim▁end|> | function ConnectionList(){
this.client = {};
|
<|file_name|>test_cts_collection_inheritance.py<|end_file_name|><|fim▁begin|>from unittest import TestCase
from MyCapytain.resources.collections.cts import XmlCtsTextInventoryMetadata, XmlCtsTextgroupMetadata, XmlCtsWorkMetadata, XmlCtsEditionMetadata, XmlCtsTranslationMetadata<|fim▁hole|> SENECA = f.read()
class TestCollectionCtsInheritance(TestCase):
def test_types(self):
TI = XmlCtsTextInventoryMetadata.parse(resource=SENECA)
self.assertCountEqual(
[type(descendant) for descendant in TI.descendants],
[XmlCtsTextgroupMetadata] + [XmlCtsWorkMetadata] * 10 + [XmlCtsEditionMetadata] * 10,
"Descendant should be correctly parsed into correct types"
)
self.assertCountEqual(
[type(descendant) for descendant in TI.readableDescendants],
[XmlCtsWorkMetadata] * 0 + [XmlCtsEditionMetadata] * 10,
"Descendant should be correctly parsed into correct types and filtered when readable"
)
def test_title(self):
TI = XmlCtsTextInventoryMetadata.parse(resource=SENECA)
self.assertCountEqual(
[str(descendant.get_label()) for descendant in TI.descendants],
["Seneca, Lucius Annaeus", "de Ira", "de Vita Beata", "de consolatione ad Helviam", "de Constantia",
"de Tranquilitate Animi", "de Brevitate Vitae", "de consolatione ad Polybium",
"de consolatione ad Marciam", "de Providentia", "de Otio Sapientis", "de Ira, Moral essays Vol 2",
"de Vita Beata, Moral essays Vol 2", "de consolatione ad Helviam, Moral essays Vol 2",
"de Constantia, Moral essays Vol 2", "de Tranquilitate Animi, Moral essays Vol 2",
"de Brevitate Vitae, Moral essays Vol 2", "de consolatione ad Polybium, Moral essays Vol 2",
"de consolatione ad Marciam, Moral essays Vol 2", "de Providentia, Moral essays Vol 2",
"de Otio Sapientis, Moral essays Vol 2"],
"Title should be computed correctly : default should be set"
)
def test_new_object(self):
""" When creating an object with same urn, we should retrieve the same metadata"""
TI = XmlCtsTextInventoryMetadata.parse(resource=SENECA)
a = TI["urn:cts:latinLit:stoa0255.stoa012.perseus-lat2"].metadata
b = (CtsTextgroupMetadata("urn:cts:latinLit:stoa0255")).metadata<|fim▁end|> | from MyCapytain.resources.prototypes.cts.inventory import CtsTextgroupMetadata
with open("tests/testing_data/examples/getcapabilities.seneca.xml") as f: |
<|file_name|>test_methodbinder1.py<|end_file_name|><|fim▁begin|>#####################################################################################
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of this distribution. If
# you cannot locate the Apache License, Version 2.0, please send an email to
# [email protected]. By using this source code in any fashion, you are agreeing to be bound
# by the terms of the Apache License, Version 2.0.
#
# You must not remove this notice, or any other, from this software.
#
#
#####################################################################################
#
# PART 1. how IronPython choose the CLI method, treat parameters WHEN NO OVERLOADS PRESENT
#
from iptest.assert_util import *
from iptest.type_util import *
skiptest("win32")
load_iron_python_test()
from IronPythonTest.BinderTest import *
myint1, myint2 = myint(20), myint(-20)
mylong1, mylong2 = mylong(3), mylong(-4)
myfloat1, myfloat2 = myfloat(4.5), myfloat(-4.5)
mycomplex1 = mycomplex(3)
funcs = '''
M100 M201 M202 M203 M204 M205 M301 M302 M303 M304
M310 M311 M312 M313 M320 M321 M400 M401 M402 M403
M404 M410 M411 M450 M451
M500 M510 M600 M610 M611 M620 M630
M650 M651 M652 M653
M680 M700 M701
M710 M715
'''.split()
args = '''
NoArg Int32 Double BigInt Bool String SByte Int16 Int64 Single
Byte UInt16 UInt32 UInt64 Char Decml Object I C1 C2
S1 A C6 E1 E2
ArrInt32 ArrI ParamArrInt32 ParamArrI ParamArrS Int32ParamArrInt32 IParamArrI
IListInt Array IEnumerableInt IEnumeratorInt
NullableInt RefInt32 OutInt32
DefValInt32 Int32DefValInt32
'''.split()
arg2func = dict(list(zip(args, funcs)))
func2arg = dict(list(zip(funcs, args)))
TypeE = TypeError
OverF = OverflowError
def _get_funcs(args): return [arg2func[x] for x in args.split()]
def _self_defined_method(name): return len(name) == 4 and name[0] == "M"
def _my_call(func, arg):
if isinstance(arg, tuple):
l = len(arg)
# by purpose
if l == 0: func()
elif l == 1: func(arg[0])
elif l == 2: func(arg[0], arg[1])
elif l == 3: func(arg[0], arg[1], arg[2])
elif l == 4: func(arg[0], arg[1], arg[2], arg[3])
elif l == 5: func(arg[0], arg[1], arg[2], arg[3], arg[4])
elif l == 6: func(arg[0], arg[1], arg[2], arg[3], arg[4], arg[5])
else: func(*arg)
else:
func(arg)
def _helper(func, positiveArgs, flagValue, negativeArgs, exceptType):
for arg in positiveArgs:
try:
_my_call(func, arg)
except Exception as e:
Fail("unexpected exception %s when calling %s with %s\n%s" % (e, func, arg, func.__doc__))
else:
AreEqual(Flag.Value, flagValue)
Flag.Value = -188
for arg in negativeArgs:
try:
_my_call(func, arg)
except Exception as e:
if not isinstance(e, exceptType):
Fail("expected '%s', but got '%s' when calling %s with %s\n%s" % (exceptType, e, func, arg, func.__doc__))
else:
Fail("expected exception (but didn't get one) when calling func %s on args %s\n%s" % (func, arg, func.__doc__))
def test_this_matrix():
'''
This will test the full matrix.
To print the matrix, enable the following flag
'''
print_the_matrix = False
funcnames = "M201 M680 M202 M203 M204 M205 M301 M302 M303 M304 M310 M311 M312 M313 M320 M321 M400".split()
matrix = (
#### M201 M680 M202 M203 M204 M205 M301 M302 M303 M304 M310 M311 M312 M313 M320 M321 M400
#### int int? double bigint bool str sbyte i16 i64 single byte ui16 ui32 ui64 char decm obj
( "SByteMax", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( "ByteMax", True, True, True, True, True, TypeE, OverF, True, True, True, True, True, True, True, TypeE, True, True, ),
( "Int16Max", True, True, True, True, True, TypeE, OverF, True, True, True, OverF, True, True, True, TypeE, True, True, ),
( "UInt16Max", True, True, True, True, True, TypeE, OverF, OverF, True, True, OverF, True, True, True, TypeE, True, True, ),
( "intMax", True, True, True, True, True, TypeE, OverF, OverF, True, True, OverF, OverF, True, True, TypeE, True, True, ),
( "UInt32Max", OverF, OverF, True, True, True, TypeE, OverF, OverF, True, True, OverF, OverF, True, True, TypeE, True, True, ),
( "Int64Max", OverF, OverF, True, True, True, TypeE, OverF, OverF, True, True, OverF, OverF, OverF, True, TypeE, True, True, ),
( "UInt64Max", OverF, OverF, True, True, True, TypeE, OverF, OverF, OverF, True, OverF, OverF, OverF, True, TypeE, True, True, ),
( "DecimalMax", OverF, OverF, True, True, True, TypeE, OverF, OverF, OverF, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
( "SingleMax", OverF, OverF, True, True, True, TypeE, OverF, OverF, OverF, True, OverF, OverF, OverF, OverF, TypeE, OverF, True, ),
( "floatMax", OverF, OverF, True, True, True, TypeE, OverF, OverF, OverF, True, OverF, OverF, OverF, OverF, TypeE, OverF, True, ),
#### M201 M680 M202 M203 M204 M205 M301 M302 M303 M304 M310 M311 M312 M313 M320 M321 M400
#### int int? double bigint bool str sbyte i16 i64 single byte ui16 ui32 ui64 char decm obj
( "SByteMin", True, True, True, True, True, TypeE, True, True, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
( "ByteMin", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( "Int16Min", True, True, True, True, True, TypeE, OverF, True, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
( "UInt16Min", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( "intMin", True, True, True, True, True, TypeE, OverF, OverF, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
( "UInt32Min", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( "Int64Min", OverF, OverF, True, True, True, TypeE, OverF, OverF, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
( "UInt64Min", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( "DecimalMin", OverF, OverF, True , True, True, TypeE, OverF, OverF, OverF, True, OverF, OverF, OverF, OverF, TypeE, True , True, ),
( "SingleMin", OverF, OverF, True, True, True, TypeE, OverF, OverF, OverF, True, OverF, OverF, OverF, OverF, TypeE, OverF, True, ),
( "floatMin", OverF, OverF, True, True, True, TypeE, OverF, OverF, OverF, True, OverF, OverF, OverF, OverF, TypeE, OverF, True, ),
#### M201 M680 M202 M203 M204 M205 M301 M302 M303 M304 M310 M311 M312 M313 M320 M321 M400
#### int int? double bigint bool str sbyte i16 i64 single byte ui16 ui32 ui64 char decm obj
( "SBytePlusOne", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( "BytePlusOne", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( "Int16PlusOne", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( "UInt16PlusOne", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( "intPlusOne", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( myint1, True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( "UInt32PlusOne", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( "Int64PlusOne", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( "UInt64PlusOne", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( "DecimalPlusOne", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( "SinglePlusOne", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( "floatPlusOne", True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( myfloat1, True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
#### M201 M680 M202 M203 M204 M205 M301 M302 M303 M304 M310 M311 M312 M313 M320 M321 M400
#### int int? double bigint bool str sbyte i16 i64 single byte ui16 ui32 ui64 char decm obj
( "SByteMinusOne", True, True, True, True, True, TypeE, True, True, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
( "Int16MinusOne", True, True, True, True, True, TypeE, True, True, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
( "intMinusOne", True, True, True, True, True, TypeE, True, True, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
( myint2, True, True, True, True, True, TypeE, True, True, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
( "Int64MinusOne", True, True, True, True, True, TypeE, True, True, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
( "DecimalMinusOne", True, True, True, True, True, TypeE, True, True, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
( "SingleMinusOne", True, True, True, True, True, TypeE, True, True, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
( "floatMinusOne", True, True, True, True, True, TypeE, True, True, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
( myfloat2, True, True, True, True, True, TypeE, True, True, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
################################################## pass in bool #########################################################
#### M201 M680 M202 M203 M204 M205 M301 M302 M303 M304 M310 M311 M312 M313 M320 M321 M400
#### int int? double bigint bool str sbyte i16 i64 single byte ui16 ui32 ui64 char decm obj
( True, True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( False, True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
################################################## pass in BigInt #########################################################
#### int int? double bigint bool str sbyte i16 i64 single byte ui16 ui32 ui64 char decm obj
#### M201 M680 M202 M203 M204 M205 M301 M302 M303 M304 M310 M311 M312 M313 M320 M321 M400
( 10, True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( -10, True, True, True, True, True, TypeE, True, True, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
( 1234567890123456, OverF, OverF, True , True, True, TypeE, OverF, OverF, True, True, OverF, OverF, OverF, True, TypeE, True, True, ),
( mylong1, True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ),
( mylong2, True, True, True, True, True, TypeE, True, True, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ),
################################################## pass in Complex #########################################################
#### M201 M680 M202 M203 M204 M205 M301 M302 M303 M304 M310 M311 M312 M313 M320 M321 M400
#### int int? double bigint bool str sbyte i16 i64 single byte ui16 ui32 ui64 char decm obj
( (3+0j), TypeE, TypeE, TypeE, TypeE, True, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, True, ),
( (3+1j), TypeE, TypeE, TypeE, TypeE, True, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, True, ),
( mycomplex1, TypeE, TypeE, TypeE, TypeE, True, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, True, )
)
if is_silverlight==False:
InvariantCulture = System.Globalization.CultureInfo.InvariantCulture
matrix = list(matrix)
################################################## pass in char #########################################################
#### M201 M680 M202 M203 M204 M205 M301 M302 M303 M304 M310 M311 M312 M313 M320 M321 M400
#### int int? double bigint bool str sbyte i16 i64 single byte ui16 ui32 ui64 char decm obj
matrix.append((System.Char.Parse('A'), TypeE, TypeE, TypeE, TypeE, True, True, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, TypeE, True, True, True, ))
################################################## pass in float #########################################################
#### single/double becomes Int32, but this does not apply to other primitive types
#### int int? double bigint bool str sbyte i16 i64 single byte ui16 ui32 ui64 char decm obj
matrix.append((System.Single.Parse("8.01", InvariantCulture), True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ))
matrix.append((System.Double.Parse("10.2", InvariantCulture), True, True, True, True, True, TypeE, True, True, True, True, True, True, True, True, TypeE, True, True, ))
matrix.append((System.Single.Parse("-8.1", InvariantCulture), True, True, True, True, True, TypeE, True, True, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ))
matrix.append((System.Double.Parse("-1.8", InvariantCulture), True, True, True, True, True, TypeE, True, True, True, True, OverF, OverF, OverF, OverF, TypeE, True, True, ))
matrix = tuple(matrix)
for scenario in matrix:
if isinstance(scenario[0], str):
value = clr_numbers[scenario[0]]
if print_the_matrix: print('(%18s,' % ('"'+ scenario[0] +'"'), end=' ')
else:
value = scenario[0]
if print_the_matrix: print('(%18s,' % value, end=' ')
for i in range(len(funcnames)):
funcname = funcnames[i]
func = getattr(target, funcname)
if print_the_matrix:
try:
func(value)
print("True, ", end=' ')
except TypeError:
print("TypeE,", end=' ')
except OverflowError:
print("OverF,", end=' ')
print("),")
else:
try:
func(value)
except Exception as e:
if scenario[i+1] not in [TypeE, OverF]:
Fail("unexpected exception %s, when func %s on arg %s (%s)\n%s" % (e, funcname, scenario[0], type(value), func.__doc__))
if isinstance(e, scenario[i+1]): pass
else: Fail("expect %s, but got %s when func %s on arg %s (%s)\n%s" % (scenario[i+1], e, funcname, scenario[0], type(value), func.__doc__))
else:
if scenario[i+1] in [TypeE, OverF]:
Fail("expect %s, but got none when func %s on arg %s (%s)\n%s" % (scenario[i+1], funcname, scenario[0], type(value), func.__doc__))
left = Flag.Value ; Flag.Value = -99 # reset
right = int(funcname[1:])
if left != right:
Fail("left %s != right %s when func %s on arg %s (%s)\n%s" % (left, right, funcname, scenario[0], type(value), func.__doc__))
# these funcs should behavior same as M201(Int32)
# should have NullableInt too ?
for funcname in _get_funcs('RefInt32 ParamArrInt32 Int32ParamArrInt32'):
for scenario in matrix:
if isinstance(scenario[0], str): value = clr_numbers[scenario[0]]
else: value = scenario[0]
func = getattr(target, funcname)
if scenario[1] not in [TypeE, OverF]:
func(value)
left = Flag.Value
right = int(funcname[1:])
if left != right:
Fail("left %s != right %s when func %s on arg %s" % (left, right, funcname, scenario[0]))
Flag.Value = -99 # reset
else:
try: func(value)
except scenario[1]: pass # 1 is M201
else: Fail("expect %s, but got none when func %s on arg %s" % (scenario[1], funcname, scenario[0]))
def test_char_string_asked():
# char asked
_helper(target.M320, ['a', System.Char.MaxValue, System.Char.MinValue, 'abc'[2]], 320, ['abc', ('a b')], TypeError)
# string asked
_helper(target.M205, ['a', System.Char.MaxValue, System.Char.MinValue, 'abc'[2], 'abc', 'a b' ], 205, [('a', 'b'), 23, ], TypeError)
def test_pass_extensible_types():
# number covered by that matrix
# string or char
mystr1, mystr2 = mystr('a'), mystr('abc')
_helper(target.M205, [mystr1, mystr2, ], 205, [], TypeError) # String
_helper(target.M320, [mystr1, ], 320, [mystr2, ], TypeError) # Char
# check the bool conversion result
def test_bool_asked():
for arg in ['a', 3, object(), True]:
target.M204(arg)
Assert(Flag.BValue, "argument is %s" % arg)
Flag.BValue = False
if is_silverlight==False:
for arg in [0, System.Byte.Parse('0'), System.UInt64.Parse('0'), 0.0, 0, False, None, tuple(), list()]:
target.M204(arg)
Assert(not Flag.BValue, "argument is %s" % (arg,))
Flag.BValue = True
def test_user_defined_conversion():
class CP1:
def __int__(self): return 100
class CP2(object):
def __int__(self): return 99
class CP3: pass
cp1, cp2, cp3 = CP1(), CP2(), CP3()
### 1. not work for Nullable<Int32> required (?)
### 2. (out int): should pass in nothing
### int params int int? ref int defVal int+defVal
works = 'M201 M600 M680 M620 M700 M710 M715'
for fn in works.split():
_helper(getattr(target, fn), [cp1, cp2, ], int(fn[1:]), [cp3, ], TypeError)
for fn in dir(target):
### bool obj
if _self_defined_method(fn) and fn not in (works + 'M204 M400 '):
_helper(getattr(target, fn), [], 0, [cp1, cp2, cp3, ], TypeError)
def test_pass_in_derived_python_types():
class CP1(I): pass
class CP2(C1): pass
class CP3(C2): pass
class CP4(C6, I): pass
cp1, cp2, cp3, cp4 = CP1(), CP2(), CP3(), CP4()
# I asked
_helper(target.M401, [C1(), C2(), S1(), cp1, cp2, cp3, cp4,], 401,[C3(), object()], TypeError)
# C2 asked
_helper(target.M403, [C2(), cp3, ], 403, [C3(), object(), C1(), cp1, cp2, cp4, ], TypeError)
class CP1(A): pass
class CP2(C6): pass
cp1, cp2 = CP1(), CP2()
# A asked
_helper(target.M410, [C6(), cp1, cp2, cp4,], 410, [C3(), object(), C1(), cp3, ], TypeError)
# C6 asked
_helper(target.M411, [C6(), cp2, cp4, ], 411, [C3(), object(), C1(), cp1, cp3,], TypeError)
def test_nullable_int():
_helper(target.M680, [None, 100, 100, System.Byte.MaxValue, System.UInt32.MinValue, myint1, mylong2, 3.6, ], 680, [(), 3+1j], TypeError)
def test_out_int():
if is_silverlight==False:
_helper(target.M701, [], 701, [1, 10, None, System.Byte.Parse('3')], TypeError) # not allow to pass in anything
def test_collections():
arrayInt = array_int((10, 20))
tupleInt = ((10, 20), )
listInt = ([10, 20], )
tupleBool = ((True, False, True, True, False), )
tupleLong1, tupleLong2 = ((10, 20), ), ((System.Int64.MaxValue, System.Int32.MaxValue * 2),)
arrayByte = array_byte((10, 20))
arrayObj = array_object(['str', 10])
# IList<int>
_helper(target.M650, [arrayInt, tupleInt, listInt, arrayObj, tupleLong1, tupleLong2, ], 650, [arrayByte, ], TypeError)
# arrayObj, tupleLong1, tupleLong2 : conversion happens late
# Array
_helper(target.M651, [arrayInt, arrayObj, arrayByte, ], 651, [listInt, tupleInt, tupleLong1, tupleLong2, ], TypeError)
# IEnumerable[int]
_helper(target.M652, [arrayInt, arrayObj, arrayByte, listInt, tupleInt, tupleLong1, tupleLong2, ], 652, [], TypeError)
# IEnumerator[int]
_helper(target.M653, [], 653, [arrayInt, arrayObj, arrayByte, listInt, tupleInt, tupleLong1, tupleLong2, ], TypeError)
# Int32[]
_helper(target.M500, [arrayInt, tupleInt, tupleLong1, tupleBool, ], 500, [listInt, arrayByte, arrayObj, ], TypeError)
_helper(target.M500, [], 500, [tupleLong2, ], OverflowError)
# params Int32[]
_helper(target.M600, [arrayInt, tupleInt, tupleLong1, tupleBool, ], 600, [listInt, arrayByte, arrayObj, ], TypeError)
_helper(target.M600, [], 600, [tupleLong2, ], OverflowError)
# Int32, params Int32[]
_helper(target.M620, [(10, 10), (10, 10), (10, 10), (10, 10), (10, arrayInt), (10, (10, 20)), ], 620, [(10, [10, 20]), ], TypeError)
_helper(target.M620, [], 620, [(10, 123456789101234), ], OverflowError)
arrayI1 = System.Array[I]( (C1(), C2()) )
arrayI2 = System.Array[I]( () )
arrayObj3 = System.Array[object]( (C1(), C2()) )
tupleI = ((C1(), C2()),)
listI = ([C1(), C2()],)
_helper(target.M510, [arrayI1, arrayI2, tupleI, ], 510, [arrayObj3, listI, ], TypeError) # I[]
_helper(target.M610, [arrayI1, arrayI2, tupleI, ], 610, [arrayObj3, listI, ], TypeError) # params I[]
def test_no_arg_asked():
# no args asked
_helper(target.M100, [()], 100, [2, None, (2, None)], TypeError)
def test_enum():
# E1 asked
_helper(target.M450, [E1.A, ], 450, [10, E2.A], TypeError)
# E2: ushort asked
if is_silverlight==False:
_helper(target.M451, [E2.A, ], 451, [10, E1.A, System.UInt16.Parse("3")], TypeError)
def _repeat_with_one_arg(goodStr, getArg):
passSet = _get_funcs(goodStr)
skipSet = []
for fn in passSet:
if fn in skipSet: continue
arg = getArg()
getattr(target, fn)(arg)
left = Flag.Value
right = int(fn[1:])
if left != right:
Fail("left %s != right %s when func %s on arg %s" % (left, right, fn, arg))
for fn in dir(target):
if _self_defined_method(fn) and (fn not in passSet) and (fn not in skipSet):
arg = getArg()
try: getattr(target, fn)(arg)<|fim▁hole|> except TypeError : pass
else: Fail("expect TypeError, but got none when func %s on arg %s" % (fn, arg))
def test_pass_in_none():
test_str = '''
Bool String Object I C1 C2 A C6
ArrInt32 ArrI ParamArrInt32 ParamArrI ParamArrS IParamArrI
IListInt Array IEnumerableInt IEnumeratorInt NullableInt
'''
# Big integers are only nullable in CLR 2
if not is_net40:
test_str = "BigInt " + test_str
_repeat_with_one_arg(test_str, lambda : None)
def test_pass_in_clrReference():
import clr
_repeat_with_one_arg('Object RefInt32 OutInt32', lambda : clr.Reference[int](0))
_repeat_with_one_arg('Object', lambda : clr.Reference[object](None))
_repeat_with_one_arg('Object RefInt32 OutInt32', lambda : clr.Reference[int](10))
_repeat_with_one_arg('Object ', lambda : clr.Reference[float](123.123))
_repeat_with_one_arg('Object', lambda : clr.Reference[type](str)) # ref.Value = (type)
def test_pass_in_nothing():
passSet = _get_funcs('NoArg ParamArrInt32 ParamArrS ParamArrI OutInt32 DefValInt32')
skipSet = [ ] # be empty before release
for fn in passSet:
if fn in skipSet: continue
getattr(target, fn)()
left = Flag.Value
right = int(fn[1:])
if left != right:
Fail("left %s != right %s when func %s on arg Nothing" % (left, right, fn))
for fn in dir(target):
if _self_defined_method(fn) and (fn not in passSet) and (fn not in skipSet):
try: getattr(target, fn)()
except TypeError : pass
else: Fail("expect TypeError, but got none when func %s on arg Nothing" % fn)
def test_other_concern():
target = COtherConcern()
# static void M100()
target.M100()
AreEqual(Flag.Value, 100); Flag.Value = 99
COtherConcern.M100()
AreEqual(Flag.Value, 100); Flag.Value = 99
AssertError(TypeError, target.M100, target)
AssertError(TypeError, COtherConcern.M100, target)
# static void M101(COtherConcern arg)
target.M101(target)
AreEqual(Flag.Value, 101); Flag.Value = 99
COtherConcern.M101(target)
AreEqual(Flag.Value, 101); Flag.Value = 99
AssertError(TypeError, target.M101)
AssertError(TypeError, COtherConcern.M101)
# void M102(COtherConcern arg)
target.M102(target)
AreEqual(Flag.Value, 102); Flag.Value = 99
COtherConcern.M102(target, target)
AreEqual(Flag.Value, 102); Flag.Value = 99
AssertError(TypeError, target.M102)
AssertError(TypeError, COtherConcern.M102, target)
# generic method
target.M200[int](100)
AreEqual(Flag.Value, 200); Flag.Value = 99
target.M200[int](100.1234)
AreEqual(Flag.Value, 200); Flag.Value = 99
target.M200[int](100)
AreEqual(Flag.Value, 200); Flag.Value = 99
AssertError(OverflowError, target.M200[System.Byte], 300)
AssertError(OverflowError, target.M200[int], 12345678901234)
# We should ignore Out attribute on non-byref.
# It's used in native interop scenarios to designate a buffer (StringBUilder, arrays, etc.)
# the caller allocates, passes to the method and expects the callee to populate it with data.
AssertError(TypeError, target.M222)
AreEqual(target.M222(0), None)
AreEqual(Flag.Value, 222)
# what does means when passing in None
target.M300(None)
AreEqual(Flag.Value, 300); Flag.Value = 99
AreEqual(Flag.BValue, True)
target.M300(C1())
AreEqual(Flag.BValue, False)
# void M400(ref Int32 arg1, out Int32 arg2, Int32 arg3) etc...
AreEqual(target.M400(1, 100), (100, 100))
AreEqual(target.M401(1, 100), (100, 100))
AreEqual(target.M402(100, 1), (100, 100))
# default Value
target.M450()
AreEqual(Flag.Value, 80); Flag.Value = 99
# 8 args
target.M500(1,2,3,4,5,6,7,8)
AreEqual(Flag.Value, 500)
AssertError(TypeError, target.M500)
AssertError(TypeError, target.M500, 1)
AssertError(TypeError, target.M500, 1,2,3,4,5,6,7,8,9)
# IDictionary
for x in [ {1:1}, {"str": 3} ]:
target.M550(x)
AreEqual(Flag.Value, 550); Flag.Value = 99
AssertError(TypeError, target.M550, [1, 2])
# not supported
for fn in (target.M600, target.M601, target.M602):
for l in ( {1:'a'}, [1,2], (1,2) ):
AssertError(TypeError, fn, l)
# delegate
def f(x): return x * x
AssertError(TypeError, target.M700, f)
from IronPythonTest import IntIntDelegate
for x in (lambda x: x, lambda x: x*2, f):
target.M700(IntIntDelegate(x))
AreEqual(Flag.Value, x(10)); Flag.Value = 99
target.M701(lambda x: x*2)
AreEqual(Flag.Value, 20); Flag.Value = 99
AssertError(TypeError, target.M701, lambda : 10)
# keywords
x = target.M800(arg1 = 100, arg2 = 200, arg3 = 'this'); AreEqual(x, 'THIS')
x = target.M800(arg3 = 'Python', arg1 = 100, arg2 = 200); AreEqual(x, 'PYTHON')
x = target.M800(100, arg3 = 'iron', arg2 = C1()); AreEqual(x, 'IRON')
try: target.M800(100, 'Yes', arg2 = C1())
except TypeError: pass
else: Fail("expect: got multiple values for keyword argument arg2")
# more ref/out sanity check
import clr
def f1(): return clr.Reference[object](None)
def f2(): return clr.Reference[int](10)
def f3(): return clr.Reference[S1](S1())
def f4(): return clr.Reference[C1](C2()) # C2 inherits C1
for (f, a, b, c, d) in [
('M850', False, False, True, False),
('M851', False, False, False, True),
('M852', False, False, True, False),
('M853', False, False, False, True),
]:
expect = (f in 'M850 M852') and S1 or C1
func = getattr(target, f)
for i in range(4):
ref = (f1, f2, f3, f4)[i]()
if (a,b,c,d)[i]:
func(ref); AreEqual(type(ref.Value), expect)
else:
AssertError(TypeError, func, ref)
# call 854
AssertError(TypeError, target.M854, clr.Reference[object](None))
AssertError(TypeError, target.M854, clr.Reference[int](10))
# call 855
AssertError(TypeError, target.M855, clr.Reference[object](None))
AssertError(TypeError, target.M855, clr.Reference[int](10))
# call 854 and 855 with Reference[bool]
target.M854(clr.Reference[bool](True)); AreEqual(Flag.Value, 854)
target.M855(clr.Reference[bool](True)); AreEqual(Flag.Value, 855)
# practical
ref = clr.Reference[int](0)
ref2 = clr.Reference[int](0)
ref.Value = 300
ref2.Value = 100
## M860(ref arg1, arg2, out arg3): arg3 = arg1 + arg2; arg1 = 100;
x = target.M860(ref, 200, ref2)
AreEqual(x, None)
AreEqual(ref.Value, 100)
AreEqual(ref2.Value, 500)
# pass one clr.Reference(), and leave the other one open
ref.Value = 300
AssertError(TypeError, target.M860, ref, 200)
# the other way
x = target.M860(300, 200)
AreEqual(x, (100, 500))
# GOtherConcern<T>
target = GOtherConcern[int]()
for x in [100, 200, 4.56, myint1]:
target.M100(x)
AreEqual(Flag.Value, 100); Flag.Value = 99
GOtherConcern[int].M100(target, 200)
AreEqual(Flag.Value, 100); Flag.Value = 99
AssertError(TypeError, target.M100, 'abc')
AssertError(OverflowError, target.M100, 12345678901234)
def test_iterator_sequence():
class C:
def __init__(self): self.x = 0
def __iter__(self): return self
def __next__(self):
if self.x < 10:
y = self.x
self.x += 1
return y
else:
self.x = 0
raise StopIteration
def __len__(self): return 10
# different size
c = C()
list1 = [1, 2, 3]
tuple1 = [4, 5, 6, 7]
str1 = "890123"
all = (list1, tuple1, str1, c)
target = COtherConcern()
for x in all:
# IEnumerable / IEnumerator
target.M620(x)
AreEqual(Flag.Value, len(x)); Flag.Value = 0
# built in types are not IEnumerator, they are enumerable
if not isinstance(x, C):
AssertError(TypeError, target.M621, x)
else:
target.M621(x)
AreEqual(Flag.Value, len(x))
# IEnumerable<char> / IEnumerator<char>
target.M630(x)
AreEqual(Flag.Value, len(x)); Flag.Value = 0
AssertError(TypeError, target.M631, x)
# IEnumerable<int> / IEnumerator<int>
target.M640(x)
AreEqual(Flag.Value, len(x)); Flag.Value = 0
AssertError(TypeError, target.M641, x)
# IList / IList<char> / IList<int>
for x in (list1, tuple1):
target.M622(x)
AreEqual(Flag.Value, len(x))
target.M632(x)
AreEqual(Flag.Value, len(x))
target.M642(x)
AreEqual(Flag.Value, len(x))
for x in (str1, c):
AssertError(TypeError, target.M622, x)
AssertError(TypeError, target.M632, x)
AssertError(TypeError, target.M642, x)
def test_explicit_inheritance():
target = CInheritMany1()
Assert(hasattr(target, "M"))
target.M()
AreEqual(Flag.Value, 100)
I1.M(target); AreEqual(Flag.Value, 100); Flag.Value = 0
target = CInheritMany2()
target.M(); AreEqual(Flag.Value, 201)
I1.M(target); AreEqual(Flag.Value, 200)
target = CInheritMany3()
Assert(not hasattr(target, "M"))
try: target.M()
except AttributeError: pass
else: Fail("Expected AttributeError, got none")
I1.M(target); AreEqual(Flag.Value, 300)
I2.M(target); AreEqual(Flag.Value, 301)
target = CInheritMany4()
target.M(); AreEqual(Flag.Value, 401)
I3[object].M(target); AreEqual(Flag.Value, 400)
AssertError(TypeError, I3[int].M, target)
target = CInheritMany5()
I1.M(target); AreEqual(Flag.Value, 500)
I2.M(target); AreEqual(Flag.Value, 501)
I3[object].M(target); AreEqual(Flag.Value, 502)
target.M(); AreEqual(Flag.Value, 503)
target = CInheritMany6[int]()
target.M(); AreEqual(Flag.Value, 601)
I3[int].M(target); AreEqual(Flag.Value, 600)
AssertError(TypeError, I3[object].M, target)
target = CInheritMany7[int]()
Assert(hasattr(target, "M"))
target.M(); AreEqual(Flag.Value, 700)
I3[int].M(target); AreEqual(Flag.Value, 700)
target = CInheritMany8()
Assert(not hasattr(target, "M"))
try: target.M()
except AttributeError: pass
else: Fail("Expected AttributeError, got none")
I1.M(target); AreEqual(Flag.Value, 800); Flag.Value = 0
I4.M(target, 100); AreEqual(Flag.Value, 801)
# target.M(100) ????
# original repro
from System.Collections.Generic import Dictionary
d = Dictionary[object,object]()
d.GetEnumerator() # not throw
def test_nullable_property_double():
from IronPythonTest import NullableTest
nt = NullableTest()
nt.DProperty = 1
AreEqual(nt.DProperty, 1.0)
nt.DProperty = 2.0
AreEqual(nt.DProperty, 2.0)
nt.DProperty = None
AreEqual(nt.DProperty, None)
@disabled("Merlin 309716")
def test_nullable_property_long():
from IronPythonTest import NullableTest
nt = NullableTest()
nt.LProperty = 1
AreEqual(nt.LProperty, 1)
nt.LProperty = 2
AreEqual(nt.LProperty, 2)
nt.LProperty = None
AreEqual(nt.LProperty, None)
def test_nullable_property_bool():
from IronPythonTest import NullableTest
nt = NullableTest()
nt.BProperty = 1.0
AreEqual(nt.BProperty, True)
nt.BProperty = 0.0
AreEqual(nt.BProperty, False)
nt.BProperty = True
AreEqual(nt.BProperty, True)
nt.BProperty = None
AreEqual(nt.BProperty, None)
def test_nullable_property_enum():
from IronPythonTest import NullableTest
nt = NullableTest()
nt.EProperty = NullableTest.NullableEnums.NE1
AreEqual(nt.EProperty, NullableTest.NullableEnums.NE1)
nt.EProperty = None
AreEqual(nt.EProperty, None)
def test_nullable_parameter():
from IronPythonTest import NullableTest
nt = NullableTest()
result = nt.Method(1)
AreEqual(result, 1.0)
result = nt.Method(2.0)
AreEqual(result, 2.0)
result = nt.Method(None)
AreEqual(result, None)
# Skip on silverlight because the System.Configuration is not available
@skip("silverlight")
def test_xequals_call_for_optimization():
"""
Testing specifically for System.Configuration.ConfigurationManager
because currently its .Equals method will throw null reference
exception when called with null argument. This is a case that could
slip through our dynamic site checks.
"""
import clr
clr.AddReference("System.Configuration");
from System.Configuration import ConfigurationManager
c = ConfigurationManager.ConnectionStrings
#Invoke tests multiple times to make sure DynamicSites are utilized
for i in range(3):
AreEqual(1, c.Count)
for i in range(3):
count = c.Count
AreEqual(1, count)
AreEqual(c.Count, count)
for i in range(3):
#just ensure it doesn't throw
c[0].Name
#Just to be sure this doesn't throw...
c.Count
c.Count
def test_interface_only_access():
pc = InterfaceOnlyTest.PrivateClass
# property set
pc.Hello = InterfaceOnlyTest.PrivateClass
# property get
AreEqual(pc.Hello, pc)
# method call w/ interface param
pc.Foo(pc)
# method call w/ interface ret val
AreEqual(pc.RetInterface(), pc)
# events
global fired
fired = False
def fired(*args):
global fired
fired = True
return args[0]
# add event
pc.MyEvent += fired
# fire event
AreEqual(pc.FireEvent(pc.GetEventArgs()), pc)
AreEqual(fired, True)
# remove event
pc.MyEvent -= fired
def test_ref_bytearr():
target = COtherConcern()
arr = System.Array[System.Byte]((2,3,4))
res = target.M702(arr)
AreEqual(Flag.Value, 702)
AreEqual(type(res), System.Array[System.Byte])
AreEqual(len(res), 0)
i, res = target.M703(arr)
AreEqual(Flag.Value, 703)
AreEqual(i, 42)
AreEqual(type(res), System.Array[System.Byte])
AreEqual(len(res), 0)
i, res = target.M704(arr, arr)
AreEqual(Flag.Value, 704)
AreEqual(i, 42)
AreEqual(arr, res)
sarr = clr.StrongBox[System.Array[System.Byte]](arr)
res = target.M702(sarr)
AreEqual(Flag.Value, 702)
AreEqual(res, None)
res = sarr.Value
AreEqual(type(res), System.Array[System.Byte])
AreEqual(len(res), 0)
sarr.Value = arr
i = target.M703(sarr)
AreEqual(Flag.Value, 703)
AreEqual(i, 42)
AreEqual(len(sarr.Value), 0)
i = target.M704(arr, sarr)
AreEqual(Flag.Value, 704)
AreEqual(i, 42)
AreEqual(sarr.Value, arr)
def test_struct_prop_assign():
from IronPythonTest.BinderTest import SOtherConcern
a = SOtherConcern()
a.P100 = 42
AreEqual(a.P100, 42)
def test_generic_type_inference():
from IronPythonTest import GenericTypeInference, GenericTypeInferenceInstance, SelfEnumerable
from System import Array, Exception, ArgumentException
from System.Collections.Generic import IEnumerable, List
from System.Collections.Generic import Dictionary as Dict
class UserGenericType(GenericTypeInferenceInstance): pass
# public PythonType MInst<T>(T x) -> pytype(T)
AreEqual(UserGenericType().MInst(42), int)
class UserObject(object): pass
userInst = UserObject()
userInt, userLong, userFloat, userComplex, userStr = myint(), mylong(), myfloat(), mycomplex(), mystr()
userTuple, userList, userDict = mytuple(), mylist(), mydict()
objArray = System.Array[object]( (1,2,3) )
doubleArray = System.Array[float]( (1.0,2.0,3.0) )
for target in [GenericTypeInference, GenericTypeInferenceInstance(), UserGenericType()]:
tests = [
# simple single type tests, no constraints
# public static PythonType M0<T>(T x) -> pytypeof(T)
# target method, args, Result, KeywordCall, Exception
(target.M0, (1, ), int, True, None),
(target.M0, (userInst, ), object, True, None),
(target.M0, (userInt, ), object, True, None),
(target.M0, (userStr, ), object, True, None),
(target.M0, (userLong, ), object, True, None),
(target.M0, (userFloat, ), object, True, None),
(target.M0, (userComplex, ), object, True, None),
(target.M0, (userTuple, ), tuple, True, None),
(target.M0, (userList, ), list, True, None),
(target.M0, (userDict, ), dict, True, None),
(target.M0, ((), ), tuple, True, None),
(target.M0, ([], ), list, True, None),
(target.M0, ({}, ), dict, True, None),
# multiple arguments
# public static PythonType M1<T>(T x, T y) -> pytypeof(T)
# public static PythonType M2<T>(T x, T y, T z) -> pytypeof(T)
(target.M1, (1, 2), int, True, None),
(target.M2, (1, 2, 3), int, True, None),
(target.M1, (userInst, userInst), object, True, None),
(target.M2, (userInst, userInst, userInst), object, True, None),
(target.M1, (1, 2.0), None, True, TypeError),
(target.M1, (1, 'abc'), None, True, TypeError),
(target.M1, (object(), userInst), object, True, None),
(target.M1, ([], userList), list, True, None),
# params arguments
# public static PythonType M3<T>(params T[] args) -> pytypeof(T)
(target.M3, (), None, False, TypeError),
(target.M3, (1, ), int, False, None),
(target.M3, (1, 2), int, False, None),
(target.M3, (1, 2, 3), int, False, None),
(target.M3, (1, 2.0), object, False, TypeError),
(target.M3, (1, 'abc'), object, False, TypeError),
(target.M3, (object(), userInst), object, False, None),
(target.M3, ([], userList), list, False, None),
# public static PythonType M4<T>(T x, params T[] args) -> pytypeof(T)
(target.M4, (1, 2), int, False, None),
(target.M4, (1, 2.0), object, False, TypeError),
(target.M4, (1, 'abc'), object, False, TypeError),
(target.M4, (object(), userInst), object, False, None),
(target.M4, ([], userList), list, False, None),
# simple constraints
# public static PythonType M5<T>(T x) where T : class -> pytype(T)
# public static PythonType M6<T>(T x) where T : struct -> pytype(T)
# public static PythonType M7<T>(T x) where T : IList -> pytype(T)
(target.M5, (1, ), None, False, TypeError),
(target.M6, ('abc', ), None, False, TypeError),
(target.M7, (object(), ), None, False, TypeError),
(target.M7, (2, ), None, False, TypeError),
(target.M5, ('abc', ), str, False, None),
(target.M5, (object(), ), object, False, None),
(target.M6, (1, ), int, False, None),
(target.M7, ([], ), list, False, None),
(target.M7, (objArray, ), type(objArray),False, None),
# simple dependent constraints
# public static PythonTuple M8<T0, T1>(T0 x, T1 y) where T0 : T1 -> (pytype(T0), pytype(T1))
(target.M8, (1, 2), (int, int), False, None),
(target.M8, ('abc', object()), (str, object),False, None),
(target.M8, (object(), 'abc'), None, False, TypeError),
(target.M8, (1, object()), (int, object),False, None),
(target.M8, (object(), 1), None, False, TypeError),
# no types can be inferred, error
# public static PythonTuple M9<T0, T1>(object x, T1 y) where T0 : T1
# public static PythonTuple M9b<T0, T1>(T0 x, object y) where T0 : T1
# public static PythonType M11<T>(object x)
# public static PythonType M12<T0, T1>(T0 x, object y)
(target.M9, (1, 2), None, False, TypeError),
(target.M9b, (1, 2), None, False, TypeError),
(target.M9, (object(), object()), None, True, TypeError),
(target.M9b, (object(), object()), None, True, TypeError),
(target.M11, (1, ), None, False, TypeError),
(target.M12, (1, 2), None, False, TypeError),
# multiple dependent constraints
# public static PythonTuple M10<T0, T1, T2>(T0 x, T1 y, T2 z) where T0 : T1 where T1 : T2 -> (pytype(T0), pytype(T1), pytype(T2))
(target.M10, (ArgumentException(), Exception(), object()), (ArgumentException, Exception, object),False, None),
(target.M10, (Exception(), ArgumentException(), object()), None,False, TypeError),
(target.M10, (ArgumentException(), object(), Exception()), None,False, TypeError),
(target.M10, (object(), ArgumentException(), Exception()), None,False, TypeError),
(target.M10, (object(), Exception(), ArgumentException()), None,False, TypeError),
# public static PythonType M11<T>(object x) -> pytypeof(T)
# public static PythonType M12<T0, T1>(T0 x, object y) -> pytypeof(T0)
(target.M11, (object(), ), None, True, TypeError),
(target.M12, (3, object()), None, True, TypeError),
# public static PythonType M13<T>(T x, Func<T> y) -> pytype(T), func()
# public static PythonType M14<T>(T x, Action<T> y) -> pytype(T)
# public static PythonTuple M15<T>(T x, IList<T> y) -> pytype, list...
# public static PythonType M16<T>(T x, Dictionary<T, IList<T>> list) -> pytype, listKeys...
(target.M13, (1, lambda: 42), (object, 42), False, None),
(target.M14, (1, lambda x: None), object, False, None),
(target.M15, (1, [2, ]), (object, 2), True, None),
(target.M15, (1, (2, )), (object, 2), True, None),
(target.M15, (1, objArray), (object, 1,2,3), True, None),
(target.M15, (1, doubleArray), None, True, TypeError),
(target.M16, (1, {1: [1,2]}), None, False, TypeError),
# public static PythonType M17<T>(T x, IEnumerable<T> y) -> pytype(T)
(target.M17, (SelfEnumerable(), SelfEnumerable()), SelfEnumerable, True, None),
(target.M17, (1, [1,2,3]), object, True, None),
(target.M17, (1.0, [1,2,3]), object, True, None),
(target.M17, (object(), [1,2,3]), object, True, None),
# public static PythonType M18<T>(T x) where T : IEnumerable<T> -> pytype(T)
(target.M18, (SelfEnumerable(), ), SelfEnumerable, True, None),
# public static PythonType M19<T0, T1>(T0 x, T1 y) where T0 : IList<T1> -> pytype(T0), pytype(T1)
(target.M19, ([], 1), None, True, TypeError),
(target.M19, (List[int](), 1), (List[int], int), True, None),
# public static PythonType M20<T0, T1>(T0 x, T1 y) -> pytype(T0), pytype(T1)
(target.M20, ([], 1), (list, int), True, None),
(target.M20, (List[int](), 1), (List[int], int), True, None),
# constructed types
# public static PythonType M21<T>(IEnumerable<T> enumerable)
(target.M21, ([1,2,3], ), object, False, None),
# overloaded by function
# public static PythonTuple M22<T>(IEnumerable<T> enumerable, Func<T, bool> predicate) -> pytype(T), True
# public static PythonTuple M22<T>(IEnumerable<T> enumerable, Func<T, int, bool> predicate) -> pytype(T), False
(target.M22, ([1,2,3], lambda x:True), (object, True), True, None),
(target.M22, ([1,2,3], lambda x,y:True), (object, False), True, None),
# public static PythonType M23<T>(List<T> x) -> pytype(T)
# public static PythonType M24<T>(List<List<T>> x) -> pytype(T)
# public static PythonType M25<T>(Dictionary<T, T> x) -> pytype(T)
(target.M23, (List[int](), ), int, True, None),
(target.M24, (List[List[int]](), ), int, True, None),
(target.M25, (Dict[int, int](), ), int, True, None),
(target.M25, (Dict[int, str](), ), None, True, TypeError),
# constructed types and constraints
# public static PythonType M26<T>(List<T> x) where T : class -> pytype(T)
# public static PythonType M27<T>(List<T> x) where T : struct -> pytype(T)
# public static PythonType M28<T>(List<T> x) where T : new() -> pytype(T)
(target.M26, (List[int](), ), None, False, TypeError),
(target.M27, (List[str](), ), None, False, TypeError),
(target.M28, (List[str](), ), None, False, TypeError),
(target.M26, (List[str](), ), str, False, None),
(target.M27, (List[int](), ), int, False, None),
(target.M28, (List[List[str]](), ), List[str], False, None),
# public static PythonType M29<T>(Dictionary<Dictionary<T, T>, Dictionary<T, T>> x)
(target.M29, (Dict[Dict[int, int], Dict[int, int]](), ), int, True, None),
# constraints and constructed types
# public static PythonType M30<T>(Func<T, bool> y) where T : struct -> pytype(T)
# public static PythonType M31<T>(Func<T, bool> y) where T : IList -> pytype(T)
# public static PythonType M32<T>(List<T> y) where T : new() -> pytype(T)
# public static PythonType M33<T>(List<T> y) where T : class -> pytype(T)
(target.M30, (lambda x: False, ), int, True, TypeError),
(target.M31, (lambda x: False, ), int, True, TypeError),
(target.M32, (List[str](), ), int, True, TypeError),
(target.M33, (List[int](), ), int, True, TypeError),
# public static PythonType M34<T>(IList<T> x, IList<T> y) -> pytype(T)
(target.M34, ((), [], ), object, True, None),
# T[] and IList<T> overloads:
(target.M35, (objArray, ), System.Array[object], False, None),
]
# TODO: more by-ref and arrays tests:
x = Array.Resize(Array.CreateInstance(int, 10), 20)
AreEqual(x.Length, 20)
for method, args, res, kwArgs, excep in tests:
generic_method_tester(method, args, res, kwArgs, excep)
def generic_method_tester(method, args, res, kwArgs, excep):
#print method, args, res, excep
if excep is None:
# test method w/ multiple calling conventions
if len(args) == 1:
AreEqual(method(args[0]), res)
if kwArgs:
AreEqual(method(x = args[0]), res)
AreEqual(method(**{'x' : args[0]}), res)
elif len(args) == 2:
AreEqual(method(args[0], args[1]), res)
if kwArgs:
AreEqual(method(x = args[0], y = args[1]), res)
AreEqual(method(args[0], y = args[1]), res)
AreEqual(method(y = args[1], x = args[0]), res)
AreEqual(method(*(args[0], ), **{'y' : args[1]}), res)
AreEqual(method(**{'x' : args[0], 'y' : args[1]}), res)
elif len(args) == 3:
AreEqual(method(args[0], args[1], args[2]), res)
if kwArgs:
AreEqual(method(x = args[0], y = args[1], z = args[2]), res)
AreEqual(method(args[0], y = args[1], z = args[2]), res)
AreEqual(method(args[0], args[1], z = args[2]), res)
AreEqual(method(z = args[2], y = args[1], x = args[0]), res)
AreEqual(method(*(args[0], args[1]), **{'z' : args[2]}), res)
AreEqual(method(*(args[0], ), **{'y': args[1], 'z' : args[2]}), res)
AreEqual(method(**{'x' : args[0], 'y' : args[1], 'z' : args[2]}), res)
else:
raise Exception("need to add new case for len %d " % len(args))
AreEqual(method(*args), res)
AreEqual(method(args[0], *args[1:]), res)
else:
# test error method w/ multiple calling conventions
if len(args) == 0:
f = lambda : method()
fkw, fkw2 = None, None
elif len(args) == 1:
f = lambda : method(args[0])
fkw = lambda : method(x = args[0])
fkw2 = lambda : method(**{'x' : args[0]})
elif len(args) == 2:
f = lambda : method(args[0], args[1])
fkw = lambda : method(x = args[0], y = args[1])
fkw2 = lambda : method(**{'x' : args[0], 'y' : args[1]})
elif len(args) == 3:
f = lambda : method(args[0], args[1], args[2])
fkw = lambda : method(x = args[0], y = args[1], z = args[2])
fkw2 = lambda : method(**{'x' : args[0], 'y' : args[1], 'z' : args[2]})
else:
raise Exception("need to add new case for len %d " % len(args))
if not kwArgs:
fkw = None
fkw2 = None
# test w/o splatting
AssertError(excep, f)
if fkw: AssertError(excep, fkw)
if fkw2: AssertError(excep, fkw2)
# test with splatting
AssertError(excep, method, *args)
print('>>>> methods in reference type')
target = CNoOverloads()
run_test(__name__)<|fim▁end|> | |
<|file_name|>Range.java<|end_file_name|><|fim▁begin|>package excelcom.api;
import com.sun.jna.platform.win32.COM.COMException;
import com.sun.jna.platform.win32.COM.COMLateBindingObject;
import com.sun.jna.platform.win32.COM.IDispatch;
import com.sun.jna.platform.win32.OaIdl;
import com.sun.jna.platform.win32.OleAuto;
import com.sun.jna.platform.win32.Variant;
import static com.sun.jna.platform.win32.Variant.VT_NULL;
/**
* Represents a Range
*/
class Range extends COMLateBindingObject {
Range(IDispatch iDispatch) throws COMException {
super(iDispatch);
}
Variant.VARIANT getValue() {
return this.invoke("Value");
}
int getRow() {
return this.invoke("Row").intValue();
}
int getColumn() {
return this.invoke("Column").intValue();
}
void setInteriorColor(ExcelColor color) {
new CellPane(this.getAutomationProperty("Interior", this)).setColorIndex(color);
}
ExcelColor getInteriorColor() {
return ExcelColor.getColor(new CellPane(this.getAutomationProperty("Interior", this)).getColorIndex());
}
void setFontColor(ExcelColor color) {
new CellPane(this.getAutomationProperty("Font", this)).setColorIndex(color);
}
ExcelColor getFontColor() {
return ExcelColor.getColor(new CellPane(this.getAutomationProperty("Font", this)).getColorIndex());
}
void setBorderColor(ExcelColor color) {
new CellPane(this.getAutomationProperty("Borders", this)).setColorIndex(color);
}
ExcelColor getBorderColor() {
return ExcelColor.getColor(new CellPane(this.getAutomationProperty("Borders", this)).getColorIndex());
}
void setComment(String comment) {
this.invokeNoReply("ClearComments");
this.invoke("AddComment", new Variant.VARIANT(comment));
}
String getComment() {
return new COMLateBindingObject(this.getAutomationProperty("Comment")) {
private String getText() {
return this.invoke("Text").stringValue();
}
}.getText();
}
FindResult find(Variant.VARIANT[] options) {
IDispatch find = (IDispatch) this.invoke("Find", options).getValue();
if (find == null) {
return null;
}
return new FindResult(find, this);
}
FindResult findNext(FindResult previous) {
return new FindResult(this.getAutomationProperty("FindNext", this, previous.toVariant()), this);
}
/**
* Can be Interior, Border or Font. Has methods for setting e.g. Color.
*/
private class CellPane extends COMLateBindingObject {
CellPane(IDispatch iDispatch) {
super(iDispatch);
}
void setColorIndex(ExcelColor color) {
this.setProperty("ColorIndex", color.getIndex());
}
<|fim▁hole|> throw new NullPointerException("return type of colorindex is null. Maybe multiple colors in range?");
}
return this.invoke("ColorIndex").intValue();
}
}
}<|fim▁end|> | int getColorIndex() {
Variant.VARIANT colorIndex = this.invoke("ColorIndex");
if(colorIndex.getVarType().intValue() == VT_NULL) { |
<|file_name|>committees.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import re
import lxml.html
from billy.scrape.committees import CommitteeScraper, Committee
from openstates.utils import LXMLMixin
class NYCommitteeScraper(CommitteeScraper, LXMLMixin):
jurisdiction = "ny"
latest_only = True
def _parse_name(self, name):
"""
Split a committee membership string into name and role.
>>> parse_name('Felix Ortiz')
('Felix Ortiz', 'member')
>>> parse_name('Felix Ortiz (Chair)')
('Felix Ortiz', 'chair')
>>> parse_name('Hon. Felix Ortiz, Co-Chair')
('Felix Ortiz', 'co-chair')
>>> parse_name('Owen H.\\r\\nJohnson (Vice Chairperson)')
('Owen H. Johnson', 'vice chairperson')
"""
name = re.sub(r'^(Hon\.|Assemblyman|Assemblywoman)\s+', '', name)
name = re.sub(r'\s+', ' ', name)
roles = ['Chairwoman', 'Chairperson', 'Chair', 'Secretary',
'Treasurer', 'Parliamentarian', 'Chaplain']
match = re.match(
r'([^(]+),? \(?((Co|Vice)?-?\s*(%s))\)?' % '|'.join(roles),
name)
role = 'member'
if match:
name = match.group(1).strip(' ,')
role = match.group(2).lower()
name = name.replace('Sen.', '').replace('Rep.', '').strip()
return (name, role)
def scrape(self, chamber, term):
getattr(self, 'scrape_' + chamber + '_chamber')()
def scrape_lower_chamber(self, only_names=None):
url = 'http://assembly.state.ny.us/comm/'
<|fim▁hole|> page = self.lxmlize(url)
committees = []
link_nodes = self.get_nodes(
page,
'//a[contains(@href, "sec=mem")]')
for link_node in link_nodes:
committee_name_text = self.get_node(
link_node,
'../strong/text()')
if committee_name_text is not None:
committee_name = committee_name_text.strip()
assert committee_name
if 'Caucus' in committee_name:
continue
committees.append(committee_name)
url = link_node.attrib['href']
committee = self.scrape_lower_committee(committee_name, url)
self.save_committee(committee)
return committees
def scrape_lower_committee(self, name, url):
page = self.lxmlize(url)
committee = Committee('lower', name)
committee.add_source(url)
seen = set()
member_links = self.get_nodes(
page,
'//div[@class="commlinks"]//a[contains(@href, "mem")]')
for member_link in member_links:
member_name = None
member_role = None
member_text = member_link.text
if member_text is not None:
member = member_text.strip()
member = re.sub(r'\s+', ' ', member)
member_name, member_role = self._parse_name(member)
if member_name is None:
continue
# Figure out if this person is the chair.
role_type = self.get_node(
member_link,
'../../preceding-sibling::div[1]/text()')
if role_type in (['Chair'], ['Co-Chair']):
member_role = 'chair'
else:
member_role = 'member'
if name not in seen:
committee.add_member(member_name, member_role)
seen.add(member_name)
return committee
def scrape_upper_chamber(self):
url = 'http://www.nysenate.gov/senators-committees'
page = self.lxmlize(url)
committees = []
committee_nodes = self.get_nodes(
page,
'//div[@id="c-committees-container"][1]//'
'a[@class="c-committee-link"]')
for committee_node in committee_nodes:
name_text = self.get_node(
committee_node,
'./h4[@class="c-committee-title"][1]/text()')
if name_text is not None:
name = name_text.strip()
assert name
committees.append(name)
# Retrieve committee information.
committee_url = committee_node.attrib['href']
committee = self.scrape_upper_committee(name,
committee_url)
self.save_committee(committee)
return committees
def scrape_upper_committee(self, committee_name, url):
page = self.lxmlize(url)
committee = Committee('upper', committee_name)
committee.add_source(url)
# Committee member attributes.
member_name = None
member_role = None
# Attempt to record the committee chair.
committee_chair = self.get_node(
page,
'//div[@class="nys-senator" and div[@class="nys-senator--info"'
' and p[@class="nys-senator--title" and'
' normalize-space(text())="Chair"]]]')
if committee_chair is not None:
info_node = self.get_node(
committee_chair,
'div[@class="nys-senator--info" and p[@class='
'"nys-senator--title" and contains(text(), "Chair")]]')
if info_node is not None:
# Attempt to retrieve committee chair's name.
member_name_text = self.get_node(
info_node,
'./h4[@class="nys-senator--name"][1]/a[1]/text()')
if member_name_text is not None:
member_name = member_name_text.strip()
else:
warning = ('Could not find the name of the chair for the'
' {} committee')
self.logger.warning(warning.format(committee_name))
# Attempt to retrieve committee chair's role (explicitly).
member_role_text = self.get_node(
info_node,
'./p[@class="nys-senator--title" and contains(text(), '
'"Chair")][1]/text()')
if member_role_text is not None:
member_role = member_role_text.strip()
else:
# This seems like a silly case, but could still be useful
# to check for.
warning = ('Could not find the role of the chair for the'
' {} committee')
self.logger.warning(warning.format(committee_name))
if member_name is not None and member_role is not None:
committee.add_member(member_name, member_role)
else:
warning = ('Could not find information for the chair of the'
' {} committee.')
self.logger.warning(warning.format(committee_name))
else:
warning = 'Missing chairperson for the {} committee.'
self.logger.warning(warning.format(committee_name))
# Get list of regular committee members.
member_nodes = self.get_nodes(
page,
'//div[contains(concat(" ", @class, " "), '
'" c-senators-container ")]//div[@class="view-content"]/'
' div/a')
# Attempt to record each committee member.
for member_node in member_nodes:
member_name = None
member_name_text = self.get_node(
member_node,
'.//div[@class="nys-senator--info"][1]/h4[@class='
'"nys-senator--name"][1]/text()')
if member_name_text is not None:
member_name = member_name_text.strip()
if member_name is not None:
committee.add_member(member_name, 'member')
else:
warning = ('Could not find the name of a member in the {}'
' committee')
self.logger.warning(warning.format(committee_name))
return committee<|fim▁end|> | |
<|file_name|>main.py<|end_file_name|><|fim▁begin|># This module is free software. You can redistribute it and/or modify it under
# the terms of the MIT License, see the file COPYING included with this
# distribution.
from __future__ import division
"""
main.py -- main program of motif sequence coverage pipeline tool
example for running code: python main.py -jid test -confFile ./data/default_scan_only.conf
This will create a results folder with the name test. You will need to delete the folder if you want to run the code again with the same name
"""
#python imports
import sys
import os
import argparse
import shutil
#add the util folder path to use util files in it
inPath = os.path.realpath(__file__)
split = inPath.split('/')
inPath = '/'.join(split[:len(split)-1])
sys.path.append(inPath + '/utils')
import conf
import general_utils
import Fimo
import Tomtom
#add the alg folder path to call the different algorithms
sys.path.append(inPath + '/algo')
import greedy
import motif_pwm_scan_cov
import motif_pwm_scan_only
#MAIN
def main(args):
#example for running code: python main.py -jid test -confFile ./data/default_scan_only.conf
print "main.py::main()"
parser = argparse.ArgumentParser()
parser.add_argument("-jid", "--jid", help="enter job ID") #job id to make a folder to store all the data for a specific job
parser.add_argument("-confFile", "--confFile", help="enter the configuration file")#path to configuration file
args = parser.parse_args()<|fim▁hole|>
#make a results directory to store job results
resultsDirName = args.jid
os.makedirs(resultsDirName)
#make a file list to store all the files to be moved to the results folder
fileList = []
#copy the config file
cpConfFileName = args.jid + '_in_conf_file'
cpConfFile = open(cpConfFileName, 'wb')
with open(args.confFile, 'rb') as handler:
for line in handler:
cpConfFile.write(line)
cpConfFile.close()
fileList.append(cpConfFileName)
#make a config object
confObj = conf.Conf()
confDict = confObj.read(args.confFile)
############
#Have a PWM file and want to scan it across a fasta file and then apply sequence coverage
############
if confDict['job.type']['type'] == 'motifPwmScanCov':
print 'motif_pwm scanning and coverage operation'
motif_pwm_scan_cov.callMotifPwmScanCov(args, confDict, fileList)
#move files to results folder
for outFile in fileList:
shutil.move(outFile, resultsDirName)
exit()
############
#Have a PWM file and want to scan it across a file only
############
if confDict['job.type']['type'] == 'pwmScan':
print 'motif pwm scanning only'
motif_pwm_scan_only.callMotifPwmScanOnly(args, confDict, fileList)
#move files to results folder
for outFile in fileList:
shutil.move(outFile, resultsDirName)
exit()
###############
#EXIT
###############
exit()
#calling main
if( __name__ == "__main__" ):
main(sys.argv)<|fim▁end|> | print 'jobId:', args.jid,'configfile:', args.confFile |
<|file_name|>SwRegInfo.java<|end_file_name|><|fim▁begin|>package ru.mail.parking.sw2.system;
import com.sonyericsson.extras.liveware.aef.registration.Registration;
import com.sonyericsson.extras.liveware.extension.util.ExtensionUtils;
import com.sonyericsson.extras.liveware.extension.util.registration.RegistrationInformation;
import android.content.ContentValues;
import ru.mail.parking.R;
import ru.mail.parking.ui.SettingsActivity;
import static ru.mail.parking.App.app;
public class SwRegInfo extends RegistrationInformation {
public static final String EXTENSION_KEY = app().getPackageName();
private static final ContentValues INFO = new ContentValues();
public SwRegInfo() {
INFO.put(Registration.ExtensionColumns.CONFIGURATION_ACTIVITY, SettingsActivity.class.getName());
INFO.put(Registration.ExtensionColumns.NAME, app().getString(R.string.sw_title));
INFO.put(Registration.ExtensionColumns.EXTENSION_KEY, EXTENSION_KEY);
INFO.put(Registration.ExtensionColumns.LAUNCH_MODE, Registration.LaunchMode.CONTROL);
String icon = ExtensionUtils.getUriString(app(), R.drawable.icon);
INFO.put(Registration.ExtensionColumns.HOST_APP_ICON_URI, icon);
icon = ExtensionUtils.getUriString(app(), R.drawable.icon_sw);
INFO.put(Registration.ExtensionColumns.EXTENSION_48PX_ICON_URI, icon);
}
@Override
public ContentValues getExtensionRegistrationConfiguration() {
return INFO;
}
@Override
public int getRequiredWidgetApiVersion() {
return RegistrationInformation.API_NOT_REQUIRED;
}
@Override
public int getRequiredSensorApiVersion() {
return RegistrationInformation.API_NOT_REQUIRED;
}
@Override
public int getRequiredNotificationApiVersion() {
return RegistrationInformation.API_NOT_REQUIRED;
}
@Override
public int getRequiredControlApiVersion() {
return 2;
}
@Override
public boolean controlInterceptsBackButton() {
return true;
}<|fim▁hole|> return width == app().getResources().getDimensionPixelSize(R.dimen.smart_watch_2_control_width) &&
height == app().getResources().getDimensionPixelSize(R.dimen.smart_watch_2_control_height);
}
}<|fim▁end|> |
@Override
public boolean isDisplaySizeSupported(int width, int height) { |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")<|fim▁hole|> return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()<|fim▁end|> | s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1]) |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>use std::cmp::Ord;<|fim▁hole|>fn chop<T: Ord>(item : T, slice : &[T]) -> i32 {
let length = slice.len();
// Catch empty slices
if length < 1 {
return -1;
}
let mut width = length;
let mut low = 0;
while width > 0 {
let mid_index = low + (width / 2);
let comparison = item.cmp(&slice[mid_index]);
match comparison {
Less => (),
Greater => {
low = mid_index + 1;
width -= 1;
}
Equal => return mid_index as i32
}
width /= 2;
}
return -1;
}
fn main() {
println!("{}", chop(3, &[1,3,5]));
}
#[test]
fn test_chop() {
assert_eq!(-1, chop(3, &[]));
assert_eq!(-1, chop(3, &[1]));
assert_eq!(0, chop(1, &[1]));
assert_eq!(0, chop(1, &[1, 3, 5]));
assert_eq!(1, chop(3, &[1, 3, 5]));
assert_eq!(2, chop(5, &[1, 3, 5]));
assert_eq!(-1, chop(0, &[1, 3, 5]));
assert_eq!(-1, chop(2, &[1, 3, 5]));
assert_eq!(-1, chop(4, &[1, 3, 5]));
assert_eq!(-1, chop(6, &[1, 3, 5]));
assert_eq!(0, chop(1, &[1, 3, 5, 7]));
assert_eq!(1, chop(3, &[1, 3, 5, 7]));
assert_eq!(2, chop(5, &[1, 3, 5, 7]));
assert_eq!(3, chop(7, &[1, 3, 5, 7]));
assert_eq!(-1, chop(0, &[1, 3, 5, 7]));
assert_eq!(-1, chop(2, &[1, 3, 5, 7]));
assert_eq!(-1, chop(4, &[1, 3, 5, 7]));
assert_eq!(-1, chop(6, &[1, 3, 5, 7]));
assert_eq!(-1, chop(8, &[1, 3, 5, 7]));
}<|fim▁end|> | use std::cmp::Ordering::{Less, Equal, Greater};
|
<|file_name|>win32_ops.hpp<|end_file_name|><|fim▁begin|>//
// Boost.Process
//
// Copyright (c) 2006 Julio M. Merino Vidal.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt.)
//
//!
//! \file boost/process/detail/win32_ops.hpp
//!
//! Provides some convenience functions to start processes under Win32
//! operating systems.
//!
#if !defined(BOOST_PROCESS_DETAIL_WIN32_OPS_HPP)
/** \cond */
#define BOOST_PROCESS_DETAIL_WIN32_OPS_HPP
/** \endcond */
#include <boost/process/config.hpp>
#if !defined(BOOST_PROCESS_WIN32_API)
<|fim▁hole|>extern "C" {
#include <tchar.h>
#include <windows.h>
// Added for OpenLieroX - Dev-Cpp workarounds
#if defined(WIN32) && defined(__GNUC__)
#define _tcscpy_s(D,N,S) _tcscpy(D,S)
#define _tcscat_s(D,N,S) _tcscat(D,S)
#endif
}
#include <boost/optional.hpp>
#include <boost/process/detail/file_handle.hpp>
#include <boost/process/detail/pipe.hpp>
#include <boost/process/detail/stream_info.hpp>
#include <boost/process/environment.hpp>
#include <boost/process/exceptions.hpp>
#include <boost/process/stream_behavior.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_array.hpp>
#include <boost/throw_exception.hpp>
namespace boost {
namespace process {
namespace detail {
// ------------------------------------------------------------------------
//!
//! \brief Converts the command line to a plain string.
//!
//! Converts the command line's list of arguments to the format
//! expected by the \a lpCommandLine parameter in the CreateProcess()
//! system call.
//!
//! This operation is only available in Win32 systems.
//!
//! \return A dynamically allocated string holding the command line
//! to be passed to the executable. It is returned in a
//! shared_array object to ensure its release at some point.
//!
template< class Arguments >
inline
boost::shared_array< TCHAR >
collection_to_win32_cmdline(const Arguments& args)
{
typedef std::vector< std::string > arguments_vector;
Arguments args2;
typename Arguments::size_type i = 0;
std::size_t length = 0;
for (typename Arguments::const_iterator iter = args.begin();
iter != args.end(); iter++) {
std::string arg = (*iter);
std::string::size_type pos = 0;
while ((pos = arg.find('"', pos)) != std::string::npos) {
arg.replace(pos, 1, "\\\"");
pos += 2;
}
if (arg.find(' ') != std::string::npos)
arg = '\"' + arg + '\"';
if (i != args.size() - 1)
arg += ' ';
args2.push_back(arg);
length += arg.size() + 1;
i++;
}
boost::shared_array< TCHAR > cmdline(new TCHAR[length]);
::_tcscpy_s(cmdline.get(), length, TEXT(""));
for (arguments_vector::size_type i = 0; i < args2.size(); i++)
::_tcscat_s(cmdline.get(), length, TEXT(args2[i].c_str()));
return cmdline;
}
// ------------------------------------------------------------------------
//!
//! \brief Converts an environment to a string used by CreateProcess().
//!
//! Converts the environment's contents to the format used by the
//! CreateProcess() system call. The returned TCHAR* string is
//! allocated in dynamic memory and the caller must free it when not
//! used any more. This is enforced by the use of a shared pointer.
//! The string is of the form var1=value1\\0var2=value2\\0\\0.
//!
inline
boost::shared_array< TCHAR >
environment_to_win32_strings(const environment& env)
{
boost::shared_array< TCHAR > strs(NULL);
// TODO: Add the "" variable to the returned string; it shouldn't
// be in the environment if the user didn't add it.
if (env.size() == 0) {
strs.reset(new TCHAR[2]);
::ZeroMemory(strs.get(), sizeof(TCHAR) * 2);
} else {
std::string::size_type len = sizeof(TCHAR);
for (environment::const_iterator iter = env.begin();
iter != env.end(); iter++)
len += ((*iter).first.length() + 1 + (*iter).second.length() +
1) * sizeof(TCHAR);
strs.reset(new TCHAR[len]);
TCHAR* ptr = strs.get();
for (environment::const_iterator iter = env.begin();
iter != env.end(); iter++) {
std::string tmp = (*iter).first + "=" + (*iter).second;
_tcscpy_s(ptr, len - (ptr - strs.get()) * sizeof(TCHAR),
TEXT(tmp.c_str()));
ptr += (tmp.length() + 1) * sizeof(TCHAR);
BOOST_ASSERT(static_cast< std::string::size_type >
(ptr - strs.get()) * sizeof(TCHAR) < len);
}
*ptr = '\0';
}
BOOST_ASSERT(strs.get() != NULL);
return strs;
}
// ------------------------------------------------------------------------
//!
//! \brief Helper class to configure a Win32 %child.
//!
//! This helper class is used to hold all the attributes that configure a
//! new Win32 %child process .
//!
//! All its fields are public for simplicity. It is only intended for
//! internal use and it is heavily coupled with the Launcher
//! implementations.
//!
struct win32_setup
{
//!
//! \brief The work directory.
//!
//! This string specifies the directory in which the %child process
//! starts execution. It cannot be empty.
//!
std::string m_work_directory;
//!
//! \brief The process startup properties.
//!
//! This Win32-specific object holds a list of properties that describe
//! how the new process should be started. The STARTF_USESTDHANDLES
//! flag should not be set in it because it is automatically configured
//! by win32_start().
//!
STARTUPINFO* m_startupinfo;
};
// ------------------------------------------------------------------------
//!
//! \brief Starts a new child process in a Win32 operating system.
//!
//! This helper functions is provided to simplify the Launcher's task when
//! it comes to starting up a new process in a Win32 operating system.
//!
//! \param cl The command line used to execute the child process.
//! \param env The environment variables that the new child process
//! receives.
//! \param infoin Information that describes stdin's behavior.
//! \param infoout Information that describes stdout's behavior.
//! \param infoerr Information that describes stderr's behavior.
//! \param setup A helper object holding extra child information.
//! \return The new process' information as returned by the ::CreateProcess
//! system call. The caller is responsible of creating an
//! appropriate Child representation for it.
//! \pre \a setup.m_startupinfo cannot have the \a STARTF_USESTDHANDLES set
//! in the \a dwFlags field.
//!
template< class Executable, class Arguments >
inline
PROCESS_INFORMATION
win32_start(const Executable& exe,
const Arguments& args,
const environment& env,
stream_info& infoin,
stream_info& infoout,
stream_info& infoerr,
const win32_setup& setup)
{
file_handle chin, chout, cherr;
BOOST_ASSERT(setup.m_startupinfo->cb >= sizeof(STARTUPINFO));
BOOST_ASSERT(!(setup.m_startupinfo->dwFlags & STARTF_USESTDHANDLES));
// XXX I'm not sure this usage of scoped_ptr is correct...
boost::scoped_ptr< STARTUPINFO > si
((STARTUPINFO*)new char[setup.m_startupinfo->cb]);
::CopyMemory(si.get(), setup.m_startupinfo, setup.m_startupinfo->cb);
si->dwFlags |= STARTF_USESTDHANDLES;
if (infoin.m_type == stream_info::close) {
} else if (infoin.m_type == stream_info::inherit) {
chin = file_handle::win32_std(STD_INPUT_HANDLE, true);
} else if (infoin.m_type == stream_info::use_file) {
HANDLE h = ::CreateFile(TEXT(infoin.m_file.c_str()), GENERIC_READ,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
NULL);
if (h == INVALID_HANDLE_VALUE)
boost::throw_exception
(system_error("boost::process::detail::win32_start",
"CreateFile failed", ::GetLastError()));
chin = file_handle(h);
} else if (infoin.m_type == stream_info::use_handle) {
chin = infoin.m_handle;
chin.win32_set_inheritable(true);
} else if (infoin.m_type == stream_info::use_pipe) {
infoin.m_pipe->rend().win32_set_inheritable(true);
chin = infoin.m_pipe->rend();
} else
BOOST_ASSERT(false);
si->hStdInput = chin.is_valid() ? chin.get() : INVALID_HANDLE_VALUE;
if (infoout.m_type == stream_info::close) {
} else if (infoout.m_type == stream_info::inherit) {
chout = file_handle::win32_std(STD_OUTPUT_HANDLE, true);
} else if (infoout.m_type == stream_info::use_file) {
HANDLE h = ::CreateFile(TEXT(infoout.m_file.c_str()), GENERIC_WRITE,
0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL,
NULL);
if (h == INVALID_HANDLE_VALUE)
boost::throw_exception
(system_error("boost::process::detail::win32_start",
"CreateFile failed", ::GetLastError()));
chout = file_handle(h);
} else if (infoout.m_type == stream_info::use_handle) {
chout = infoout.m_handle;
chout.win32_set_inheritable(true);
} else if (infoout.m_type == stream_info::use_pipe) {
infoout.m_pipe->wend().win32_set_inheritable(true);
chout = infoout.m_pipe->wend();
} else
BOOST_ASSERT(false);
si->hStdOutput = chout.is_valid() ? chout.get() : INVALID_HANDLE_VALUE;
if (infoerr.m_type == stream_info::close) {
} else if (infoerr.m_type == stream_info::inherit) {
cherr = file_handle::win32_std(STD_ERROR_HANDLE, true);
} else if (infoerr.m_type == stream_info::redirect) {
BOOST_ASSERT(infoerr.m_desc_to == 1);
BOOST_ASSERT(chout.is_valid());
cherr = file_handle::win32_dup(chout.get(), true);
} else if (infoerr.m_type == stream_info::use_file) {
HANDLE h = ::CreateFile(TEXT(infoerr.m_file.c_str()), GENERIC_WRITE,
0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL,
NULL);
if (h == INVALID_HANDLE_VALUE)
boost::throw_exception
(system_error("boost::process::detail::win32_start",
"CreateFile failed", ::GetLastError()));
cherr = file_handle(h);
} else if (infoerr.m_type == stream_info::use_handle) {
cherr = infoerr.m_handle;
cherr.win32_set_inheritable(true);
} else if (infoerr.m_type == stream_info::use_pipe) {
infoerr.m_pipe->wend().win32_set_inheritable(true);
cherr = infoerr.m_pipe->wend();
} else
BOOST_ASSERT(false);
si->hStdError = cherr.is_valid() ? cherr.get() : INVALID_HANDLE_VALUE;
PROCESS_INFORMATION pi;
::ZeroMemory(&pi, sizeof(pi));
boost::shared_array< TCHAR > cmdline = collection_to_win32_cmdline(args);
boost::scoped_array< TCHAR > executable(::_tcsdup(TEXT(exe.c_str())));
boost::scoped_array< TCHAR > workdir
(::_tcsdup(TEXT(setup.m_work_directory.c_str())));
boost::shared_array< TCHAR > envstrs = environment_to_win32_strings(env);
if (!::CreateProcess(executable.get(), cmdline.get(), NULL, NULL, TRUE,
0, envstrs.get(), workdir.get(),
si.get(), &pi)) {
boost::throw_exception
(system_error("boost::process::detail::win32_start",
"CreateProcess failed", ::GetLastError()));
}
return pi;
}
// ------------------------------------------------------------------------
} // namespace detail
} // namespace process
} // namespace boost
#endif // !defined(BOOST_PROCESS_DETAIL_WIN32_OPS_HPP)<|fim▁end|> | # error "Unsupported platform."
#endif
|
<|file_name|>adaptive_play_bot.py<|end_file_name|><|fim▁begin|><|fim▁hole|>
class AdaptivePlayBot(HumanBot):
def __init(self):
pass<|fim▁end|> | from human_bot import HumanBot |
<|file_name|>test_client_utils.py<|end_file_name|><|fim▁begin|>from .testlib import TestCase
import argparse
import logging
import os.path
import re
import unittest
from resync.client_utils import init_logging, count_true_args, parse_links, parse_link, parse_capabilities, parse_capability_lists, add_shared_misc_options, process_shared_misc_options
from resync.client import ClientFatalError
from resync.url_or_file_open import CONFIG
class TestClientUtils(TestCase):
def test01_init_logging(self):
# to_file=False, logfile=None, default_logfile='/tmp/resync.log',
# human=True, verbose=False, eval_mode=False,
# default_logger='client', extra_loggers=None):
tmplog = os.path.join(self.tmpdir, 'tmp.log')
init_logging(to_file=True, default_logfile=tmplog,
extra_loggers=['x1', 'x2'])
# check x1 and x2 set, not x3 (can tell by level)
self.assertTrue(logging.getLogger('x1').level, logging.DEBUG)
self.assertTrue(logging.getLogger('x2').level, logging.DEBUG)
self.assertEqual(logging.getLogger('x3').level, 0)
# write something, check goes to file
log = logging.getLogger('resync')
log.warning('PIGS MIGHT FLY')
logtxt = open(tmplog, 'r').read()
self.assertTrue(re.search(r'WARNING \| PIGS MIGHT FLY', logtxt))
def test02_count_true_args(self):
self.assertEqual(count_true_args(), 0)
self.assertEqual(count_true_args(True), 1)
self.assertEqual(count_true_args(False), 0)
self.assertEqual(count_true_args(0, 1, 2, 3), 3)
def test03_parse_links(self):
self.assertEqual(parse_links([]), [])
self.assertEqual(parse_links(['u,h']), [{'href': 'h', 'rel': 'u'}])
self.assertEqual(parse_links(['u,h', 'v,i']), [
{'href': 'h', 'rel': 'u'}, {'href': 'i', 'rel': 'v'}])
self.assertRaises(ClientFatalError, parse_links, 'xx')
self.assertRaises(ClientFatalError, parse_links, ['u'])
self.assertRaises(ClientFatalError, parse_links, ['u,h', 'u'])
def test04_parse_link(self):
# Input string of the form: rel,href,att1=val1,att2=val2
self.assertEqual(parse_link('u,h'), {'href': 'h', 'rel': 'u'})
self.assertEqual(parse_link('u,h,a=b'), {
'a': 'b', 'href': 'h', 'rel': 'u'})
self.assertEqual(parse_link('u,h,a=b,c=d'), {
'a': 'b', 'c': 'd', 'href': 'h', 'rel': 'u'})
self.assertEqual(parse_link('u,h,a=b,a=d'), {<|fim▁hole|> self.assertRaises(ClientFatalError, parse_link, '')
self.assertRaises(ClientFatalError, parse_link, 'u')
self.assertRaises(ClientFatalError, parse_link, 'u,')
self.assertRaises(ClientFatalError, parse_link, 'u,h,,')
self.assertRaises(ClientFatalError, parse_link, 'u,h,a')
self.assertRaises(ClientFatalError, parse_link, 'u,h,a=')
self.assertRaises(ClientFatalError, parse_link, 'u,h,a=b,=c')
def test05_parse_capabilities(self):
# Input string of the form: cap_name=uri,cap_name=uri
# good
c = parse_capabilities('a=')
self.assertEqual(len(c), 1)
self.assertEqual(c['a'], '')
c = parse_capabilities('a=b,c=')
self.assertEqual(len(c), 2)
self.assertEqual(c['a'], 'b')
# bad
self.assertRaises(ClientFatalError, parse_capabilities, 'a')
self.assertRaises(ClientFatalError, parse_capabilities, 'a=b,')
def test06_parse_capability_lists(self):
# Input string of the form: uri,uri
self.assertEqual(parse_capability_lists('a,b'), ['a', 'b'])
def test07_add_shared_misc_options(self):
"""Test add_shared_misc_options method."""
parser = argparse.ArgumentParser()
add_shared_misc_options(parser, default_logfile='/tmp/abc.log')
args = parser.parse_args(['--hash', 'md5', '--hash', 'sha-1',
'--checksum',
'--from', '2020-01-01T01:01:01Z',
'--exclude', 'ex1', '--exclude', 'ex2',
'--multifile',
'--logger', '--logfile', 'log.out',
'--spec-version', '1.0',
'-v'])
self.assertEqual(args.hash, ['md5', 'sha-1'])
self.assertTrue(args.checksum)
self.assertEqual(args.from_datetime, '2020-01-01T01:01:01Z')
self.assertEqual(args.exclude, ['ex1', 'ex2'])
self.assertTrue(args.multifile)
self.assertTrue(args.logger)
self.assertEqual(args.logfile, 'log.out')
self.assertEqual(args.spec_version, '1.0')
self.assertTrue(args.verbose)
# Remote options
parser = argparse.ArgumentParser()
add_shared_misc_options(parser, default_logfile='/tmp/abc.log', include_remote=True)
args = parser.parse_args(['--noauth',
'--access-token', 'VerySecretToken',
'--delay', '1.23',
'--user-agent', 'rc/2.1.1'])
self.assertTrue(args.noauth)
self.assertEqual(args.access_token, 'VerySecretToken')
self.assertEqual(args.delay, 1.23)
self.assertEqual(args.user_agent, 'rc/2.1.1')
# Remote options note selected
parser = argparse.ArgumentParser()
add_shared_misc_options(parser, default_logfile='/tmp/abc.log', include_remote=False)
self.assertRaises(SystemExit, parser.parse_args, ['--access-token', 'VerySecretToken'])
def test08_process_shared_misc_options(self):
"""Test process_shared_misc_options method."""
global CONFIG
config_copy = CONFIG.copy()
args = argparse.Namespace(hash=['sha-1'], checksum='md5')
process_shared_misc_options(args)
self.assertEqual(args.hash, ['sha-1', 'md5'])
# Remote options
args = argparse.Namespace(access_token='ExtraSecretToken',
delay=2.5,
user_agent='me',
checksum=None)
process_shared_misc_options(args, include_remote=True)
self.assertEqual(CONFIG['bearer_token'], 'ExtraSecretToken')
self.assertEqual(CONFIG['delay'], 2.5)
self.assertEqual(CONFIG['user_agent'], 'me')
# Negative delay is bad...
args = argparse.Namespace(access_token=None, delay=-1.0, user_agent=None, checksum=None)
self.assertRaises(argparse.ArgumentTypeError, process_shared_misc_options, args, include_remote=True)
# Config is a global so reset back to old version
for (k, v) in config_copy.items():
CONFIG[k] = v<|fim▁end|> | 'a': 'd', 'href': 'h', 'rel': 'u'}) # desired?? |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf import settings
from django.conf.urls import url
from plans.views import CreateOrderView, OrderListView, InvoiceDetailView, AccountActivationView, \
OrderPaymentReturnView, CurrentPlanView, UpgradePlanView, OrderView, BillingInfoRedirectView, \
BillingInfoCreateView, BillingInfoUpdateView, BillingInfoDeleteView, CreateOrderPlanChangeView, ChangePlanView, \<|fim▁hole|> url(r'^account/$', CurrentPlanView.as_view(), name='current_plan'),
url(r'^account/activation/$', AccountActivationView.as_view(), name='account_activation'),
url(r'^upgrade/$', UpgradePlanView.as_view(), name='upgrade_plan'),
url(r'^order/extend/new/(?P<pk>\d+)/$', CreateOrderView.as_view(), name='create_order_plan'),
url(r'^order/upgrade/new/(?P<pk>\d+)/$', CreateOrderPlanChangeView.as_view(), name='create_order_plan_change'),
url(r'^change/(?P<pk>\d+)/$', ChangePlanView.as_view(), name='change_plan'),
url(r'^order/$', OrderListView.as_view(), name='order_list'),
url(r'^order/(?P<pk>\d+)/$', OrderView.as_view(), name='order'),
url(r'^order/(?P<pk>\d+)/payment/success/$', OrderPaymentReturnView.as_view(status='success'),
name='order_payment_success'),
url(r'^order/(?P<pk>\d+)/payment/failure/$', OrderPaymentReturnView.as_view(status='failure'),
name='order_payment_failure'),
url(r'^billing/$', BillingInfoRedirectView.as_view(), name='billing_info'),
url(r'^billing/create/$', BillingInfoCreateView.as_view(), name='billing_info_create'),
url(r'^billing/update/$', BillingInfoUpdateView.as_view(), name='billing_info_update'),
url(r'^billing/delete/$', BillingInfoDeleteView.as_view(), name='billing_info_delete'),
url(r'^invoice/(?P<pk>\d+)/preview/html/$', InvoiceDetailView.as_view(), name='invoice_preview_html'),
]
if getattr(settings, 'DEBUG', False):
urlpatterns += [
url(r'^fakepayments/(?P<pk>\d+)/$', FakePaymentsView.as_view(), name='fake_payments'),
]<|fim▁end|> | PricingView, FakePaymentsView
urlpatterns = [
url(r'^pricing/$', PricingView.as_view(), name='pricing'), |
<|file_name|>start.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
import xmlrpc.client
from time import sleep
def remoteCall(func, *args):
try:
ret = func(*args)
return ret<|fim▁hole|>server = xmlrpc.client.ServerProxy("https://localhost:8080", allow_none=True)
sid = remoteCall(server.login, "dj", "abc123")
print(remoteCall(server.getfoo, sid))
sleep(3)
print(remoteCall(server.getfoo, sid))
sleep(6)
print(remoteCall(server.getfoo, sid))<|fim▁end|> | except xmlrpc.client.Fault as e:
print(e)
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># (C) British Crown Copyright 2016, Met Office
#
# This file is part of Biggus.
#
# Biggus is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Biggus is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#<|fim▁hole|>"""Unit tests for `biggus._init`"""
from __future__ import absolute_import, division, print_function
from six.moves import (filter, input, map, range, zip) # noqa<|fim▁end|> | # You should have received a copy of the GNU Lesser General Public License
# along with Biggus. If not, see <http://www.gnu.org/licenses/>. |
<|file_name|>thread-local-in-ctfe.rs<|end_file_name|><|fim▁begin|>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT<|fim▁hole|>//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(const_fn, thread_local)]
#[thread_local]
static A: u32 = 1;
static B: u32 = A;
//~^ ERROR thread-local statics cannot be accessed at compile-time
static C: &u32 = &A;
//~^ ERROR thread-local statics cannot be accessed at compile-time
const D: u32 = A;
//~^ ERROR thread-local statics cannot be accessed at compile-time
const E: &u32 = &A;
//~^ ERROR thread-local statics cannot be accessed at compile-time
const fn f() -> u32 {
A
//~^ ERROR thread-local statics cannot be accessed at compile-time
}
fn main() {}<|fim▁end|> | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. |
<|file_name|>domrectlist.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DOMRectListBinding;
use dom::bindings::codegen::Bindings::DOMRectListBinding::DOMRectListMethods;
use dom::bindings::global;
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::domrect::DOMRect;
use dom::window::Window;
#[dom_struct]
pub struct DOMRectList {
reflector_: Reflector,
rects: Vec<JS<DOMRect>>,
window: JS<Window>,
}
impl DOMRectList {
fn new_inherited(window: JSRef<Window>,
rects: Vec<JSRef<DOMRect>>) -> DOMRectList {
let rects = rects.iter().map(|rect| JS::from_rooted(*rect)).collect();
DOMRectList {
reflector_: Reflector::new(),
rects: rects,
window: JS::from_rooted(window),
}
}
pub fn new(window: JSRef<Window>,
rects: Vec<JSRef<DOMRect>>) -> Temporary<DOMRectList> {
reflect_dom_object(box DOMRectList::new_inherited(window, rects),
&global::Window(window), DOMRectListBinding::Wrap)
}
}
impl<'a> DOMRectListMethods for JSRef<'a, DOMRectList> {
fn Length(self) -> u32 {
self.rects.len() as u32
}
fn Item(self, index: u32) -> Option<Temporary<DOMRect>> {
let rects = &self.rects;
if index < rects.len() as u32 {
Some(Temporary::new(rects[index as uint].clone()))
} else {<|fim▁hole|> }
fn IndexedGetter(self, index: u32, found: &mut bool) -> Option<Temporary<DOMRect>> {
*found = index < self.rects.len() as u32;
self.Item(index)
}
}
impl Reflectable for DOMRectList {
fn reflector<'a>(&'a self) -> &'a Reflector {
&self.reflector_
}
}<|fim▁end|> | None
} |
<|file_name|>f07.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
<|fim▁hole|> match [7, 77, 777, 7777] {
[x, y, ..] => x + y
};
}<|fim▁end|> | pub fn pat_vec_7() { |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>{% extends 'setup.py.jj2' %}
{%block platform_block%}
{%endblock%}
{%block additional_keywords%}
"plain",
"simple",
"grid",
"pipe",
"orgtbl",
"rst",<|fim▁hole|> "latex_booktabs",
"html",
"json"
{%endblock%}<|fim▁end|> | "mediawiki",
"latex", |
<|file_name|>kindck-copy.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Test which of the builtin types are considered POD.
use std::rc::Rc;
fn assert_copy<T:Copy>() { }
trait Dummy { }
#[derive(Copy, Clone)]
struct MyStruct {
x: isize,
y: isize,
}
<|fim▁hole|>struct MyNoncopyStruct {
x: Box<char>,
}
fn test<'a,T,U:Copy>(_: &'a isize) {
// lifetime pointers are ok...
assert_copy::<&'static isize>();
assert_copy::<&'a isize>();
assert_copy::<&'a str>();
assert_copy::<&'a [isize]>();
// ...unless they are mutable
assert_copy::<&'static mut isize>(); //~ ERROR : std::marker::Copy` is not satisfied
assert_copy::<&'a mut isize>(); //~ ERROR : std::marker::Copy` is not satisfied
// boxes are not ok
assert_copy::<Box<isize>>(); //~ ERROR : std::marker::Copy` is not satisfied
assert_copy::<String>(); //~ ERROR : std::marker::Copy` is not satisfied
assert_copy::<Vec<isize> >(); //~ ERROR : std::marker::Copy` is not satisfied
assert_copy::<Box<&'a mut isize>>(); //~ ERROR : std::marker::Copy` is not satisfied
// borrowed object types are generally ok
assert_copy::<&'a Dummy>();
assert_copy::<&'a (Dummy+Send)>();
assert_copy::<&'static (Dummy+Send)>();
// owned object types are not ok
assert_copy::<Box<Dummy>>(); //~ ERROR : std::marker::Copy` is not satisfied
assert_copy::<Box<Dummy+Send>>(); //~ ERROR : std::marker::Copy` is not satisfied
// mutable object types are not ok
assert_copy::<&'a mut (Dummy+Send)>(); //~ ERROR : std::marker::Copy` is not satisfied
// unsafe ptrs are ok
assert_copy::<*const isize>();
assert_copy::<*const &'a mut isize>();
// regular old ints and such are ok
assert_copy::<isize>();
assert_copy::<bool>();
assert_copy::<()>();
// tuples are ok
assert_copy::<(isize,isize)>();
// structs of POD are ok
assert_copy::<MyStruct>();
// structs containing non-POD are not ok
assert_copy::<MyNoncopyStruct>(); //~ ERROR : std::marker::Copy` is not satisfied
// ref counted types are not ok
assert_copy::<Rc<isize>>(); //~ ERROR : std::marker::Copy` is not satisfied
}
pub fn main() {
}<|fim▁end|> | |
<|file_name|>air_quality.py<|end_file_name|><|fim▁begin|>"""Support for the Airly air_quality service."""
from homeassistant.components.air_quality import (
ATTR_AQI,
ATTR_PM_2_5,
ATTR_PM_10,
AirQualityEntity,
)
from homeassistant.const import CONF_NAME
from .const import (
ATTR_API_ADVICE,
ATTR_API_CAQI,
ATTR_API_CAQI_DESCRIPTION,
ATTR_API_CAQI_LEVEL,
ATTR_API_PM10,
ATTR_API_PM10_LIMIT,
ATTR_API_PM10_PERCENT,
ATTR_API_PM25,
ATTR_API_PM25_LIMIT,
ATTR_API_PM25_PERCENT,
DOMAIN,
)
ATTRIBUTION = "Data provided by Airly"
LABEL_ADVICE = "advice"
LABEL_AQI_DESCRIPTION = f"{ATTR_AQI}_description"
LABEL_AQI_LEVEL = f"{ATTR_AQI}_level"<|fim▁hole|>LABEL_PM_10_PERCENT = f"{ATTR_PM_10}_percent_of_limit"
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Airly air_quality entity based on a config entry."""
name = config_entry.data[CONF_NAME]
coordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities(
[AirlyAirQuality(coordinator, name, config_entry.unique_id)], False
)
def round_state(func):
"""Round state."""
def _decorator(self):
res = func(self)
if isinstance(res, float):
return round(res)
return res
return _decorator
class AirlyAirQuality(AirQualityEntity):
"""Define an Airly air quality."""
def __init__(self, coordinator, name, unique_id):
"""Initialize."""
self.coordinator = coordinator
self._name = name
self._unique_id = unique_id
self._icon = "mdi:blur"
@property
def name(self):
"""Return the name."""
return self._name
@property
def should_poll(self):
"""Return the polling requirement of the entity."""
return False
@property
def icon(self):
"""Return the icon."""
return self._icon
@property
@round_state
def air_quality_index(self):
"""Return the air quality index."""
return self.coordinator.data[ATTR_API_CAQI]
@property
@round_state
def particulate_matter_2_5(self):
"""Return the particulate matter 2.5 level."""
return self.coordinator.data[ATTR_API_PM25]
@property
@round_state
def particulate_matter_10(self):
"""Return the particulate matter 10 level."""
return self.coordinator.data[ATTR_API_PM10]
@property
def attribution(self):
"""Return the attribution."""
return ATTRIBUTION
@property
def unique_id(self):
"""Return a unique_id for this entity."""
return self._unique_id
@property
def available(self):
"""Return True if entity is available."""
return self.coordinator.last_update_success
@property
def device_state_attributes(self):
"""Return the state attributes."""
return {
LABEL_AQI_DESCRIPTION: self.coordinator.data[ATTR_API_CAQI_DESCRIPTION],
LABEL_ADVICE: self.coordinator.data[ATTR_API_ADVICE],
LABEL_AQI_LEVEL: self.coordinator.data[ATTR_API_CAQI_LEVEL],
LABEL_PM_2_5_LIMIT: self.coordinator.data[ATTR_API_PM25_LIMIT],
LABEL_PM_2_5_PERCENT: round(self.coordinator.data[ATTR_API_PM25_PERCENT]),
LABEL_PM_10_LIMIT: self.coordinator.data[ATTR_API_PM10_LIMIT],
LABEL_PM_10_PERCENT: round(self.coordinator.data[ATTR_API_PM10_PERCENT]),
}
async def async_added_to_hass(self):
"""Connect to dispatcher listening for entity data notifications."""
self.async_on_remove(
self.coordinator.async_add_listener(self.async_write_ha_state)
)
async def async_update(self):
"""Update Airly entity."""
await self.coordinator.async_request_refresh()<|fim▁end|> | LABEL_PM_2_5_LIMIT = f"{ATTR_PM_2_5}_limit"
LABEL_PM_2_5_PERCENT = f"{ATTR_PM_2_5}_percent_of_limit"
LABEL_PM_10_LIMIT = f"{ATTR_PM_10}_limit" |
<|file_name|>macro-interpolation.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[feature(macro_rules)];
macro_rules! overly_complicated (
($fnname:ident, $arg:ident, $ty:ty, $body:block, $val:expr, $pat:pat, $res:path) =>
({
fn $fnname($arg: $ty) -> Option<$ty> $body
match $fnname($val) {
Some($pat) => {
$res
}
_ => { fail2!(); }
}
})<|fim▁hole|>pub fn main() {
assert!(overly_complicated!(f, x, Option<uint>, { return Some(x); },
Some(8u), Some(y), y) == 8u)
}<|fim▁end|> |
) |
<|file_name|>walletunlock.py<|end_file_name|><|fim▁begin|><|fim▁hole|>access = ServiceProxy("http://127.0.0.1:52398")
pwd = raw_input("Enter wallet passphrase: ")
access.walletpassphrase(pwd, 60)<|fim▁end|> | from jsonrpc import ServiceProxy |
<|file_name|>socket_multiplexer_test.py<|end_file_name|><|fim▁begin|># Copyright 2011-2013 Colin Scott
# Copyright 2011-2013 Andreas Wundsam
#
# Licensed under the Apache License, Version 2.0 (the "License");<|fim▁hole|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import sys
import os
import time
from threading import Thread
import logging
log = logging.getLogger()
from sts.util.socket_mux.server_socket_multiplexer import *
from sts.util.socket_mux.sts_socket_multiplexer import *
sys.path.append(os.path.dirname(__file__) + "/../../..")
class MultiplexerTest(unittest.TestCase):
client_messages = [ "foo", "bar", "baz" ]
def setup_server(self, address):
import socket
mux_select = ServerMultiplexedSelect()
ServerMockSocket.bind_called = False
listener = ServerMockSocket(socket.AF_UNIX, socket.SOCK_STREAM,
set_true_listen_socket=mux_select.set_true_listen_socket)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(address)
listener.listen(16)
return (mux_select, listener)
def setup_client(self, num_socks, address):
try:
from pox.lib.util import connect_socket_with_backoff
io_master = MultiplexedSelect()
socket = connect_socket_with_backoff(address=address)
io_worker = io_master.create_worker_for_socket(socket)
# TODO(cs): unused variable demux
demux = STSSocketDemultiplexer(io_worker, address)
mock_socks = []
for i in xrange(num_socks):
mock_socket = STSMockSocket(None, None)
mock_socket.connect(address)
mock_socket.send(self.client_messages[i])
mock_socks.append(mock_socket)
# Now flush messages
while [ m for m in mock_socks if m.json_worker.io_worker._ready_to_send ] != []:
io_master.select(mock_socks, mock_socks, [])
except Exception as e:
log.critical("Client died: %s" % e)
raise e
def wait_for_next_accept(self, listener, mux_select):
log.info("waiting for next accept")
rl = []
while listener not in rl:
(rl, _, _) = mux_select.select([listener], [], [], 0.1)
def test_basic(self):
address = "basic_pipe"
try:
t = Thread(target=self.setup_client, args=(1,address,), name="MainThread")
t.start()
(mux_select, listener) = self.setup_server(address)
# wait for client to connect
self.wait_for_next_accept(listener, mux_select)
mock_sock = listener.accept()[0]
# now read client message
(rl, _, _) = mux_select.select([mock_sock], [], [])
start = last = time.time()
while mock_sock not in rl:
time.sleep(0.05)
if time.time() - start > 5:
self.fail("Did not find socket in rl in 5 seconds")
elif time.time() - last > 1:
log.debug("waiting for socket %s in rl %s..." % ( str(mock_sock), repr(rl)))
last = time.time()
(rl, _, _) = mux_select.select([mock_sock], [], [])
d = mock_sock.recv(2048)
self.assertEqual(self.client_messages[0], d)
finally:
if ServerSocketDemultiplexer.instance is not None:
ServerSocketDemultiplexer.instance = None
try:
os.unlink(address)
except OSError:
if os.path.exists(address):
raise RuntimeError("can't remove PIPE socket %s" % str(address))
def test_three_incoming(self):
address = "three_pipe"
try:
t = Thread(target=self.setup_client, args=(3,address,), name="MainThread")
t.start()
(mux_select, listener) = self.setup_server(address)
for i in xrange(len(self.client_messages)):
self.wait_for_next_accept(listener, mux_select)
mock_sock = listener.accept()[0]
(rl, _, _) = mux_select.select([mock_sock], [], [])
start = last = time.time()
while mock_sock not in rl:
if time.time() - start > 5:
self.fail("Did not find socket in rl in 5 seconds")
elif time.time() - last > 1:
log.debug("waiting for socket %s in rl %s..." % ( str(mock_sock), repr(rl)))
last = time.time()
(rl, _, _) = mux_select.select([mock_sock], [], [])
time.sleep(0.05)
d = mock_sock.recv(2048)
# order should be deterministic
self.assertEqual(self.client_messages[i], d)
finally:
if ServerSocketDemultiplexer.instance is not None:
ServerSocketDemultiplexer.instance = None
try:
os.unlink(address)
except OSError:
if os.path.exists(address):
raise RuntimeError("can't remove PIPE socket %s" % str(address))<|fim▁end|> | |
<|file_name|>h4.news.py<|end_file_name|><|fim▁begin|><|fim▁hole|> 'currentLabel': 'up',
'progress_mc': {'currentLabel': '_0'}}}<|fim▁end|> | {'level_mc': {'_txt': {'text': '6'}, |
<|file_name|>eab-api.js<|end_file_name|><|fim▁begin|>/* ----- Login with Fb/Tw ----- */
(function ($) {
function rsvp_after_wordpress_login (data) {
var status = 0;
try { status = parseInt(data.status, 10); } catch (e) { status = 0; }
if (!status) { // ... handle error
//update error by Hoang
if ($("#eab-wordpress_login-registration_wrapper").is(":visible")){
$('#eab-wordpress-signup-status').text(l10nEabApi.wp_signup_error);
}
else if ($("#eab-wordpress_login-login_wrapper").is(":visible")){
$('#eab-wordpress-login-status').text(l10nEabApi.wp_username_pass_invalid);
}
return false;
}
var $me = $("#eab-wordpress_login-wrapper");
var post_id = $me.attr("data-post_id");
// Get form if all went well
$.post(_eab_data.ajax_url, {
"action": "eab_get_form",
"post_id": post_id
}, function (data) {
$("body").append('<div id="eab-wordpress_form">' + data + '</div>');
$("#eab-wordpress_form").find("." + $me.attr("class")).click();
});
}
function send_wordpress_registration_request () {
var deferred = $.Deferred(),
$root = $("#eab-wordpress_login-registration_wrapper"),
data = {
username: $("#eab-wordpress_login-registration_username").val(),
email: $("#eab-wordpress_login-registration_email").val()
}
;
deferred.done(function () {
// Client-side validation first
if (!data.username || !data.email) {
$('#eab-wordpress-signup-status').text(l10nEabApi.wp_missing_user_email);
return false;
}
$root.append('<img class="eab-waiting" src="' + _eab_data.root_url + '/waiting.gif" />');
$.post(_eab_data.ajax_url, {
"action": "eab_wordpress_register",
"data": data
}, function (data) {
rsvp_after_wordpress_login(data);
}).always(function () {
$root.find("img.eab-waiting").remove();
});
});
$(document).trigger("eab-api-registration-data", [data, deferred]);
setTimeout(function () {
if ('pending' === deferred.state()) deferred.resolve();
}, 500);
}
function send_wordpress_login_request () {
// Client-side validation first
var username = $("#eab-wordpress_login-login_username").val();
var password = $("#eab-wordpress_login-login_password").val();
//if (!username) return false;
//if (!password) return false;
if(!username || !password){
//output error here,update by Hoang
$('#eab-wordpress-login-status').text(l10nEabApi.wp_missing_username_password);
return false;
}
$.post(_eab_data.ajax_url, {
"action": "eab_wordpress_login",
"data": {
"username": username,
"password": password
}
}, function (data) {
rsvp_after_wordpress_login(data);
});
}
function dispatch_login_register () {
if ($("#eab-wordpress_login-registration_wrapper").is(":visible")) return send_wordpress_registration_request();
else if ($("#eab-wordpress_login-login_wrapper").is(":visible")) return send_wordpress_login_request();
return false;
}
function create_wordpress_login_popup ($action, post_id) {
if (!$("#eab-wordpress_login-background").length) {
$("body").append(
"<div id='eab-wordpress_login-background'></div>" +
"<div id='eab-wordpress_login-wrapper' class='" + $action.removeClass("active").attr("class") + "' data-post_id='" + post_id + "'>" +
"<div id='eab-wordpress_login-registration_wrapper' class='eab-wordpress_login-element_wrapper'>" +
"<h4>" + l10nEabApi.wp_register + "</h4>" +
"<p class='eab-wordpress_login-element eab-wordpress_login-element-message'>" +
l10nEabApi.wp_registration_msg +
"</p>" +
"<p id='eab-wordpress-signup-status'></p>"+
"<p class='eab-wordpress_login-element'>" +
"<label for='eab-wordpress_login-registration_username'>" + l10nEabApi.wp_username + "</label>" +
"<input type='text' id='eab-wordpress_login-registration_username' placeholder='' />" +
"</p>" +
"<p class='eab-wordpress_login-element'>" +
"<label for='eab-wordpress_login-registration_email'>" + l10nEabApi.wp_email + "</label>" +
"<input type='text' id='eab-wordpress_login-registration_email' placeholder='' />" +
"</p>" +
"</div>" +
"<div id='eab-wordpress_login-login_wrapper' class='eab-wordpress_login-element_wrapper' style='display:none'>" +
"<h4>" + l10nEabApi.wp_login + "</h4>" +
"<p class='eab-wordpress_login-element eab-wordpress_login-element-message'>" +
l10nEabApi.wp_login_msg +
"</p>" +
"<p id='eab-wordpress-login-status'></p>"+
"<p class='eab-wordpress_login-element'>" +
"<label for='eab-wordpress_login-login_username'>" + l10nEabApi.wp_username + "</label>" +
"<input type='text' id='eab-wordpress_login-login_username' placeholder='' />" +
"</p>" +
"<p class='eab-wordpress_login-element'>" +
"<label for='eab-wordpress_login-login_password'>" + l10nEabApi.wp_password + "</label>" +
"<input type='password' id='eab-wordpress_login-login_password' placeholder='' />" +
"</p>" +
"</div>" +
"<div id='eab-wordpress_login-mode_toggle'><a href='#' data-on='" + l10nEabApi.wp_toggle_on + "' data-off='" + l10nEabApi.wp_toggle_off + "'>" + l10nEabApi.wp_toggle_on + "</a></div>" +
"<div id='eab-wordpress_login-command_wrapper'>" +
"<input type='button' id='eab-wordpress_login-command-ok' value='" + l10nEabApi.wp_submit + "' />" +
"<input type='button' id='eab-wordpress_login-command-cancel' value='" + l10nEabApi.wp_cancel + "' />" +
"</div>" +
"</div>"
);
$(document).trigger("eab-api-registration-form_rendered");
}
var $background = $("#eab-wordpress_login-background");
var $wrapper = $("#eab-wordpress_login-wrapper");
$background.css({
"width": $(document).width(),
"height": $(document).height()
});
$wrapper.css({
"left": ($(document).width() - 300) / 2
});
//$("#eab-wordpress_login-mode_toggle a").on('click', function () {
$("#eab-wordpress_login-mode_toggle a").click(function () {
var $me = $(this);
if ($("#eab-wordpress_login-registration_wrapper").is(":visible")) {
$me.text($me.attr("data-off"));
$("#eab-wordpress_login-registration_wrapper").hide();
$("#eab-wordpress_login-login_wrapper").show();
} else {
$me.text($me.attr("data-on"));
$("#eab-wordpress_login-login_wrapper").hide();
$("#eab-wordpress_login-registration_wrapper").show();
}
return false;
});
//$("#eab-wordpress_login-command-ok").on('click', dispatch_login_register);
$("#eab-wordpress_login-command-ok").click(dispatch_login_register);
//$("#eab-wordpress_login-command-cancel, #eab-wordpress_login-background").on('click', function () {
$("#eab-wordpress_login-command-cancel, #eab-wordpress_login-background").click(function () {
$wrapper.remove();
$background.remove();
return false;
});
}
function create_login_interface ($me) {
if ($("#wpmudevevents-login_links-wrapper").length) {
$("#wpmudevevents-login_links-wrapper").remove();
}
$me.parents('.wpmudevevents-buttons').after('<div id="wpmudevevents-login_links-wrapper" />');
var $root = $("#wpmudevevents-login_links-wrapper");
var post_id = $me.parents(".wpmudevevents-buttons").find('input:hidden[name="event_id"]').val();
$root.html(
'<ul class="wpmudevevents-login_links">' +
(l10nEabApi.show_facebook ? '<li><a href="#" class="wpmudevevents-login_link wpmudevevents-login_link-facebook">' + l10nEabApi.facebook + '</a></li>' : '') +
(l10nEabApi.show_twitter ? '<li><a href="#" class="wpmudevevents-login_link wpmudevevents-login_link-twitter">' + l10nEabApi.twitter + '</a></li>' : '') +
(l10nEabApi.show_google ? '<li><a href="#" class="wpmudevevents-login_link wpmudevevents-login_link-google">' + l10nEabApi.google + '</a></li>' : '') +
(l10nEabApi.show_wordpress ? '<li><a href="#" class="wpmudevevents-login_link wpmudevevents-login_link-wordpress">' + l10nEabApi.wordpress + '</a></li>' : '') +
'<li><a href="#" class="wpmudevevents-login_link wpmudevevents-login_link-cancel">' + l10nEabApi.cancel + '</a></li>' +
'</ul>'
);
$me.addClass("active");
$root.find(".wpmudevevents-login_link").each(function () {
var $lnk = $(this);
var callback = false;
if ($lnk.is(".wpmudevevents-login_link-facebook")) {
// Facebook login
callback = function () {
FB.login(function (resp) {
if (resp.authResponse && resp.authResponse.userID) {
// change UI
$root.html('<img src="' + _eab_data.root_url + 'waiting.gif" /> ' + l10nEabApi.please_wait);
$.post(_eab_data.ajax_url, {
"action": "eab_facebook_login",
"user_id": resp.authResponse.userID,
"token": FB.getAccessToken()
}, function (data) {
var status = 0;
try { status = parseInt(data.status, 10); } catch (e) { status = 0; }
if (!status) { // ... handle error
$root.remove();
$me.click();
return false;
}
// Get form if all went well
$.post(_eab_data.ajax_url, {<|fim▁hole|> "post_id": post_id
}, function (data) {
$("body").append('<div id="eab-facebook_form">' + data + '</div>');
$("#eab-facebook_form").find("." + $me.removeClass("active").attr("class")).click();
});
});
}
}, {scope: _eab_data.fb_scope});
return false;
};
} else if ($lnk.is(".wpmudevevents-login_link-twitter")) {
callback = function () {
var init_url = '//api.twitter.com/';
var twLogin = window.open(init_url, "twitter_login", "scrollbars=no,resizable=no,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,height=400,width=600");
$.post(_eab_data.ajax_url, {
"action": "eab_get_twitter_auth_url",
"url": window.location.toString()
}, function (data) {
try {
twLogin.location = data.url;
} catch (e) { twLogin.location.replace(data.url); }
var tTimer = setInterval(function () {
try {
if (twLogin.location.hostname == window.location.hostname) {
// We're back!
var location = twLogin.location;
var search = '';
try { search = location.search; } catch (e) { search = ''; }
clearInterval(tTimer);
twLogin.close();
// change UI
$root.html('<img src="' + _eab_data.root_url + 'waiting.gif" /> ' + l10nEabApi.please_wait);
$.post(_eab_data.ajax_url, {
"action": "eab_twitter_login",
"secret": data.secret,
"data": search
}, function (data) {
var status = 0;
try { status = parseInt(data.status, 10); } catch (e) { status = 0; }
if (!status) { // ... handle error
$root.remove();
$me.click();
return false;
}
// Get form if all went well
$.post(_eab_data.ajax_url, {
"action": "eab_get_form",
"post_id": post_id
}, function (data) {
$("body").append('<div id="eab-twitter_form">' + data + '</div>');
$("#eab-twitter_form").find("." + $me.removeClass("active").attr("class")).click();
});
});
}
} catch (e) {}
}, 300);
});
return false;
};
} else if ($lnk.is(".wpmudevevents-login_link-google")) {
callback = function () {
var googleLogin = window.open('https://www.google.com/accounts', "google_login", "scrollbars=no,resizable=no,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,height=400,width=800");
$.post(_eab_data.ajax_url, {
"action": "eab_get_google_auth_url",
"url": window.location.href
}, function (data) {
var href = data.url;
googleLogin.location = href;
var gTimer = setInterval(function () {
try {
if (googleLogin.location.hostname == window.location.hostname) {
// We're back!
clearInterval(gTimer);
googleLogin.close();
// change UI
$root.html('<img src="' + _eab_data.root_url + 'waiting.gif" /> ' + l10nEabApi.please_wait);
$.post(_eab_data.ajax_url, {
"action": "eab_google_login"
}, function (data) {
var status = 0;
try { status = parseInt(data.status, 10); } catch (e) { status = 0; }
if (!status) { // ... handle error
$root.remove();
$me.click();
return false;
}
// Get form if all went well
$.post(_eab_data.ajax_url, {
"action": "eab_get_form",
"post_id": post_id
}, function (data) {
$("body").append('<div id="eab-google_form">' + data + '</div>');
$("#eab-google_form").find("." + $me.removeClass("active").attr("class")).click();
});
});
}
} catch (e) {}
}, 300);
});
return false;
};
}
else if ($lnk.is(".wpmudevevents-login_link-wordpress")) {
// Pass on to wordpress login
callback = function () {
//window.location = $me.attr("href");
create_wordpress_login_popup($me, post_id);
return false;
};
} else if ($lnk.is(".wpmudevevents-login_link-cancel")) {
// Drop entire thing
callback = function () {
$me.removeClass("active");
$root.remove();
return false;
};
}
if (callback) $lnk
.unbind('click')
.bind('click', callback)
;
});
}
// Init
$(function () {
$(
"a.wpmudevevents-yes-submit, " +
"a.wpmudevevents-maybe-submit, " +
"a.wpmudevevents-no-submit"
)
.css("float", "left")
.unbind('click')
.click(function () {
$(
"a.wpmudevevents-yes-submit, " +
"a.wpmudevevents-maybe-submit, " +
"a.wpmudevevents-no-submit"
).removeClass("active");
create_login_interface($(this));
return false;
})
;
});
})(jQuery);<|fim▁end|> | "action": "eab_get_form", |
<|file_name|>coin_play.py<|end_file_name|><|fim▁begin|># Consider a row of n coins of values v1 . . . vn, where n is even.
# We play a game against an opponent by alternating turns. In each turn,
# a player selects either the first or last coin from the row, removes it
# from the row permanently, and receives the value of the coin. Determine the
# maximum possible amount of money we can definitely win if we move first.
# Note: The opponent is as clever as the user.
# http://www.geeksforgeeks.org/dynamic-programming-set-31-optimal-strategy-for-a-game/
def find_max_val_recur(coins,l,r):
if l + 1 == r:
return max(coins[l],coins[r])
if l == r:
return coins[i]
left_choose = coins[l] + min(find_max_val_recur(coins,l+1,r - 1),find_max_val_recur(coins,l+2,r))<|fim▁hole|>
coin_map = {}
def find_max_val_memo(coins,l,r):
if l + 1 == r:
return max(coins[l],coins[r])
if l == r:
return coins[i]
if (l,r) in coin_map:
return coin_map[(l,r)]
left_choose = coins[l] + min(find_max_val_memo(coins,l+1,r - 1),find_max_val_memo(coins,l+2,r))
right_choose = coins[r] + min(find_max_val_memo(coins,l + 1,r-1),find_max_val_memo(coins,l,r-2))
max_val = max(left_choose,right_choose)
coin_map[(l,r)] = max_val
return max_val
def find_max_val_bottom_up(coins):
coins_len = len(coins)
table = [[0] * coins_len for i in range(coins_len + 1)]
for gap in range(coins_len):
i = 0
for j in range(gap,coins_len):
# Here x is value of F(i+2, j), y is F(i+1, j-1) and
# z is F(i, j-2) in above recursive formula
x = table[i+2][j] if (i+2) <= j else 0
y = table[i+1][j-1] if (i+1) <= (j-1) else 0
z = table[i][j-2] if i <= (j-2) else 0
table[i][j] = max(coins[i] + min(x,y),coins[j] + min(y,z))
i += 1
return table[0][coins_len - 1]
if __name__=="__main__":
coins = [8,15,3,7]
print(find_max_val_bottom_up(coins))<|fim▁end|> | right_choose = coins[r] + min(find_max_val_recur(coins,l + 1,r-1),find_max_val_recur(coins,l,r-2))
return max(left_choose,right_choose) |
<|file_name|>RequestAdministrationPermissionEvent.java<|end_file_name|><|fim▁begin|>/*******************************************************************************
* Copyright (c) 2012 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.obiba.opal.web.gwt.app.client.administration.presenter;
import org.obiba.opal.web.gwt.rest.client.authorization.HasAuthorization;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
/**
* Fire this event to have all administration presenters authorize themselves and callback on this
* {@code HasAuthorization}.
* <p/>
* This allows decoupling a link to the administration section from the section's content.
*/
public class RequestAdministrationPermissionEvent extends GwtEvent<RequestAdministrationPermissionEvent.Handler> {
public interface Handler extends EventHandler {
void onAdministrationPermissionRequest(RequestAdministrationPermissionEvent event);
}
private static final Type<Handler> TYPE = new Type<Handler>();
<|fim▁hole|>
public RequestAdministrationPermissionEvent(HasAuthorization authorization) {
this.authorization = authorization;
}
public HasAuthorization getHasAuthorization() {
return authorization;
}
public static Type<Handler> getType() {
return TYPE;
}
@Override
protected void dispatch(Handler handler) {
handler.onAdministrationPermissionRequest(this);
}
@Override
public GwtEvent.Type<Handler> getAssociatedType() {
return getType();
}
}<|fim▁end|> | private final HasAuthorization authorization; |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""Social content items: messages aka status updates, private messages, etc."""
from __future__ import annotations
import re
from sqlalchemy.orm import relationship
from sqlalchemy.orm.query import Query
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import Integer, UnicodeText
from abilian.core.entities import SEARCHABLE, Entity
from abilian.core.extensions import db
from abilian.core.models.subjects import Group, User
__all__ = ["Message", "PrivateMessage"]
class MessageQuery(Query):
def by_creator(self, user):
return self.filter(Message.creator_id == user.id)
class Message(Entity):
"""Message aka Status update aka Note.
See: http://activitystrea.ms/head/activity-schema.html#note
"""
__tablename__ = "message"
__indexable__ = False
__editable__ = ["content"]
__exportable__ = __editable__ + [
"id",
"created_at",
"updated_at",
"creator_id",
"owner_id",
]
#: The content for this message.
content = Column(UnicodeText(), info=SEARCHABLE | {"index_to": ("text",)})
#: Nullable: if null, then message is public.
group_id = Column(Integer, ForeignKey(Group.id))
#: The group this message has been posted to.
group = relationship("Group", primaryjoin=(group_id == Group.id), lazy="joined")
query = db.session.query_property(MessageQuery)
@property
def tags(self) -> list[str]:
return re.findall(r"(?u)#([^\W]+)", self.content)
# TODO: inheriting from Entity is overkill here
class TagApplication(Entity):
__tablename__ = "tag_application"
tag = Column(UnicodeText, index=True)
message_id = Column(Integer, ForeignKey("message.id"))
class PrivateMessage(Entity):
"""Private messages are like messages, except they are private."""
__tablename__ = "private_message"
__indexable__ = False
__editable__ = ["content", "recipient_id"]<|fim▁hole|> "id",
"created_at",
"updated_at",
"creator_id",
"owner_id",
]
content = Column(UnicodeText, info=SEARCHABLE | {"index_to": ("text",)})
recipient_id = Column(Integer, ForeignKey(User.id), nullable=False)
class Like(Entity):
__tablename__ = "like"
__indexable__ = False
__editable__ = ["content", "message_id"]
__exportable__ = __editable__ + [
"id",
"created_at",
"updated_at",
"creator_id",
"owner_id",
]
content = Column(UnicodeText, info=SEARCHABLE | {"index_to": ("text",)})
message_id = Column(Integer, ForeignKey(Message.id), nullable=False)<|fim▁end|> | __exportable__ = __editable__ + [ |
<|file_name|>stackedlayout.ts<|end_file_name|><|fim▁begin|>/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2015, S. Chris Colbert
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
module phosphor.widgets {
import algo = collections.algorithm;
import Signal = core.Signal;
import emit = core.emit;
import Pair = utility.Pair;
import Size = utility.Size;
/**
* A layout in which only one widget is visible at a time.
*
* User code is responsible for managing the current layout index. The
* index defaults to -1, which means no widget will be shown. The index
* must be set to a valid index in order for a widget to be displayed.
*
* If the current widget is removed, the current index is reset to -1.
*
* This layout will typically be used in conjunction with another
* widget, such as a tab bar, which manipulates the layout index.
*/
export
class StackedLayout extends Layout {
/**
* A signal emitted when a widget is removed from the layout.
*/
static widgetRemoved = new Signal<StackedLayout, Pair<number, Widget>>();
/**
* Construct a new stack layout.
*/
constructor() { super(); }
/**
* Dispose of the resources held by the layout.
*/
dispose(): void {
this._currentItem = null;
this._items = null;
super.dispose();
}
/**
* Get the current index of the layout.
*/
get currentIndex(): number {
return algo.indexOf(this._items, this._currentItem);
}
/**
* Set the current index of the layout.
*/
set currentIndex(index: number) {
var prev = this._currentItem;
var next = this.itemAt(index) || null;
if (prev === next) {
return;
}
this._currentItem = next;
if (prev) prev.widget.hide();
if (next) next.widget.show();
// IE repaints before firing the animation frame which processes
// the layout update triggered by the show/hide calls above. This
// causes a double paint flicker when changing the visible widget.
// The workaround is to refresh the layout immediately.
this.refresh();
}
/**
* Get the current widget in the layout.
*/
get currentWidget(): Widget {
return this._currentItem.widget;
}
/**
* Set the current widget in the layout.
*/
set currentWidget(widget: Widget) {
this.currentIndex = this.indexOf(widget);
}
/**
* Get the number of layout items in the layout.
*/
get count(): number {
return this._items.length;
}
/**
* Get the layout item at the specified index.
*/
itemAt(index: number): ILayoutItem {
return this._items[index];
}
/**
* Remove and return the layout item at the specified index.
*/
removeAt(index: number): ILayoutItem {
var item = algo.removeAt(this._items, index);
if (!item) {
return void 0;
}
if (item === this._currentItem) {
this._currentItem = null;
item.widget.hide();
}
emit(this, StackedLayout.widgetRemoved, new Pair(index, item.widget));
return item;
}
/**
* Add a widget as the last item in the layout.
*
* If the widget already exists in the layout, it will be moved.
*
* Returns the index of the added widget.
*/
addWidget(widget: Widget, alignment?: Alignment): number {
return this.insertWidget(this.count, widget, alignment);
}
/**
* Insert a widget into the layout at the given index.
*
* If the widget already exists in the layout, it will be moved.
*
* Returns the index of the added widget.
*/
insertWidget(index: number, widget: Widget, alignment: Alignment = 0): number {
widget.hide();
this.remove(widget);
this.ensureParent(widget);
return algo.insert(this._items, index, new WidgetItem(widget, alignment));
}
/**
* Move a widget from one index to another.
*
* This method is more efficient for moving a widget than calling
* `insertWidget` for an already added widget. It will not remove
* the widget before moving it and will not emit `widgetRemoved`.
*
* Returns -1 if `fromIndex` is out of range.
*/
moveWidget(fromIndex: number, toIndex: number): number {
return algo.move(this._items, fromIndex, toIndex);
}
/**
* Invalidate the cached layout data and enqueue an update.
*/
invalidate(): void {
this._dirty = true;
super.invalidate();
}
/**
* Compute the preferred size of the layout.
*/
sizeHint(): Size {
if (this._dirty) {
this._setupGeometry();
}
return this._sizeHint;
}
/**
* Compute the minimum size of the layout.
*/
minSize(): Size {
if (this._dirty) {
this._setupGeometry();
}
return this._minSize;
}
/**
* Compute the maximum size of the layout.
*/
maxSize(): Size {
if (this._dirty) {<|fim▁hole|> this._setupGeometry();
}
return this._maxSize;
}
/**
* Update the geometry of the child layout items.
*/
protected layout(x: number, y: number, width: number, height: number): void {
if (this._dirty) {
this._setupGeometry();
}
if (this._currentItem !== null) {
this._currentItem.setGeometry(x, y, width, height);
}
}
/**
* Initialize the layout items and internal sizes for the layout.
*/
private _setupGeometry(): void {
// Bail early when no work needs to be done.
if (!this._dirty) {
return;
}
this._dirty = false;
// No parent means the layout is not yet attached.
var parent = this.parent;
if (!parent) {
this._sizeHint = Size.Zero;
this._minSize = Size.Zero;
this._maxSize = Size.Zero;
return;
}
// Compute the size bounds based on the visible item.
var hintW = 0;
var hintH = 0;
var minW = 0;
var minH = 0;
var maxW = Infinity;
var maxH = Infinity;
var item = this._currentItem;
if (item !== null) {
item.invalidate();
var itemHint = item.sizeHint();
var itemMin = item.minSize();
var itemMax = item.maxSize();
hintW = Math.max(hintW, itemHint.width);
hintH = Math.max(hintH, itemHint.height);
minW = Math.max(minW, itemMin.width);
minH = Math.max(minH, itemMin.height);
maxW = Math.min(maxW, itemMax.width);
maxH = Math.min(maxH, itemMax.height);
}
// Account for padding and border on the parent.
var box = parent.boxSizing;
var boxW = box.horizontalSum;
var boxH = box.verticalSum;
hintW += boxW;
hintH += boxH;
minW += boxW;
minH += boxH;
maxW += boxW;
maxH += boxH;
// Update the internal sizes.
this._sizeHint = new Size(hintW, hintH);
this._minSize = new Size(minW, minH);
this._maxSize = new Size(maxW, maxH);
}
private _dirty = true;
private _sizeHint: Size = null;
private _minSize: Size = null;
private _maxSize: Size = null;
private _items: ILayoutItem[] = [];
private _currentItem: ILayoutItem = null;
}
} // module phosphor.widgets<|fim▁end|> | |
<|file_name|>template.go<|end_file_name|><|fim▁begin|>package command
<|fim▁hole|>
"github.com/atsaki/golang-cloudstack-library"
"github.com/atsaki/lockgate"
"github.com/atsaki/lockgate/cli"
)
var (
TemplateList = cli.Command{
Name: "list",
Help: "List templates",
Args: []cli.Argument{
cli.Argument{
Name: "ids",
Help: "VM ids",
Type: cli.Strings,
},
},
Flags: []cli.Flag{
cli.Flag{
Name: "templatefilter",
Help: "templatefilter",
Default: "executable",
Type: cli.String,
},
cli.Flag{
Name: "name",
Help: "The name of the template",
Type: cli.String,
},
cli.Flag{
Name: "zone",
Help: "The zoneid or zonename of the template",
Type: cli.String,
},
},
Action: func(c *cli.Context) {
lockgate.SetLogLevel(c)
client, err := lockgate.GetClient(c)
if err != nil {
log.Fatal(err)
}
params := cloudstack.ListTemplatesParameter{}
ids := lockgate.GetArgumentsFromStdin()
ids = append(ids, c.Command.Arg("ids").Strings()...)
templatefilter := c.Command.Flag("templatefilter").String()
if templatefilter != "" {
params.SetTemplatefilter(templatefilter)
}
name := c.Command.Flag("name").String()
if name != "" {
params.SetName(name)
}
zone := c.Command.Flag("zone").String()
if zone != "" {
params.SetZoneid(zone)
}
var templates []cloudstack.Template
if len(ids) > 0 {
for _, id := range ids {
params.SetId(id)
resp, err := client.ListTemplates(params)
if err != nil {
fmt.Println(err)
log.Fatal(err)
}
templates = append(templates, resp...)
}
} else {
templates, err = client.ListTemplates(params)
if err != nil {
fmt.Println(err)
log.Fatal(err)
}
}
w := lockgate.GetTabWriter(c)
w.Print(templates)
},
}
Template = cli.Command{
Name: "template",
Help: "Manage template",
Commands: []cli.Command{
TemplateList,
},
}
)<|fim▁end|> | import (
"fmt"
"log" |
<|file_name|>DealSharpProperties.java<|end_file_name|><|fim▁begin|>package cn.xishan.oftenporter.porter.core.init;
import cn.xishan.oftenporter.porter.core.advanced.IConfigData;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Created by https://github.com/CLovinr on 2018-12-21.
*/
public class DealSharpProperties
{
private static final Logger LOGGER = LoggerFactory.getLogger(DealSharpProperties.class);
private static class PropOne
{
private String propKey,
originValue;
private int startIndex, endIndex;
public PropOne(String propKey, String originValue, int startIndex, int endIndex)
{
this.propKey = propKey;
this.originValue = originValue;
this.startIndex = startIndex;
this.endIndex = endIndex;
}
public String getPropKey()
{
return propKey;
}
public String replace(String propValue)
{
String str = originValue.substring(0, startIndex) + propValue + originValue.substring(endIndex);
return str;
}
}
/**
* 替换所有的#{propertyName}.
*
* @param string
* @param properties
* @param forEmpty 如果不为null,则用于替换所有不存在的属性。
* @return
*/
public static String replaceSharpProperties(String string, Map<String, ?> properties, String forEmpty)
{
for (Map.Entry<String, ?> entry : properties.entrySet())
{
if (string.contains("#{" + entry.getKey() + "}"))<|fim▁hole|>// if (entry.getValue() instanceof Map || entry.getValue() instanceof Collection)
// {
// rs = JSON.toJSONString(entry.getValue());
// } else
// {
// rs = String.valueOf(entry.getValue());
// }
if (entry.getValue() instanceof CharSequence)
{
rs = String.valueOf(entry.getValue());
} else if (entry.getValue() == null)
{
rs = "";
} else
{
rs = JSON.toJSONString(entry.getValue());
}
string = string.replace("#{" + entry.getKey() + "}", rs);
}
}
if (forEmpty != null)
{
string = string.replaceAll("#\\{[^{}]+\\}", forEmpty);//去掉未设置的
}
return string;
}
/**
* 替换#{properName}变量。
*
* @param srcMap 待替换属性值的map
* @param propertiesMap 提供属性的map
*/
public static void dealSharpProperties(Map srcMap, Map propertiesMap)
{
dealSharpProperties(srcMap, propertiesMap, false);
}
/**
* 替换#{properName}变量。
*
* @param srcMap 待替换属性值的map
* @param propertiesMap 提供属性的map
* @param keepNotFound 是否保留未找到的变量。
*/
public static void dealSharpProperties(Map srcMap, Map propertiesMap, boolean keepNotFound)
{
Set<String> containsVar = null;
boolean isFirst = true;
boolean hasSet = true;
//处理properties
while (hasSet)
{
hasSet = false;
Collection<String> nameCollection;
if (isFirst)
{
nameCollection = srcMap.keySet();
} else
{
nameCollection = containsVar;
}
containsVar = new HashSet<>();
for (String properName : nameCollection)
{
Object value = srcMap.get(properName);
if (!(value instanceof CharSequence))
{
continue;
}
String valueString = String.valueOf(value);
PropOne propOne = getPropertiesKey(String.valueOf(valueString));
if (propOne != null && propOne.getPropKey().equals(properName))
{
throw new RuntimeException(
"can not set property of \"" + properName + "\" with value \"" + valueString + "\",prop name eq value attr name");
} else if (propOne != null)
{
containsVar.add(properName);
if (LOGGER.isDebugEnabled())
{
LOGGER.debug("replace sharp property:key={},replace-attr={},origin-value={}", properName,
propOne.getPropKey(), valueString);
}
String replaceStr = null;
if (propertiesMap.containsKey(propOne.getPropKey()))
{
replaceStr = String.valueOf(propertiesMap.get(propOne.getPropKey()));
} else
{
if (keepNotFound)
{
containsVar.remove(properName);
} else
{
replaceStr = "";
LOGGER.warn("proper value with key '{}' is empty", propOne.getPropKey());
}
}
if (replaceStr != null)
{
String newValue = propOne.replace(replaceStr);
srcMap.put(properName, newValue);
if (LOGGER.isDebugEnabled())
{
LOGGER.debug("replace sharp property:key={},new-value={}", properName, newValue);
}
}
hasSet = true;
}
}
isFirst = false;
}
}
static void dealProperties(IConfigData configData)
{
Set<String> containsVar = null;
boolean isFirst = true;
boolean hasSet = true;
//处理properties
while (hasSet)
{
hasSet = false;
Collection<String> nameCollection;
if (isFirst)
{
nameCollection = configData.propertyNames();
} else
{
nameCollection = containsVar;
}
containsVar = new HashSet<>();
for (String properName : nameCollection)
{
Object value = configData.get(properName);
if (!(value instanceof CharSequence))
{
continue;
}
String valueString = String.valueOf(value);
PropOne propOne = getPropertiesKey(String.valueOf(valueString));
if (propOne != null && propOne.getPropKey().equals(properName))
{
throw new RuntimeException(
"can not set property of " + properName + " with value \"" + valueString + "\"");
} else if (propOne != null)
{
containsVar.add(properName);
if (LOGGER.isDebugEnabled())
{
LOGGER.debug("replace sharp property:key={},replace-attr={},origin-value={}", properName,
propOne.getPropKey(), valueString);
}
String replaceStr;
if (configData.contains(propOne.getPropKey()))
{
replaceStr = configData.getString(propOne.getPropKey());
} else
{
replaceStr = "";
LOGGER.warn("proper value with key '{}' is empty", propOne.getPropKey());
}
String newValue = propOne.replace(replaceStr);
configData.set(properName, newValue);
if (LOGGER.isDebugEnabled())
{
LOGGER.debug("replace sharp property:key={},new-value={}", properName, newValue);
}
hasSet = true;
}
}
isFirst = false;
}
}
private static final Pattern PROPERTIES_PATTERN = Pattern.compile("#\\{([^{}]+)}");
private static PropOne getPropertiesKey(String value)
{
Matcher matcher = PROPERTIES_PATTERN.matcher(value);
if (matcher.find())
{
PropOne propOne = new PropOne(matcher.group(1).trim(), value, matcher.start(), matcher.end());
return propOne;
} else
{
return null;
}
}
}<|fim▁end|> | {
String rs; |
<|file_name|>capsule_capsule_manifold_generator.rs<|end_file_name|><|fim▁begin|>use crate::math::Isometry;
use crate::pipeline::narrow_phase::{
ContactDispatcher, ContactManifoldGenerator, ConvexPolyhedronConvexPolyhedronManifoldGenerator,
};
use crate::query::{ContactManifold, ContactPrediction, ContactPreprocessor};
use crate::shape::{Capsule, Shape};
use na::{self, RealField};
/// Collision detector between a concave shape and another shape.
pub struct CapsuleCapsuleManifoldGenerator<N: RealField> {
// FIXME: use a dedicated segment-segment algorithm instead.
sub_detector: ConvexPolyhedronConvexPolyhedronManifoldGenerator<N>,
}
impl<N: RealField> CapsuleCapsuleManifoldGenerator<N> {
/// Creates a new collision detector between a concave shape and another shape.
pub fn new() -> CapsuleCapsuleManifoldGenerator<N> {
CapsuleCapsuleManifoldGenerator {
sub_detector: ConvexPolyhedronConvexPolyhedronManifoldGenerator::new(),
}
}
fn do_update(
&mut self,
dispatcher: &dyn ContactDispatcher<N>,
m1: &Isometry<N>,
g1: &Capsule<N>,
proc1: Option<&dyn ContactPreprocessor<N>>,
m2: &Isometry<N>,
g2: &Capsule<N>,
proc2: Option<&dyn ContactPreprocessor<N>>,
prediction: &ContactPrediction<N>,
manifold: &mut ContactManifold<N>,
) -> bool {
let segment1 = g1.segment();
let segment2 = g2.segment();
let mut prediction = prediction.clone();
let new_linear_prediction = prediction.linear() + g1.radius + g2.radius;
prediction.set_linear(new_linear_prediction);
// Update all collisions
self.sub_detector.generate_contacts(
dispatcher,
m1,
&segment1,
Some(&(proc1, &g1.contact_preprocessor())),
m2,
&segment2,
Some(&(proc2, &g2.contact_preprocessor())),
&prediction,
manifold,
)
}
}
impl<N: RealField> ContactManifoldGenerator<N> for CapsuleCapsuleManifoldGenerator<N> {
fn generate_contacts(
&mut self,
d: &dyn ContactDispatcher<N>,
ma: &Isometry<N>,
a: &dyn Shape<N>,
proc1: Option<&dyn ContactPreprocessor<N>>,
mb: &Isometry<N>,
b: &dyn Shape<N>,
proc2: Option<&dyn ContactPreprocessor<N>>,
prediction: &ContactPrediction<N>,
manifold: &mut ContactManifold<N>,
) -> bool {
if let (Some(cs1), Some(cs2)) = (a.as_shape::<Capsule<N>>(), b.as_shape::<Capsule<N>>()) {
self.do_update(d, ma, cs1, proc1, mb, cs2, proc2, prediction, manifold)<|fim▁hole|>}<|fim▁end|> | } else {
false
}
} |
<|file_name|>check.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""Checks/fixes are bundled in one namespace."""
import logging
from rdflib.namespace import RDF, SKOS
from .rdftools.namespace import SKOSEXT
from .rdftools import localname, find_prop_overlap
def _hierarchy_cycles_visit(rdf, node, parent, break_cycles, status):
if status.get(node) is None:
status[node] = 1 # entered
for child in sorted(rdf.subjects(SKOS.broader, node)):
_hierarchy_cycles_visit(
rdf, child, node, break_cycles, status)
status[node] = 2 # set this node as completed
elif status.get(node) == 1: # has been entered but not yet done
if break_cycles:
logging.warning("Hierarchy cycle removed at %s -> %s",
localname(parent), localname(node))
rdf.remove((node, SKOS.broader, parent))
rdf.remove((node, SKOS.broaderTransitive, parent))
rdf.remove((node, SKOSEXT.broaderGeneric, parent))
rdf.remove((node, SKOSEXT.broaderPartitive, parent))
rdf.remove((parent, SKOS.narrower, node))
rdf.remove((parent, SKOS.narrowerTransitive, node))
else:
logging.warning(
"Hierarchy cycle detected at %s -> %s, "
"but not removed because break_cycles is not active",
localname(parent), localname(node))
elif status.get(node) == 2: # is completed already
pass
def hierarchy_cycles(rdf, fix=False):
"""Check if the graph contains skos:broader cycles and optionally break these.
:param Graph rdf: An rdflib.graph.Graph object.
:param bool fix: Fix the problem by removing any skos:broader that overlaps
with skos:broaderTransitive.
"""
top_concepts = sorted(rdf.subject_objects(SKOS.hasTopConcept))
status = {}
for cs, root in top_concepts:
_hierarchy_cycles_visit(
rdf, root, None, fix, status=status)
# double check that all concepts were actually visited in the search,
# and visit remaining ones if necessary
recheck_top_concepts = False
for conc in sorted(rdf.subjects(RDF.type, SKOS.Concept)):
if conc not in status:
recheck_top_concepts = True
_hierarchy_cycles_visit(
rdf, conc, None, fix, status=status)
return recheck_top_concepts
def disjoint_relations(rdf, fix=False):
"""Check if the graph contains concepts connected by both of the semantically
disjoint semantic skos:related and skos:broaderTransitive (S27),
and optionally remove the involved skos:related relations.
:param Graph rdf: An rdflib.graph.Graph object.
:param bool fix: Fix the problem by removing skos:related relations that
overlap with skos:broaderTransitive.
"""
for conc1, conc2 in sorted(rdf.subject_objects(SKOS.related)):
if conc2 in sorted(rdf.transitive_objects(conc1, SKOS.broader)):
if fix:
logging.warning(
"Concepts %s and %s connected by both "
"skos:broaderTransitive and skos:related, "
"removing skos:related",
conc1, conc2)
rdf.remove((conc1, SKOS.related, conc2))
rdf.remove((conc2, SKOS.related, conc1))
else:
logging.warning(
"Concepts %s and %s connected by both "
"skos:broaderTransitive and skos:related, "
"but keeping it because keep_related is enabled",
conc1, conc2)
def hierarchical_redundancy(rdf, fix=False):
"""Check for and optionally remove extraneous skos:broader relations.
:param Graph rdf: An rdflib.graph.Graph object.
:param bool fix: Fix the problem by removing skos:broader relations between
concepts that are otherwise connected by skos:broaderTransitive.
"""
for conc, parent1 in sorted(rdf.subject_objects(SKOS.broader)):
for parent2 in sorted(rdf.objects(conc, SKOS.broader)):
if parent1 == parent2:
continue # must be different
if parent2 in rdf.transitive_objects(parent1, SKOS.broader):
if fix:
logging.warning(<|fim▁hole|> "%s skos:broader %s",
conc, parent2)
rdf.remove((conc, SKOS.broader, parent2))
rdf.remove((conc, SKOS.broaderTransitive, parent2))
rdf.remove((parent2, SKOS.narrower, conc))
rdf.remove((parent2, SKOS.narrowerTransitive, conc))
else:
logging.warning(
"Redundant hierarchical relationship "
"%s skos:broader %s found, but not eliminated "
"because eliminate_redundancy is not set",
conc, parent2)
def preflabel_uniqueness(rdf, policy='all'):
"""Check that concepts have no more than one value of skos:prefLabel per
language tag (S14), and optionally move additional values to skos:altLabel.
:param Graph rdf: An rdflib.graph.Graph object.
:param str policy: Policy for deciding which value to keep as prefLabel
when multiple prefLabels are found. Possible values are 'shortest'
(keep the shortest label), 'longest' (keep the longest label),
'uppercase' (prefer uppercase), 'lowercase' (prefer uppercase) or
'all' (keep all, just log the problems). Alternatively, a list of
policies to apply in order, such as ['shortest', 'lowercase'], may
be used.
"""
resources = set(
(res for res, label in rdf.subject_objects(SKOS.prefLabel)))
policy_fn = {
'shortest': len,
'longest': lambda x: -len(x),
'uppercase': lambda x: int(x[0].islower()),
'lowercase': lambda x: int(x[0].isupper())
}
if type(policy) not in (list, tuple):
policies = policy.split(',')
else:
policies = policy
for p in policies:
if p not in policy_fn:
logging.critical("Unknown preflabel-policy: %s", policy)
return
def key_fn(label):
return [policy_fn[p](label) for p in policies] + [str(label)]
for res in sorted(resources):
prefLabels = {}
for label in rdf.objects(res, SKOS.prefLabel):
lang = label.language
if lang not in prefLabels:
prefLabels[lang] = []
prefLabels[lang].append(label)
for lang, labels in prefLabels.items():
if len(labels) > 1:
if policies[0] == 'all':
logging.warning(
"Resource %s has more than one prefLabel@%s, "
"but keeping all of them due to preflabel-policy=all.",
res, lang)
continue
chosen = sorted(labels, key=key_fn)[0]
logging.warning(
"Resource %s has more than one prefLabel@%s: "
"choosing %s (policy: %s)",
res, lang, chosen, str(policy))
for label in labels:
if label != chosen:
rdf.remove((res, SKOS.prefLabel, label))
rdf.add((res, SKOS.altLabel, label))
def label_overlap(rdf, fix=False):
"""Check if concepts have the same value for any two of the pairwise
disjoint properties skos:prefLabel, skos:altLabel and skos:hiddenLabel
(S13), and optionally remove the least significant property.
:param Graph rdf: An rdflib.graph.Graph object.
:param bool fix: Fix the problem by removing the least significant property
(altLabel or hiddenLabel).
"""
def label_warning(res, label, keep, remove):
if fix:
logging.warning(
"Resource %s has '%s'@%s as both %s and %s; removing %s",
res, label, label.language, keep, remove, remove
)
else:
logging.warning(
"Resource %s has '%s'@%s as both %s and %s",
res, label, label.language, keep, remove
)
for res, label in find_prop_overlap(rdf, SKOS.prefLabel, SKOS.altLabel):
label_warning(res, label, 'prefLabel', 'altLabel')
if fix:
rdf.remove((res, SKOS.altLabel, label))
for res, label in find_prop_overlap(rdf, SKOS.prefLabel, SKOS.hiddenLabel):
label_warning(res, label, 'prefLabel', 'hiddenLabel')
if fix:
rdf.remove((res, SKOS.hiddenLabel, label))
for res, label in find_prop_overlap(rdf, SKOS.altLabel, SKOS.hiddenLabel):
label_warning(res, label, 'altLabel', 'hiddenLabel')
if fix:
rdf.remove((res, SKOS.hiddenLabel, label))<|fim▁end|> | "Eliminating redundant hierarchical relationship: " |
<|file_name|>1A - Theatre Square.py<|end_file_name|><|fim▁begin|>from math import *
<|fim▁hole|>m = int(spl[1])
a = int(spl[2])
i = int(ceil(n * 1.0 / a))
j = int(ceil(m * 1.0 / a))
print max(1, i * j)<|fim▁end|> | inp = raw_input()
spl = inp.split()
n = int(spl[0]) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from base64 import b64encode, b64decode
import datetime
import copy
import json
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound, HttpResponseNotAllowed
from gripcontrol import Channel, HttpResponseFormat, HttpStreamFormat
from django_grip import set_hold_longpoll, set_hold_stream, publish
import redis_ops
def _setting(name, default):
v = getattr(settings, name, None)
if v is None:
return default
return v
db = redis_ops.RedisOps()
grip_prefix = _setting('WHINBOX_GRIP_PREFIX', 'wi-')
orig_headers = _setting('WHINBOX_ORIG_HEADERS', False)
# useful list derived from requestbin
ignore_headers = """
X-Varnish
X-Forwarded-For
X-Heroku-Dynos-In-Use
X-Request-Start
X-Heroku-Queue-Wait-Time
X-Heroku-Queue-Depth
X-Real-Ip
X-Forwarded-Proto
X-Via
X-Forwarded-Port
Grip-Sig
Grip-Feature
Grip-Last
""".split("\n")[1:-1]
def _ignore_header(name):
name = name.lower()
for h in ignore_headers:
if name == h.lower():
return True
return False
def _convert_header_name(name):
out = ''
word_start = True
for c in name:
if c == '_':
out += '-'
word_start = True
elif word_start:
out += c.upper()
word_start = False
else:
out += c.lower()
return out
def _req_to_item(req):
item = dict()
item['method'] = req.method
item['path'] = req.path
query = req.META.get('QUERY_STRING')
if query:
item['query'] = query
raw_headers = list()
content_length = req.META.get('CONTENT_LENGTH')
if content_length:
raw_headers.append(('CONTENT_LENGTH', content_length))
content_type = req.META.get('CONTENT_TYPE')
if content_type:
raw_headers.append(('CONTENT_TYPE', content_type))
for k, v in req.META.iteritems():
if k.startswith('HTTP_'):
raw_headers.append((k[5:], v))
# undjangoify the header names
headers = list()
for h in raw_headers:
headers.append((_convert_header_name(h[0]), h[1]))
if orig_headers:
# if this option is set, then we assume the exact headers are magic prefixed
tmp = list()
for h in headers:
if h[0].lower().startswith('eb9bf0f5-'):
tmp.append((h[0][9:], h[1]))
headers = tmp
else:
# otherwise, use the blacklist to clean things up
tmp = list()
for h in headers:
if not _ignore_header(h[0]):
tmp.append(h)
headers = tmp
item['headers'] = headers
if len(req.body) > 0:
try:
# if the body is valid utf-8, then store as text
item['body'] = req.body.decode('utf-8')
except:
# else, store as binary
item['body-bin'] = b64encode(req.body)
forwardedfor = req.META.get('HTTP_X_FORWARDED_FOR')
if forwardedfor:
ip_address = forwardedfor.split(',')[0].strip()
else:
ip_address = req.META['REMOTE_ADDR']
item['ip_address'] = ip_address
return item
def _convert_item(item, responded=False):
out = copy.deepcopy(item)
created = datetime.datetime.fromtimestamp(item['created']).isoformat()
if len(created) > 0 and created[-1] != 'Z':
created += 'Z'
out['created'] = created
if responded:
out['state'] = 'responded'
else:
out['state'] = 'response-pending'
return out
def root(req):
return HttpResponseNotFound('Not Found\n')
def create(req):
if req.method == 'POST':
host = req.META.get('HTTP_HOST')
if not host:
return HttpResponseBadRequest('Bad Request: No \'Host\' header\n')
inbox_id = req.POST.get('id')
if inbox_id is not None and len(inbox_id) > 64:
return HttpResponseBadRequest('Bad Request: Id length must not exceed 64\n')
ttl = req.POST.get('ttl')
if ttl is not None:
ttl = int(ttl)
if ttl is None:
ttl = 3600
response_mode = req.POST.get('response_mode')
if not response_mode:
response_mode = 'auto'
if response_mode not in ('auto', 'wait-verify', 'wait'):
return HttpResponseBadRequest('Bad Request: response_mode must be "auto", "wait-verify", or "wait"\n')
try:
inbox_id = db.inbox_create(inbox_id, ttl, response_mode)
except redis_ops.InvalidId:
return HttpResponseBadRequest('Bad Request: Invalid id\n')
except redis_ops.ObjectExists:
return HttpResponse('Conflict: Inbox already exists\n', status=409)
except:
return HttpResponse('Service Unavailable\n', status=503)
out = dict()
out['id'] = inbox_id
out['base_url'] = 'http://' + host + '/i/' + inbox_id + '/'
out['ttl'] = ttl
out['response_mode'] = response_mode
return HttpResponse(json.dumps(out) + '\n', content_type='application/json')
else:
return HttpResponseNotAllowed(['POST'])
def inbox(req, inbox_id):
if req.method == 'GET':
host = req.META.get('HTTP_HOST')
if not host:
return HttpResponseBadRequest('Bad Request: No \'Host\' header\n')
try:
inbox = db.inbox_get(inbox_id)
except redis_ops.InvalidId:
return HttpResponseBadRequest('Bad Request: Invalid id\n')
except redis_ops.ObjectDoesNotExist:
return HttpResponseNotFound('Not Found\n')
except:
return HttpResponse('Service Unavailable\n', status=503)
out = dict()
out['id'] = inbox_id
out['base_url'] = 'http://' + host + '/i/' + inbox_id + '/'
out['ttl'] = inbox['ttl']
response_mode = inbox.get('response_mode')
if not response_mode:
response_mode = 'auto'
out['response_mode'] = response_mode
return HttpResponse(json.dumps(out) + '\n', content_type='application/json')
elif req.method == 'DELETE':
try:
db.inbox_delete(inbox_id)
except redis_ops.InvalidId:
return HttpResponseBadRequest('Bad Request: Invalid id\n')
except redis_ops.ObjectDoesNotExist:
return HttpResponseNotFound('Not Found\n')
except:
return HttpResponse('Service Unavailable\n', status=503)
# we'll push a 404 to any long polls because we're that cool
publish(grip_prefix + 'inbox-%s' % inbox_id, HttpResponseFormat(code=404, headers={'Content-Type': 'text/html'}, body='Not Found\n'))
return HttpResponse('Deleted\n')
else:
return HttpResponseNotAllowed(['GET', 'DELETE'])
def refresh(req, inbox_id):
if req.method == 'POST':
ttl = req.POST.get('ttl')
if ttl is not None:
ttl = int(ttl)
try:
db.inbox_refresh(inbox_id, ttl)
except redis_ops.InvalidId:
return HttpResponseBadRequest('Bad Request: Invalid id\n')
except redis_ops.ObjectDoesNotExist:
return HttpResponseNotFound('Not Found\n')
except:
return HttpResponse('Service Unavailable\n', status=503)
return HttpResponse('Refreshed\n')
else:
return HttpResponseNotAllowed(['POST'])
def respond(req, inbox_id, item_id):
if req.method == 'POST':
try:
content = json.loads(req.body)
except:
return HttpResponseBadRequest('Bad Request: Body must be valid JSON\n')
try:
code = content.get('code')
if code is not None:
code = int(code)
else:
code = 200
reason = content.get('reason')
headers = content.get('headers')
if 'body-bin' in content:
body = b64decode(content['body-bin'])
elif 'body' in content:
body = content['body']
else:
body = ''
except:
return HttpResponseBadRequest('Bad Request: Bad format of response\n')
try:
db.request_remove_pending(inbox_id, item_id)
except redis_ops.InvalidId:
return HttpResponseBadRequest('Bad Request: Invalid id\n')
except redis_ops.ObjectDoesNotExist:
return HttpResponseNotFound('Not Found\n')
except:
return HttpResponse('Service Unavailable\n', status=503)
publish(grip_prefix + 'wait-%s-%s' % (inbox_id, item_id), HttpResponseFormat(code=code, reason=reason, headers=headers, body=body), id='1', prev_id='0')
return HttpResponse('Ok\n')
else:
return HttpResponseNotAllowed(['POST'])
def hit(req, inbox_id):
if len(req.grip.last) > 0:
for channel, last_id in req.grip.last.iteritems():
break
set_hold_longpoll(req, Channel(channel, last_id))
return HttpResponse('Service Unavailable\n', status=503, content_type='text/html')
try:
inbox = db.inbox_get(inbox_id)
except redis_ops.InvalidId:
return HttpResponseBadRequest('Bad Request: Invalid id\n')
except redis_ops.ObjectDoesNotExist:
return HttpResponseNotFound('Not Found\n')
except:
return HttpResponse('Service Unavailable\n', status=503)
response_mode = inbox.get('response_mode')
if not response_mode:
response_mode = 'auto'
# pubsubhubbub verify request?
hub_challenge = req.GET.get('hub.challenge')
if response_mode == 'wait' or (response_mode == 'wait-verify' and hub_challenge):
respond_now = False
else:
respond_now = True
item = _req_to_item(req)
if hub_challenge:
item['type'] = 'hub-verify'
else:
item['type'] = 'normal'
try:
item_id, prev_id, item_created = db.inbox_append_item(inbox_id, item)
db.inbox_clear_expired_items(inbox_id)
except redis_ops.InvalidId:
return HttpResponseBadRequest('Bad Request: Invalid id\n')
except redis_ops.ObjectDoesNotExist:
return HttpResponseNotFound('Not Found\n')
except:
return HttpResponse('Service Unavailable\n', status=503)
item['id'] = item_id
item['created'] = item_created
item = _convert_item(item, respond_now)
hr_headers = dict()
hr_headers['Content-Type'] = 'application/json'
hr = dict()
hr['last_cursor'] = item_id
hr['items'] = [item]
hr_body = json.dumps(hr) + '\n'
hs_body = json.dumps(item) + '\n'
formats = list()
formats.append(HttpResponseFormat(headers=hr_headers, body=hr_body))
formats.append(HttpStreamFormat(hs_body))
publish(grip_prefix + 'inbox-%s' % inbox_id, formats, id=item_id, prev_id=prev_id)
if respond_now:
if hub_challenge:
return HttpResponse(hub_challenge)
else:
return HttpResponse('Ok\n')
else:
# wait for the user to respond
db.request_add_pending(inbox_id, item_id)
set_hold_longpoll(req, Channel(grip_prefix + 'wait-%s-%s' % (inbox_id, item_id), '0'))
return HttpResponse('Service Unavailable\n', status=503, content_type='text/html')
def items(req, inbox_id):
if req.method == 'GET':
try:
db.inbox_refresh(inbox_id)
except redis_ops.InvalidId:
return HttpResponseBadRequest('Bad Request: Invalid id\n')
except redis_ops.ObjectDoesNotExist:
return HttpResponseNotFound('Not Found\n')
except:
return HttpResponse('Service Unavailable\n', status=503)
order = req.GET.get('order')
if order and order not in ('created', '-created'):
return HttpResponseBadRequest('Bad Request: Invalid order value\n')
if not order:
order = 'created'
imax = req.GET.get('max')
if imax:
try:
imax = int(imax)
if imax < 1:
raise ValueError('max too small')
except:
return HttpResponseBadRequest('Bad Request: Invalid max value\n')
if not imax or imax > 50:
imax = 50
since = req.GET.get('since')
since_id = None
since_cursor = None
if since:
if since.startswith('id:'):
since_id = since[3:]
elif since.startswith('cursor:'):
since_cursor = since[7:]
else:
return HttpResponseBadRequest('Bad Request: Invalid since value\n')
# at the moment, cursor is identical to id
item_id = None
if since_id:
item_id = since_id
elif since_cursor:
item_id = since_cursor
if order == 'created':
try:
items, last_id = db.inbox_get_items_after(inbox_id, item_id, imax)
except redis_ops.InvalidId:
return HttpResponseBadRequest('Bad Request: Invalid id\n')
except redis_ops.ObjectDoesNotExist:
return HttpResponseNotFound('Not Found\n')
except:
return HttpResponse('Service Unavailable\n', status=503)
<|fim▁hole|> for i in items:
out_items.append(_convert_item(i, not db.request_is_pending(inbox_id, i['id'])))
out['items'] = out_items
if len(out_items) == 0:
set_hold_longpoll(req, Channel(grip_prefix + 'inbox-%s' % inbox_id, last_id))
return HttpResponse(json.dumps(out) + '\n', content_type='application/json')
else: # -created
try:
items, last_id, eof = db.inbox_get_items_before(inbox_id, item_id, imax)
except redis_ops.InvalidId:
return HttpResponseBadRequest('Bad Request: Invalid id\n')
except redis_ops.ObjectDoesNotExist:
return HttpResponseNotFound('Not Found\n')
except:
return HttpResponse('Service Unavailable\n', status=503)
out = dict()
if not eof and last_id:
out['last_cursor'] = last_id
out_items = list()
for i in items:
out_items.append(_convert_item(i, not db.request_is_pending(inbox_id, i['id'])))
out['items'] = out_items
return HttpResponse(json.dumps(out) + '\n', content_type='application/json')
else:
return HttpResponseNotAllowed(['GET'])
def stream(req, inbox_id):
if req.method == 'GET':
try:
db.inbox_get(inbox_id)
except redis_ops.InvalidId:
return HttpResponseBadRequest('Bad Request: Invalid id\n')
except redis_ops.ObjectDoesNotExist:
return HttpResponseNotFound('Not Found\n')
except:
return HttpResponse('Service Unavailable\n', status=503)
set_hold_stream(req, grip_prefix + 'inbox-%s' % inbox_id)
return HttpResponse('[opened]\n', content_type='text/plain')
else:
return HttpResponseNotAllowed(['GET'])<|fim▁end|> | out = dict()
out['last_cursor'] = last_id
out_items = list() |
<|file_name|>compiler.py<|end_file_name|><|fim▁begin|>import unittest, re
from rexp.compiler import PatternCompiler
class CompilerTestMethods(unittest.TestCase):
def test_compile_1(self):
compiler = PatternCompiler(pattern_set=dict(
TEST=r'\w+'
))
try:
c1 = compiler.compile('$1{TEST}')
except Exception as exc:
self.assertTrue(1)<|fim▁hole|>
c1 = compiler.compile('$1{TEST}', ['test'])
self.assertEqual(c1, r'(?:(?P<test>(\w+)))')
def test_compile_2(self):
compiler = PatternCompiler(pattern_set=dict(
TEST=r'\w+'
))
try:
c1 = compiler.compile('$1{TEST}')
except:
self.assertTrue(1)
c1 = compiler.compile('$1{TEST}', ['test'])
self.assertEqual(c1, r'(?:(?P<test>(\w+)))')<|fim▁end|> | |
<|file_name|>test_disconnect_host_volume_create_negative1.py<|end_file_name|><|fim▁begin|>import zstackwoodpecker.operations.host_operations as host_ops
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.volume_operations as vol_ops
import zstackwoodpecker.test_util as test_util
volume = None
disconnect = False
host = None
def test():
global disconnect, volume, host
# query&get clusters
cond = res_ops.gen_query_conditions('name', '=', "cluster1")
cluster1 = res_ops.query_resource(res_ops.CLUSTER, cond)[0]
cond = res_ops.gen_query_conditions('name', '=', "cluster2")
cluster2 = res_ops.query_resource(res_ops.CLUSTER, cond)[0]
# query&get hosts
cond = res_ops.gen_query_conditions('clusterUuid', '=', cluster1.uuid)
cluster1_host = res_ops.query_resource(res_ops.HOST, cond)
cond = res_ops.gen_query_conditions('clusterUuid', '=', cluster2.uuid)
cluster2_host = res_ops.query_resource(res_ops.HOST, cond)
# disconnect mn_host1
host = cluster1_host[0]
host_ops.update_kvm_host(host.uuid, 'username', "root1")
try:
host_ops.reconnect_host(host.uuid)
except:
test_util.test_logger("host: [%s] is disconnected" % host.uuid)
disconnect = True
# create_volume on 2 clusters
ps = res_ops.query_resource(res_ops.PRIMARY_STORAGE)[0]
systemtags1 = ["volumeProvisioningStrategy::ThickProvisioning", "capability::virtio-scsi",
"miniStorage::clusterUuid::%s" % cluster1.uuid]
volume_creation_option = test_util.VolumeOption()
volume_creation_option.set_name("cluster1_volume")
volume_creation_option.set_primary_storage_uuid(ps.uuid)
volume_creation_option.set_system_tags(systemtags1)
volume_creation_option.set_diskSize(2 * 1024 * 1024 * 1024)
try:
volume_inv = vol_ops.create_volume_from_diskSize(volume_creation_option)
except Exception as e:
host_ops.update_kvm_host(host.uuid, 'username', "root")
host_ops.reconnect_host(host.uuid)
print e.message.encode("utf-8")
def error_cleanup():
global host, disconnect
if disconnect:
host_ops.update_kvm_host(host.uuid, 'username', "root")
host_ops.reconnect_host(host.uuid)
disconnect = False
def env_recover():
global host, disconnect
if disconnect:
host_ops.update_kvm_host(host.uuid, 'username', "root")
host_ops.reconnect_host(host.uuid)<|fim▁hole|><|fim▁end|> | disconnect = False |
<|file_name|>slope_histogram_cumulative_graph.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#/******************************************************************************
# * $Id$
# *
# * Project: GDAL Make Histogram and Cumulative graph from Tab delimited tab as
# generated by gdal_hist.py
# * Purpose: Take a gdal_hist.py output and create a histogram plot using matplotlib
# * Author: Trent Hare, [email protected]
# *
# ******************************************************************************
# * Public domain licenes (unlicense)
# *
# * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# * DEALINGS IN THE SOFTWARE.
# ****************************************************************************/
import sys
import os
import math
import numpy as np
import pandas as pd
from pandas.tools.plotting import table
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def usage():
print 'Usage: slope_histogram_cumulative_graph.py -name "InSight E1" slope_histogram_table.tab outfile.png'
print " This program is geared to run on a table as generated by gdal_hist.py"
print 'slope_histogram_cumulative_graph.py -name "E_Marg_CE 01" DEM_1m_E_Marg_CE_adir_1m_hist.xls DEM_1m_E_Marg_CE_adir_1m_hist.png'
sys.exit(0)
#set None for commandline options
name = ""
infile = None
outfile = None
# =============================================================================
# Parse command line arguments.
# =============================================================================
i = 1
while i < len(sys.argv):
arg = sys.argv[i]
if arg == '-name':
i = i + 1
name = sys.argv[i]
elif infile is None:
infile = arg
elif outfile is None:
outfile = arg
else:
Usage()
i = i + 1
if infile is None:
usage()
if not(os.path.isfile(infile)):
input = sys.argv[1]
print "filename %s does not exist." % (infile)
sys.exit(1)
#load table
df = pd.DataFrame.from_csv(infile, sep='\t', header=1)
#initialize figure
fig, ax1 = plt.subplots()<|fim▁hole|>
#not to reverse histogram before calculating 'approx' stats
#min = round(df.value.min(),2)
#max = round(df.value.max(),2)
#mean = round(df.value.mean(),2)
#stddev = round(df.value.std(),2)
#rms = round(math.sqrt((mean * mean) + (stddev * stddev)),2)
#statsDict = {'Min':min,'Max':max,'Mean':mean \
#,'StdDev':stddev,'RMS':rms}
#statsSeries = pd.Series(statsDict,name='stats')
#statsSeries.sort()
#t = table(ax1, statsSeries, \
#loc='lower right', colWidths=[0.1] * 2)
#t.set_fontsize(18)
#props = t.properties()
#cells = props['child_artists']
#for c in cells:
#c.set_height(0.05)
#Plot frequency histogram from input table
ax1.fill(df.value,df['count'],'gray')
#df.plot(ax1=ax1, kind='area', color='gray', legend=True)
ax1.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
ax1.get_yaxis().set_tick_params(direction='out')
#get min and max as found by pandas for plotting 'arrow' at X=15
#minY = round(df['count'].min(),0)
#maxY = round(df['count'].max(),0)
#grab existing ax1 axes
#ax = plt.axes()
#ax.arrow(15, minY, 0, maxY, head_width=0, head_length=0, fc='k', ec='k')
ax1.axvline(x=15, color='black', alpha=0.5)
#add cumulative plot on 'Y2' axis using save X axes
ax2 = ax1.twinx()
ax2.plot(df.value,df['cumulative'],'blue')
#df.plot(ax2=ax2, df.value,df['cumulative'],'blue')
ax2.get_yaxis().set_tick_params(direction='out')
#define labels
ax1.set_xlabel('Slope (degrees)')
ax1.set_ylabel('Count')
ax2.set_ylabel('Cumulative')
plt.suptitle(name + ' Slope Histogram and Cumulative Plot')
#save out PNG
plt.savefig(outfile)
print "Graph exported to %s" % (outfile)<|fim▁end|> |
#calculate unscaled values
#df.value = (df.value * 5) - 0.2
#df.ix[df.value < 0] = 0; df |
<|file_name|>gui.py<|end_file_name|><|fim▁begin|>import math
import os
import re
import itertools
from types import LambdaType
import pkg_resources
import numpy
from PyQt4 import QtGui, QtCore, QtWebKit
from PyQt4.QtCore import Qt, pyqtSignal as Signal
from PyQt4.QtGui import QCursor, QApplication
import Orange.data
from Orange.widgets.utils import getdeepattr
from Orange.data import ContinuousVariable, StringVariable, DiscreteVariable, Variable
from Orange.widgets.utils import vartype
from Orange.widgets.utils.constants import CONTROLLED_ATTRIBUTES, ATTRIBUTE_CONTROLLERS
from Orange.util import namegen
YesNo = NoYes = ("No", "Yes")
_enter_icon = None
__re_label = re.compile(r"(^|[^%])%\((?P<value>[a-zA-Z]\w*)\)")
OrangeUserRole = itertools.count(Qt.UserRole)
LAMBDA_NAME = namegen('_lambda_')
def resource_filename(path):
"""
Return a resource filename (package data) for path.
"""
return pkg_resources.resource_filename(__name__, path)
class TableWidget(QtGui.QTableWidget):
""" An easy to use, row-oriented table widget """
ROW_DATA_ROLE = QtCore.Qt.UserRole + 1
ITEM_DATA_ROLE = ROW_DATA_ROLE + 1
class TableWidgetNumericItem(QtGui.QTableWidgetItem):
"""TableWidgetItem that sorts numbers correctly!"""
def __lt__(self, other):
return (self.data(TableWidget.ITEM_DATA_ROLE) <
other.data(TableWidget.ITEM_DATA_ROLE))
def selectionChanged(self, selected:[QtGui.QItemSelectionRange], deselected:[QtGui.QItemSelectionRange]):
"""Override or monkey-patch this method to catch selection changes"""
super().selectionChanged(selected, deselected)
def __setattr__(self, attr, value):
"""
The following selectionChanged magic ensures selectionChanged
slot, when monkey-patched, always calls the super's selectionChanged
first (--> avoids Qt quirks), and the user needs not care about that.
"""
if attr == 'selectionChanged':
func = value
@QtCore.pyqtSlot(QtGui.QItemSelection, QtGui.QItemSelection)
def _f(selected, deselected):
super(self.__class__, self).selectionChanged(selected, deselected)
func(selected, deselected)
value = _f
self.__dict__[attr] = value
def _update_headers(func):
"""Decorator to update certain table features after method calls"""
def _f(self, *args, **kwargs):
func(self, *args, **kwargs)
if self.col_labels is not None:
self.setHorizontalHeaderLabels(self.col_labels)
if self.row_labels is not None:
self.setVerticalHeaderLabels(self.row_labels)
if self.stretch_last_section:
self.horizontalHeader().setStretchLastSection(True)
return _f
@_update_headers
def __init__(self,
parent=None,
col_labels=None,
row_labels=None,
stretch_last_section=True,
multi_selection=False,
select_rows=False):
"""
Parameters
----------
parent: QObject
Parent QObject. If parent has layout(), this widget is added to it.
col_labels: list of str
Labels or [] (sequential numbers) or None (no horizontal header)
row_label: list_of_str
Labels or [] (sequential numbers) or None (no vertical header)
stretch_last_section: bool
multi_selection: bool
Single selection if False
select_rows: bool
If True, select whole rows instead of individual cells.
"""
super().__init__(parent)
self._column_filter = {}
self.col_labels = col_labels
self.row_labels = row_labels
self.stretch_last_section = stretch_last_section
try: parent.layout().addWidget(self)
except (AttributeError, TypeError): pass
if col_labels is None:
self.horizontalHeader().setVisible(False)
if row_labels is None:
self.verticalHeader().setVisible(False)
if multi_selection:
self.setSelectionMode(self.MultiSelection)
if select_rows:
self.setSelectionBehavior(self.SelectRows)
self.setHorizontalScrollMode(self.ScrollPerPixel)
self.setVerticalScrollMode(self.ScrollPerPixel)
self.setEditTriggers(self.NoEditTriggers)
self.setAlternatingRowColors(True)
self.setShowGrid(False)
self.setSortingEnabled(True)
@_update_headers
def addRow(self, items:tuple, data=None):
"""
Appends iterable of `items` as the next row, optionally setting row
data to `data`. Each item of `items` can be a string or tuple
(item_name, item_data) if individual, cell-data is required.
"""
row_data = data
row = self.rowCount()
self.insertRow(row)
col_count = max(len(items), self.columnCount())
if col_count != self.columnCount():
self.setColumnCount(col_count)
for col, item_data in enumerate(items):
if isinstance(item_data, str):
name = item_data
elif hasattr(item_data, '__iter__') and len(item_data) == 2:
name, item_data = item_data
elif isinstance(item_data, float):
name = '{:.4f}'.format(item_data)
else:
name = str(item_data)
if isinstance(item_data, (float, int, numpy.number)):
item = self.TableWidgetNumericItem(name)
else:
item = QtGui.QTableWidgetItem(name)
item.setData(self.ITEM_DATA_ROLE, item_data)
if col in self._column_filter:
item = self._column_filter[col](item) or item
self.setItem(row, col, item)
self.resizeColumnsToContents()
self.resizeRowsToContents()
if row_data is not None:
self.setRowData(row, row_data)
def rowData(self, row:int):
return self.item(row, 0).data(self.ROW_DATA_ROLE)
def setRowData(self, row:int, data):
self.item(row, 0).setData(self.ROW_DATA_ROLE, data)
def setColumnFilter(self, item_filter_func, columns:int or list):
"""
Pass item(s) at column(s) through `item_filter_func` before
insertion. Useful for setting specific columns to bold or similar.
"""
try: iter(columns)
except TypeError: columns = [columns]
for i in columns:
self._column_filter[i] = item_filter_func
def clear(self):
super().clear()
self.setRowCount(0)
self.setColumnCount(0)
def selectFirstRow(self):
if self.rowCount() > 0:
self.selectRow(0)
def selectRowsWhere(self, col, value, n_hits=-1,
flags=QtCore.Qt.MatchExactly, _select=True):
"""
Select (also return) at most `n_hits` rows where column `col`
has value (``data()``) `value`.
"""
model = self.model()
matches = model.match(model.index(0, col),
self.ITEM_DATA_ROLE,
value,
n_hits,
flags)
model = self.selectionModel()
selection_flag = model.Select if _select else model.Deselect
for index in matches:
if _select ^ model.isSelected(index):
model.select(index, selection_flag | model.Rows)
return matches
def deselectRowsWhere(self, col, value, n_hits=-1,
flags=QtCore.Qt.MatchExactly):
"""
Deselect (also return) at most `n_hits` rows where column `col`
has value (``data()``) `value`.
"""
return self.selectRowsWhere(col, value, n_hits, flags, False)
class WebviewWidget(QtWebKit.QWebView):
"""WebKit window in a window"""
def __init__(self, parent=None, bridge=None, html=None, debug=None):
"""
Parameters
----------
parent: QObject
Parent QObject. If parent has layout(), this widget is added to it.
bridge: QObject
The "bridge" object exposed as ``window.pybridge`` in JavaScript.
Any bridge methods desired to be accessible from JS need to be
decorated ``@QtCore.pyqtSlot(<*args>, result=<type>)``.
html: str
HTML content to set in the webview.
debug: bool
If True, enable context menu and webkit inspector.
"""
super().__init__(parent)
self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding))
self._bridge = bridge
try: parent.layout().addWidget(self)
except (AttributeError, TypeError): pass
settings = self.settings()
settings.setAttribute(settings.LocalContentCanAccessFileUrls, True)
if debug is None:
import logging
debug = logging.getLogger().level <= logging.DEBUG
if debug:
settings.setAttribute(settings.DeveloperExtrasEnabled, True)
else:
self.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
if html:
self.setHtml(html)
def setContent(self, data, mimetype, url=''):
super().setContent(data, mimetype, QtCore.QUrl(url))
if self._bridge:
self.page().mainFrame().addToJavaScriptWindowObject('pybridge', self._bridge)
def setHtml(self, html, url=''):
self.setContent(html.encode('utf-8'), 'text/html', url)
def sizeHint(self):
return QtCore.QSize(600, 500)
def evalJS(self, javascript):
self.page().mainFrame().evaluateJavaScript(javascript)
class ControlledAttributesDict(dict):
def __init__(self, master):
super().__init__()
self.master = master
def __setitem__(self, key, value):
if key not in self:
dict.__setitem__(self, key, [value])
else:
dict.__getitem__(self, key).append(value)
set_controllers(self.master, key, self.master, "")
callbacks = lambda obj: getattr(obj, CONTROLLED_ATTRIBUTES, {})
subcontrollers = lambda obj: getattr(obj, ATTRIBUTE_CONTROLLERS, {})
def notify_changed(obj, name, value):
if name in callbacks(obj):
for callback in callbacks(obj)[name]:
callback(value)
return
for controller, prefix in list(subcontrollers(obj)):
if getdeepattr(controller, prefix, None) != obj:
del subcontrollers(obj)[(controller, prefix)]
continue
full_name = prefix + "." + name
if full_name in callbacks(controller):
for callback in callbacks(controller)[full_name]:
callback(value)
continue
prefix = full_name + "."
prefix_length = len(prefix)
for controlled in callbacks(controller):
if controlled[:prefix_length] == prefix:
set_controllers(value, controlled[prefix_length:], controller, full_name)
def set_controllers(obj, controlled_name, controller, prefix):
while obj:
if prefix:
if hasattr(obj, ATTRIBUTE_CONTROLLERS):
getattr(obj, ATTRIBUTE_CONTROLLERS)[(controller, prefix)] = True
else:
setattr(obj, ATTRIBUTE_CONTROLLERS, {(controller, prefix): True})
parts = controlled_name.split(".", 1)
if len(parts) < 2:
break
new_prefix, controlled_name = parts
obj = getattr(obj, new_prefix, None)
if prefix:
prefix += '.'
prefix += new_prefix
class OWComponent:
def __init__(self, widget):
setattr(self, CONTROLLED_ATTRIBUTES, ControlledAttributesDict(self))
if widget.settingsHandler:
widget.settingsHandler.initialize(self)
def __setattr__(self, key, value):
super().__setattr__(key, value)
notify_changed(self, key, value)
def miscellanea(control, box, parent,
addToLayout=True, stretch=0, sizePolicy=None, addSpace=False,
disabled=False, tooltip=None):
"""
Helper function that sets various properties of the widget using a common
set of arguments.
The function
- sets the `control`'s attribute `box`, if `box` is given and `control.box`
is not yet set,
- attaches a tool tip to the `control` if specified,
- disables the `control`, if `disabled` is set to `True`,
- adds the `box` to the `parent`'s layout unless `addToLayout` is set to
`False`; the stretch factor can be specified,
- adds the control into the box's layout if the box is given (regardless
of `addToLayout`!)
- sets the size policy for the box or the control, if the policy is given,
- adds space in the `parent`'s layout after the `box` if `addSpace` is set
and `addToLayout` is not `False`.
If `box` is the same as `parent` it is set to `None`; this is convenient
because of the way complex controls are inserted.
:param control: the control, e.g. a `QCheckBox`
:type control: PyQt4.QtGui.QWidget
:param box: the box into which the widget was inserted
:type box: PyQt4.QtGui.QWidget or None
:param parent: the parent into whose layout the box or the control will be
inserted
:type parent: PyQt4.QtGui.QWidget
:param addSpace: the amount of space to add after the widget
:type addSpace: bool or int
:param disabled: If set to `True`, the widget is initially disabled
:type disabled: bool
:param addToLayout: If set to `False` the widget is not added to the layout
:type addToLayout: bool
:param stretch: the stretch factor for this widget, used when adding to
the layout (default: 0)
:type stretch: int
:param tooltip: tooltip that is attached to the widget
:type tooltip: str or None
:param sizePolicy: the size policy for the box or the control
:type sizePolicy: PyQt4.QtQui.QSizePolicy
"""
if disabled:
# if disabled==False, do nothing; it can be already disabled
control.setDisabled(disabled)
if tooltip is not None:
control.setToolTip(tooltip)
if box is parent:
box = None
elif box and box is not control and not hasattr(control, "box"):
control.box = box
if box and box.layout() is not None and \
isinstance(control, QtGui.QWidget) and \
box.layout().indexOf(control) == -1:
box.layout().addWidget(control)
if sizePolicy is not None:
(box or control).setSizePolicy(sizePolicy)
if addToLayout and parent and parent.layout() is not None:
parent.layout().addWidget(box or control, stretch)
_addSpace(parent, addSpace)
def setLayout(widget, orientation):
"""
Set the layout of the widget according to orientation. Argument
`orientation` can be an instance of :obj:`~PyQt4.QtGui.QLayout`, in which
case is it used as it is. If `orientation` is `'vertical'` or `True`,
the layout is set to :obj:`~PyQt4.QtGui.QVBoxLayout`. If it is
`'horizontal'` or `False`, it is set to :obj:`~PyQt4.QtGui.QVBoxLayout`.
:param widget: the widget for which the layout is being set
:type widget: PyQt4.QtGui.QWidget
:param orientation: orientation for the layout
:type orientation: str or bool or PyQt4.QtGui.QLayout
"""
if isinstance(orientation, QtGui.QLayout):
widget.setLayout(orientation)
elif orientation == 'horizontal' or not orientation:
widget.setLayout(QtGui.QHBoxLayout())
else:
widget.setLayout(QtGui.QVBoxLayout())
def _enterButton(parent, control, placeholder=True):
"""
Utility function that returns a button with a symbol for "Enter" and
optionally a placeholder to show when the enter button is hidden. Both
are inserted into the parent's layout, if it has one. If placeholder is
constructed it is shown and the button is hidden.
The height of the button is the same as the height of the widget passed
as argument `control`.
:param parent: parent widget into which the button is inserted
:type parent: PyQt4.QtGui.QWidget
:param control: a widget for determining the height of the button
:type control: PyQt4.QtGui.QWidget
:param placeholder: a flag telling whether to construct a placeholder
(default: True)
:type placeholder: bool
:return: a tuple with a button and a place holder (or `None`)
:rtype: PyQt4.QtGui.QToolButton or tuple
"""
global _enter_icon
if not _enter_icon:
_enter_icon = QtGui.QIcon(
os.path.dirname(__file__) + "/icons/Dlg_enter.png")
button = QtGui.QToolButton(parent)
height = control.sizeHint().height()
button.setFixedSize(height, height)
button.setIcon(_enter_icon)
if parent.layout() is not None:
parent.layout().addWidget(button)
if placeholder:
button.hide()
holder = QtGui.QWidget(parent)
holder.setFixedSize(height, height)
if parent.layout() is not None:
parent.layout().addWidget(holder)
else:
holder = None
return button, holder
def _addSpace(widget, space):
"""
A helper function that adds space into the widget, if requested.
The function is called by functions that have the `addSpace` argument.
:param widget: Widget into which to insert the space
:type widget: PyQt4.QtGui.QWidget
:param space: Amount of space to insert. If False, the function does
nothing. If the argument is an `int`, the specified space is inserted.
Otherwise, the default space is inserted by calling a :obj:`separator`.
:type space: bool or int
"""
if space:
if type(space) == int: # distinguish between int and bool!
separator(widget, space, space)
else:
separator(widget)
def separator(widget, width=4, height=4):
"""
Add a separator of the given size into the widget.
:param widget: the widget into whose layout the separator is added
:type widget: PyQt4.QtGui.QWidget
:param width: width of the separator
:type width: int
:param height: height of the separator
:type height: int
:return: separator
:rtype: PyQt4.QtGui.QWidget
"""
sep = QtGui.QWidget(widget)
if widget.layout() is not None:
widget.layout().addWidget(sep)
sep.setFixedSize(width, height)
return sep
def rubber(widget):
"""
Insert a stretch 100 into the widget's layout
"""
widget.layout().addStretch(100)
def widgetBox(widget, box=None, orientation='vertical', margin=None, spacing=4,
**misc):
"""
Construct a box with vertical or horizontal layout, and optionally,
a border with an optional label.
If the widget has a frame, the space after the widget is added unless
explicitly disabled.
:param widget: the widget into which the box is inserted
:type widget: PyQt4.QtGui.QWidget or None
:param box: tells whether the widget has a border, and its label
:type box: int or str or None
:param orientation: orientation for the layout. If the argument is an
instance of :obj:`~PyQt4.QtGui.QLayout`, it is used as a layout. If
"horizontal" or false-ish, the layout is horizontal
(:obj:`~PyQt4.QtGui.QHBoxLayout`), otherwise vertical
(:obj:`~PyQt4.QtGui.QHBoxLayout`).
:type orientation: str, int or :obj:`PyQt4.QtGui.QLayout`
:param sizePolicy: The size policy for the widget (default: None)
:type sizePolicy: :obj:`~PyQt4.QtGui.QSizePolicy`
:param margin: The margin for the layout. Default is 7 if the widget has
a border, and 0 if not.
:type margin: int
:param spacing: Spacing within the layout (default: 4)
:type spacing: int
:return: Constructed box
:rtype: PyQt4.QtGui.QGroupBox or PyQt4.QtGui.QWidget
"""
if box:
b = QtGui.QGroupBox(widget)
if isinstance(box, str):
b.setTitle(" " + box.strip() + " ")
if margin is None:
margin = 7
else:
b = QtGui.QWidget(widget)
b.setContentsMargins(0, 0, 0, 0)
if margin is None:
margin = 0
setLayout(b, orientation)
b.layout().setSpacing(spacing)
b.layout().setMargin(margin)
misc.setdefault('addSpace', bool(box))
miscellanea(b, None, widget, **misc)
return b
def indentedBox(widget, sep=20, orientation="vertical", **misc):
"""
Creates an indented box. The function can also be used "on the fly"::
gui.checkBox(gui.indentedBox(box), self, "spam", "Enable spam")
To align the control with a check box, use :obj:`checkButtonOffsetHint`::
gui.hSlider(gui.indentedBox(self.interBox), self, "intervals")
:param widget: the widget into which the box is inserted
:type widget: PyQt4.QtGui.QWidget
:param sep: Indent size (default: 20)
:type sep: int
:param orientation: layout of the inserted box; see :obj:`widgetBox` for
details
:type orientation: str, int or PyQt4.QtGui.QLayout
:return: Constructed box
:rtype: PyQt4.QtGui.QGroupBox or PyQt4.QtGui.QWidget
"""
outer = widgetBox(widget, orientation=False, spacing=0)
separator(outer, sep, 0)
indented = widgetBox(outer, orientation=orientation)
miscellanea(indented, outer, widget, **misc)
return indented
def widgetLabel(widget, label="", labelWidth=None, **misc):
"""
Construct a simple, constant label.
:param widget: the widget into which the box is inserted
:type widget: PyQt4.QtGui.QWidget or None
:param label: The text of the label (default: None)
:type label: str
:param labelWidth: The width of the label (default: None)
:type labelWidth: int
:return: Constructed label
:rtype: PyQt4.QtGui.QLabel
"""
lbl = QtGui.QLabel(label, widget)
if labelWidth:
lbl.setFixedSize(labelWidth, lbl.sizeHint().height())
miscellanea(lbl, None, widget, **misc)
return lbl
def label(widget, master, label, labelWidth=None, box=None,
orientation="vertical", **misc):
"""
Construct a label that contains references to the master widget's
attributes; when their values change, the label is updated.
Argument :obj:`label` is a format string following Python's syntax
(see the corresponding Python documentation): the label's content is
rendered as `label % master.__dict__`. For instance, if the
:obj:`label` is given as "There are %(mm)i monkeys", the value of
`master.mm` (which must be an integer) will be inserted in place of
`%(mm)i`.
:param widget: the widget into which the box is inserted
:type widget: PyQt4.QtGui.QWidget or None
:param master: master widget
:type master: OWWidget or OWComponent
:param label: The text of the label, including attribute names
:type label: str
:param labelWidth: The width of the label (default: None)
:type labelWidth: int
:return: label
:rtype: PyQt4.QtGui.QLabel
"""
if box:
b = widgetBox(widget, box, orientation=None, addToLayout=False)
else:
b = widget
lbl = QtGui.QLabel("", b)
reprint = CallFrontLabel(lbl, label, master)
for mo in __re_label.finditer(label):
getattr(master, CONTROLLED_ATTRIBUTES)[mo.group("value")] = reprint
reprint()
if labelWidth:
lbl.setFixedSize(labelWidth, lbl.sizeHint().height())
miscellanea(lbl, b, widget, **misc)
return lbl
class SpinBoxWFocusOut(QtGui.QSpinBox):
"""
A class derived from QtGui.QSpinBox, which postpones the synchronization
of the control's value with the master's attribute until the user presses
Enter or clicks an icon that appears beside the spin box when the value
is changed.
The class overloads :obj:`onChange` event handler to show the commit button,
and :obj:`onEnter` to commit the change when enter is pressed.
.. attribute:: enterButton
A widget (usually an icon) that is shown when the value is changed.
.. attribute:: placeHolder
A placeholder which is shown when the button is hidden
.. attribute:: inSetValue
A flag that is set when the value is being changed through
:obj:`setValue` to prevent the programmatic changes from showing the
commit button.
"""
def __init__(self, minv, maxv, step, parent=None):
"""
Construct the object and set the range (`minv`, `maxv`) and the step.
:param minv: Minimal value
:type minv: int
:param maxv: Maximal value
:type maxv: int
:param step: Step
:type step: int
:param parent: Parent widget
:type parent: PyQt4.QtGui.QWidget
"""
super().__init__(parent)
self.setRange(minv, maxv)
self.setSingleStep(step)
self.inSetValue = False
self.enterButton = None
self.placeHolder = None
def onChange(self, _):
"""
Hides the place holder and shows the commit button unless
:obj:`inSetValue` is set.
"""
if not self.inSetValue:
self.placeHolder.hide()
self.enterButton.show()
def onEnter(self):
"""
If the commit button is visible, the overload event handler commits
the change by calling the appropriate callbacks. It also hides the
commit button and shows the placeHolder.
"""
if self.enterButton.isVisible():
self.enterButton.hide()
self.placeHolder.show()
if self.cback:
self.cback(int(str(self.text())))
if self.cfunc:
self.cfunc()
# doesn't work: it's probably LineEdit's focusOut that we should
# (but can't) catch
def focusOutEvent(self, *e):
"""
This handler was intended to catch the focus out event and reintepret
it as if enter was pressed. It does not work, though.
"""
super().focusOutEvent(*e)
if self.enterButton and self.enterButton.isVisible():
self.onEnter()
def setValue(self, value):
"""
Set the :obj:`inSetValue` flag and call the inherited method.
"""
self.inSetValue = True
super().setValue(value)
self.inSetValue = False
class DoubleSpinBoxWFocusOut(QtGui.QDoubleSpinBox):
"""
Same as :obj:`SpinBoxWFocusOut`, except that it is derived from
:obj:`~PyQt4.QtGui.QDoubleSpinBox`"""
def __init__(self, minv, maxv, step, parent):
super().__init__(parent)
self.setDecimals(math.ceil(-math.log10(step)))
self.setRange(minv, maxv)
self.setSingleStep(step)
self.inSetValue = False
self.enterButton = None
self.placeHolder = None
def onChange(self, _):
if not self.inSetValue:
self.placeHolder.hide()
self.enterButton.show()
def onEnter(self):
if self.enterButton.isVisible():
self.enterButton.hide()
self.placeHolder.show()
if self.cback:
self.cback(float(str(self.text()).replace(",", ".")))
if self.cfunc:
self.cfunc()
# doesn't work: it's probably LineEdit's focusOut that we should
# (and can't) catch
def focusOutEvent(self, *e):
super().focusOutEvent(*e)
if self.enterButton and self.enterButton.isVisible():
self.onEnter()
def setValue(self, value):
self.inSetValue = True
super().setValue(value)
self.inSetValue = False
def spin(widget, master, value, minv, maxv, step=1, box=None, label=None,
labelWidth=None, orientation=None, callback=None,
controlWidth=None, callbackOnReturn=False, checked=None,
checkCallback=None, posttext=None, disabled=False,
alignment=Qt.AlignLeft, keyboardTracking=True,
decimals=None, spinType=int, **misc):
"""
A spinbox with lots of bells and whistles, such as a checkbox and various
callbacks. It constructs a control of type :obj:`SpinBoxWFocusOut` or
:obj:`DoubleSpinBoxWFocusOut`.
:param widget: the widget into which the box is inserted
:type widget: PyQt4.QtGui.QWidget or None
:param master: master widget
:type master: OWWidget or OWComponent
:param value: the master's attribute with which the value is synchronized
:type value: str
:param minv: minimal value
:type minv: int
:param maxv: maximal value
:type maxv: int
:param step: step (default: 1)
:type step: int
:param box: tells whether the widget has a border, and its label
:type box: int or str or None
:param label: label that is put in above or to the left of the spin box
:type label: str
:param labelWidth: optional label width (default: None)
:type labelWidth: int
:param orientation: tells whether to put the label above (`"vertical"` or
`True`) or to the left (`"horizontal"` or `False`)
:type orientation: int or bool or str
:param callback: a function that is called when the value is entered; if
:obj:`callbackOnReturn` is `True`, the function is called when the
user commits the value by pressing Enter or clicking the icon
:type callback: function
:param controlWidth: the width of the spin box
:type controlWidth: int
:param callbackOnReturn: if `True`, the spin box has an associated icon
that must be clicked to confirm the value (default: False)
:type callbackOnReturn: bool
:param checked: if not None, a check box is put in front of the spin box;
when unchecked, the spin box is disabled. Argument `checked` gives the
name of the master's attribute given whose value is synchronized with
the check box's state (default: None).
:type checked: str
:param checkCallback: a callback function that is called when the check
box's state is changed
:type checkCallback: function
:param posttext: a text that is put to the right of the spin box
:type posttext: str
:param alignment: alignment of the spin box (e.g. `QtCore.Qt.AlignLeft`)
:type alignment: PyQt4.QtCore.Qt.Alignment
:param keyboardTracking: If `True`, the valueChanged signal is emitted
when the user is typing (default: True)
:type keyboardTracking: bool
:param spinType: determines whether to use QSpinBox (int) or
QDoubleSpinBox (float)
:type spinType: type
:param decimals: number of decimals (if `spinType` is `float`)
:type decimals: int
:return: Tuple `(spin box, check box) if `checked` is `True`, otherwise
the spin box
:rtype: tuple or gui.SpinBoxWFocusOut
"""
# b is the outermost box or the widget if there are no boxes;
# b is the widget that is inserted into the layout
# bi is the box that contains the control or the checkbox and the control;
# bi can be the widget itself, if there are no boxes
# cbox is the checkbox (or None)
# sbox is the spinbox itself
if box or label and not checked:
b = widgetBox(widget, box, orientation, addToLayout=False)
hasHBox = orientation == 'horizontal' or not orientation
else:
b = widget
hasHBox = False
if not hasHBox and (checked or callback and callbackOnReturn or posttext):
bi = widgetBox(b, orientation=0, addToLayout=False)
else:
bi = b
cbox = None
if checked is not None:
cbox = checkBox(bi, master, checked, label, labelWidth=labelWidth,
callback=checkCallback)
elif label:
b.label = widgetLabel(b, label, labelWidth)
if posttext:
widgetLabel(bi, posttext)
isDouble = spinType == float
sbox = bi.control = \
(SpinBoxWFocusOut, DoubleSpinBoxWFocusOut)[isDouble](minv, maxv,
step, bi)
if bi is not widget:
bi.setDisabled(disabled)
else:
sbox.setDisabled(disabled)
if decimals is not None:
sbox.setDecimals(decimals)
sbox.setAlignment(alignment)
sbox.setKeyboardTracking(keyboardTracking)
if controlWidth:
sbox.setFixedWidth(controlWidth)
if value:
sbox.setValue(getdeepattr(master, value))
cfront, sbox.cback, sbox.cfunc = connectControl(
master, value, callback,
not (callback and callbackOnReturn) and
sbox.valueChanged[(int, float)[isDouble]],
(CallFrontSpin, CallFrontDoubleSpin)[isDouble](sbox))
if checked:
cbox.disables = [sbox]
cbox.makeConsistent()
if callback and callbackOnReturn:
sbox.enterButton, sbox.placeHolder = _enterButton(bi, sbox)
sbox.valueChanged[str].connect(sbox.onChange)
sbox.editingFinished.connect(sbox.onEnter)
sbox.enterButton.clicked.connect(sbox.onEnter)
if hasattr(sbox, "upButton"):
sbox.upButton().clicked.connect(
lambda c=sbox.editor(): c.setFocus())
sbox.downButton().clicked.connect(
lambda c=sbox.editor(): c.setFocus())
miscellanea(sbox, b if b is not widget else bi, widget, **misc)
if checked:
if isDouble and b == widget:
# TODO Backward compatilibity; try to find and eliminate
sbox.control = b.control
return sbox
return cbox, sbox
else:
return sbox
# noinspection PyTypeChecker
def doubleSpin(widget, master, value, minv, maxv, step=1, box=None, label=None,
labelWidth=None, orientation=None, callback=None,
controlWidth=None, callbackOnReturn=False, checked=None,
checkCallback=None, posttext=None,
alignment=Qt.AlignLeft, keyboardTracking=True,
decimals=None, **misc):
"""
Backward compatilibity function: calls :obj:`spin` with `spinType=float`.
"""
return spin(widget, master, value, minv, maxv, step, box=box, label=label,
labelWidth=labelWidth, orientation=orientation,
callback=callback, controlWidth=controlWidth,
callbackOnReturn=callbackOnReturn, checked=checked,
checkCallback=checkCallback, posttext=posttext,
alignment=alignment, keyboardTracking=keyboardTracking,
decimals=decimals, spinType=float, **misc)
def checkBox(widget, master, value, label, box=None,
callback=None, getwidget=False, id_=None, labelWidth=None,
disables=None, **misc):
"""
A simple checkbox.
:param widget: the widget into which the box is inserted
:type widget: PyQt4.QtGui.QWidget or None
:param master: master widget
:type master: OWWidget or OWComponent
:param value: the master's attribute with which the value is synchronized
:type value: str
:param label: label
:type label: str
:param box: tells whether the widget has a border, and its label
:type box: int or str or None
:param callback: a function that is called when the check box state is
changed
:type callback: function
:param getwidget: If set `True`, the callback function will get a keyword
argument `widget` referencing the check box
:type getwidget: bool
:param id_: If present, the callback function will get a keyword argument
`id` with this value
:type id_: any
:param labelWidth: the width of the label
:type labelWidth: int
:param disables: a list of widgets that are disabled if the check box is
unchecked
:type disables: list or PyQt4.QtGui.QWidget or None
:return: constructed check box; if is is placed within a box, the box is
return in the attribute `box`
:rtype: PyQt4.QtGui.QCheckBox
"""
if box:
b = widgetBox(widget, box, orientation=None, addToLayout=False)
else:
b = widget
cbox = QtGui.QCheckBox(label, b)
if labelWidth:
cbox.setFixedSize(labelWidth, cbox.sizeHint().height())
cbox.setChecked(getdeepattr(master, value))
connectControl(master, value, None, cbox.toggled[bool],
CallFrontCheckBox(cbox),
cfunc=callback and FunctionCallback(
master, callback, widget=cbox, getwidget=getwidget,
id=id_))
if isinstance(disables, QtGui.QWidget):
disables = [disables]
cbox.disables = disables or []
cbox.makeConsistent = Disabler(cbox, master, value)
cbox.toggled[bool].connect(cbox.makeConsistent)
cbox.makeConsistent(value)
miscellanea(cbox, b, widget, **misc)
return cbox
class LineEditWFocusOut(QtGui.QLineEdit):
"""
A class derived from QtGui.QLineEdit, which postpones the synchronization
of the control's value with the master's attribute until the user leaves
the line edit, presses Enter or clicks an icon that appears beside the
line edit when the value is changed.
The class also allows specifying a callback function for focus-in event.
.. attribute:: enterButton
A widget (usually an icon) that is shown when the value is changed.
.. attribute:: placeHolder
A placeholder which is shown when the button is hidden
.. attribute:: inSetValue
A flag that is set when the value is being changed through
:obj:`setValue` to prevent the programmatic changes from showing the
commit button.
.. attribute:: callback
Callback that is called when the change is confirmed
.. attribute:: focusInCallback
Callback that is called on the focus-in event
"""
def __init__(self, parent, callback, focusInCallback=None,
placeholder=False):
super().__init__(parent)
if parent.layout() is not None:
parent.layout().addWidget(self)
self.callback = callback
self.focusInCallback = focusInCallback
self.enterButton, self.placeHolder = \
_enterButton(parent, self, placeholder)
self.enterButton.clicked.connect(self.returnPressedHandler)
self.textChanged[str].connect(self.markChanged)
self.returnPressed.connect(self.returnPressedHandler)
def markChanged(self, *_):
if self.placeHolder:
self.placeHolder.hide()
self.enterButton.show()
def markUnchanged(self, *_):
self.enterButton.hide()
if self.placeHolder:
self.placeHolder.show()
def returnPressedHandler(self):
if self.enterButton.isVisible():
self.markUnchanged()
if hasattr(self, "cback") and self.cback:
self.cback(self.text())
if self.callback:
self.callback()
def setText(self, t):
super().setText(t)
if self.enterButton:
self.markUnchanged()
def focusOutEvent(self, *e):
super().focusOutEvent(*e)
self.returnPressedHandler()
def focusInEvent(self, *e):
if self.focusInCallback:
self.focusInCallback()
return super().focusInEvent(*e)
def lineEdit(widget, master, value, label=None, labelWidth=None,
orientation='vertical', box=None, callback=None,
valueType=str, validator=None, controlWidth=None,
callbackOnType=False, focusInCallback=None,
enterPlaceholder=False, **misc):
"""
Insert a line edit.
:param widget: the widget into which the box is inserted
:type widget: PyQt4.QtGui.QWidget or None
:param master: master widget
:type master: OWWidget or OWComponent
:param value: the master's attribute with which the value is synchronized
:type value: str
:param label: label
:type label: str
:param labelWidth: the width of the label
:type labelWidth: int
:param orientation: tells whether to put the label above (`"vertical"` or
`True`) or to the left (`"horizontal"` or `False`)
:type orientation: int or bool or str
:param box: tells whether the widget has a border, and its label
:type box: int or str or None
:param callback: a function that is called when the check box state is
changed
:type callback: function
:param valueType: the type into which the entered string is converted
when synchronizing to `value`
:type valueType: type
:param validator: the validator for the input
:type validator: PyQt4.QtGui.QValidator
:param controlWidth: the width of the line edit
:type controlWidth: int
:param callbackOnType: if set to `True`, the callback is called at each
key press (default: `False`)
:type callbackOnType: bool
:param focusInCallback: a function that is called when the line edit
receives focus
:type focusInCallback: function
:param enterPlaceholder: if set to `True`, space of appropriate width is
left empty to the right for the icon that shows that the value is
changed but has not been committed yet
:type enterPlaceholder: bool
:rtype: PyQt4.QtGui.QLineEdit or a box
"""
if box or label:
b = widgetBox(widget, box, orientation, addToLayout=False)
if label is not None:
widgetLabel(b, label, labelWidth)
hasHBox = orientation == 'horizontal' or not orientation
else:
b = widget
hasHBox = False
baseClass = misc.pop("baseClass", None)
if baseClass:
ledit = baseClass(b)
ledit.enterButton = None
if b is not widget:
b.layout().addWidget(ledit)
elif focusInCallback or callback and not callbackOnType:
if not hasHBox:
outer = widgetBox(b, "", 0, addToLayout=(b is not widget))
else:
outer = b
ledit = LineEditWFocusOut(outer, callback, focusInCallback,
enterPlaceholder)
else:
ledit = QtGui.QLineEdit(b)
ledit.enterButton = None
if b is not widget:
b.layout().addWidget(ledit)
if value:
ledit.setText(str(getdeepattr(master, value)))
if controlWidth:
ledit.setFixedWidth(controlWidth)
if validator:
ledit.setValidator(validator)
if value:
ledit.cback = connectControl(
master, value,
callbackOnType and callback, ledit.textChanged[str],
CallFrontLineEdit(ledit), fvcb=value and valueType)[1]
miscellanea(ledit, b, widget, **misc)
return ledit
def button(widget, master, label, callback=None, width=None, height=None,
toggleButton=False, value="", default=False, autoDefault=True,
buttonType=QtGui.QPushButton, **misc):
"""
Insert a button (QPushButton, by default)
:param widget: the widget into which the button is inserted
:type widget: PyQt4.QtGui.QWidget or None
:param master: master widget
:type master: OWWidget or OWComponent
:param label: label
:type label: str
:param callback: a function that is called when the button is pressed
:type callback: function
:param width: the width of the button
:type width: int
:param height: the height of the button
:type height: int
:param toggleButton: if set to `True`, the button is checkable, but it is
not synchronized with any attribute unless the `value` is given
:type toggleButton: bool
:param value: the master's attribute with which the value is synchronized
(the argument is optional; if present, it makes the button "checkable",
even if `toggleButton` is not set)
:type value: str
:param default: if `True` it makes the button the default button; this is
the button that is activated when the user presses Enter unless some
auto default button has current focus
:type default: bool
:param autoDefault: all buttons are auto default: they are activated if
they have focus (or are the next in the focus chain) when the user
presses enter. By setting `autoDefault` to `False`, the button is not
activated on pressing Return.
:type autoDefault: bool
:param buttonType: the button type (default: `QPushButton`)
:type buttonType: PyQt4.QtGui.QAbstractButton
:rtype: PyQt4.QtGui.QAbstractButton
"""
button = buttonType(widget)
if label:
button.setText(label)
if width:
button.setFixedWidth(width)
if height:
button.setFixedHeight(height)
if toggleButton or value:
button.setCheckable(True)
if buttonType == QtGui.QPushButton:
button.setDefault(default)
button.setAutoDefault(autoDefault)
if value:
button.setChecked(getdeepattr(master, value))
connectControl(
master, value, None, button.toggled[bool],
CallFrontButton(button),
cfunc=callback and FunctionCallback(master, callback,
widget=button))
elif callback:
button.clicked.connect(callback)
miscellanea(button, None, widget, **misc)
return button
def toolButton(widget, master, label="", callback=None,
width=None, height=None, tooltip=None):
"""
Insert a tool button. Calls :obj:`button`
:param widget: the widget into which the button is inserted
:type widget: PyQt4.QtGui.QWidget or None
:param master: master widget
:type master: OWWidget or OWComponent
:param label: label
:type label: str
:param callback: a function that is called when the button is pressed
:type callback: function
:param width: the width of the button
:type width: int
:param height: the height of the button
:type height: int
:rtype: PyQt4.QtGui.QToolButton
"""
return button(widget, master, label, callback, width, height,
buttonType=QtGui.QToolButton, tooltip=tooltip)
def createAttributePixmap(char, background=Qt.black, color=Qt.white):
"""
Create a QIcon with a given character. The icon is 13 pixels high and wide.
:param char: The character that is printed in the icon
:type char: str
:param background: the background color (default: black)
:type background: PyQt4.QtGui.QColor
:param color: the character color (default: white)
:type color: PyQt4.QtGui.QColor
:rtype: PyQt4.QtGui.QIcon
"""
pixmap = QtGui.QPixmap(13, 13)
pixmap.fill(QtGui.QColor(0, 0, 0, 0))
painter = QtGui.QPainter()
painter.begin(pixmap)
painter.setRenderHints(painter.Antialiasing | painter.TextAntialiasing |
painter.SmoothPixmapTransform)
painter.setPen(background)
painter.setBrush(background)
rect = QtCore.QRectF(0, 0, 13, 13)
painter.drawRoundedRect(rect, 4, 4)
painter.setPen(color)
painter.drawText(2, 11, char)
painter.end()
return QtGui.QIcon(pixmap)
class __AttributeIconDict(dict):
def __getitem__(self, key):
if not self:
for tpe, char, col in ((vartype(ContinuousVariable()),
"C", (202, 0, 32)),
(vartype(DiscreteVariable()),
"D", (26, 150, 65)),
(vartype(StringVariable()),
"S", (0, 0, 0)),
(-1, "?", (128, 128, 128))):
self[tpe] = createAttributePixmap(char, QtGui.QColor(*col))
if key not in self:
key = vartype(key) if isinstance(key, Variable) else -1
return super().__getitem__(key)
#: A dict that returns icons for different attribute types. The dict is
#: constructed on first use since icons cannot be created before initializing
#: the application.
#:
#: Accepted keys are variable type codes and instances
#: of :obj:`Orange.data.variable`: `attributeIconDict[var]` will give the
#: appropriate icon for variable `var` or a question mark if the type is not
#: recognized
attributeIconDict = __AttributeIconDict()
def attributeItem(var):
"""
Construct a pair (icon, name) for inserting a variable into a combo or
list box
:param var: variable
:type var: Orange.data.Variable
:rtype: tuple with PyQt4.QtGui.QIcon and str
"""
return attributeIconDict[var], var.name
def listBox(widget, master, value=None, labels=None, box=None, callback=None,
selectionMode=QtGui.QListWidget.SingleSelection,
enableDragDrop=False, dragDropCallback=None,
dataValidityCallback=None, sizeHint=None, **misc):
"""
Insert a list box.
The value with which the box's value synchronizes (`master.<value>`)
is a list of indices of selected items.
:param widget: the widget into which the box is inserted
:type widget: PyQt4.QtGui.QWidget or None
:param master: master widget
:type master: OWWidget or OWComponent
:param value: the name of the master's attribute with which the value is
synchronized (list of ints - indices of selected items)
:type value: str
:param labels: the name of the master's attribute with the list of items
(as strings or tuples with icon and string)
:type labels: str
:param box: tells whether the widget has a border, and its label
:type box: int or str or None
:param callback: a function that is called when the selection state is
changed
:type callback: function
:param selectionMode: selection mode - single, multiple etc
:type selectionMode: PyQt4.QtGui.QAbstractItemView.SelectionMode
:param enableDragDrop: flag telling whether drag and drop is available
:type enableDragDrop: bool
:param dragDropCallback: callback function on drop event
:type dragDropCallback: function
:param dataValidityCallback: function that check the validity on enter
and move event; it should return either `ev.accept()` or `ev.ignore()`.
:type dataValidityCallback: function
:param sizeHint: size hint
:type sizeHint: PyQt4.QtGui.QSize
:rtype: OrangeListBox
"""
if box:
bg = widgetBox(widget, box,
orientation="horizontal", addToLayout=False)
else:
bg = widget
lb = OrangeListBox(master, enableDragDrop, dragDropCallback,
dataValidityCallback, sizeHint, bg)
lb.setSelectionMode(selectionMode)
lb.ogValue = value
lb.ogLabels = labels
lb.ogMaster = master
if value is not None:
clist = getdeepattr(master, value)
if not isinstance(clist, ControlledList):
clist = ControlledList(clist, lb)
master.__setattr__(value, clist)
if labels is not None:
setattr(master, labels, getdeepattr(master, labels))
if hasattr(master, CONTROLLED_ATTRIBUTES):
getattr(master, CONTROLLED_ATTRIBUTES)[labels] = CallFrontListBoxLabels(lb)
if value is not None:
setattr(master, value, getdeepattr(master, value))
connectControl(master, value, callback, lb.itemSelectionChanged,
CallFrontListBox(lb), CallBackListBox(lb, master))
misc.setdefault('addSpace', True)
miscellanea(lb, bg, widget, **misc)
return lb
# btnLabels is a list of either char strings or pixmaps
def radioButtons(widget, master, value, btnLabels=(), tooltips=None,
box=None, label=None, orientation='vertical',
callback=None, **misc):
"""
Construct a button group and add radio buttons, if they are given.
The value with which the buttons synchronize is the index of selected
button.
:param widget: the widget into which the box is inserted
:type widget: PyQt4.QtGui.QWidget or None
:param master: master widget
:type master: OWWidget or OWComponent
:param value: the master's attribute with which the value is synchronized
:type value: str
:param btnLabels: a list of labels or icons for radio buttons
:type btnLabels: list of str or pixmaps
:param tooltips: a list of tool tips of the same length as btnLabels
:type tooltips: list of str
:param box: tells whether the widget has a border, and its label
:type box: int or str or None
:param label: a label that is inserted into the box
:type label: str
:param callback: a function that is called when the selection is changed
:type callback: function
:param orientation: orientation of the layout in the box
:type orientation: int or str or QLayout
:rtype: PyQt4.QtQui.QButtonGroup
"""
bg = widgetBox(widget, box, orientation, addToLayout=False)
if not label is None:
widgetLabel(bg, label)
rb = QtGui.QButtonGroup(bg)
if bg is not widget:
bg.group = rb
bg.buttons = []
bg.ogValue = value
bg.ogMaster = master<|fim▁hole|> appendRadioButton(bg, lab, tooltip=tooltips and tooltips[i])
connectControl(master, value, callback, bg.group.buttonClicked[int],
CallFrontRadioButtons(bg), CallBackRadioButton(bg, master))
misc.setdefault('addSpace', bool(box))
miscellanea(bg.group, bg, widget, **misc)
return bg
radioButtonsInBox = radioButtons
def appendRadioButton(group, label, insertInto=None,
disabled=False, tooltip=None, sizePolicy=None,
addToLayout=True, stretch=0, addSpace=False):
"""
Construct a radio button and add it to the group. The group must be
constructed with :obj:`radioButtonsInBox` since it adds additional
attributes need for the call backs.
The radio button is inserted into `insertInto` or, if omitted, into the
button group. This is useful for more complex groups, like those that have
radio buttons in several groups, divided by labels and inside indented
boxes.
:param group: the button group
:type group: PyQt4.QtCore.QButtonGroup
:param label: string label or a pixmap for the button
:type label: str or PyQt4.QtGui.QPixmap
:param insertInto: the widget into which the radio button is inserted
:type insertInto: PyQt4.QtGui.QWidget
:rtype: PyQt4.QtGui.QRadioButton
"""
i = len(group.buttons)
if isinstance(label, str):
w = QtGui.QRadioButton(label)
else:
w = QtGui.QRadioButton(str(i))
w.setIcon(QtGui.QIcon(label))
if not hasattr(group, "buttons"):
group.buttons = []
group.buttons.append(w)
group.group.addButton(w)
w.setChecked(getdeepattr(group.ogMaster, group.ogValue) == i)
# miscellanea for this case is weird, so we do it here
if disabled:
w.setDisabled(disabled)
if tooltip is not None:
w.setToolTip(tooltip)
if sizePolicy:
w.setSizePolicy(sizePolicy)
if addToLayout:
dest = insertInto or group
dest.layout().addWidget(w, stretch)
_addSpace(dest, addSpace)
return w
def hSlider(widget, master, value, box=None, minValue=0, maxValue=10, step=1,
callback=None, label=None, labelFormat=" %d", ticks=False,
divideFactor=1.0, vertical=False, createLabel=True, width=None,
intOnly=True, **misc):
"""
Construct a slider.
:param widget: the widget into which the box is inserted
:type widget: PyQt4.QtGui.QWidget or None
:param master: master widget
:type master: OWWidget or OWComponent
:param value: the master's attribute with which the value is synchronized
:type value: str
:param box: tells whether the widget has a border, and its label
:type box: int or str or None
:param label: a label that is inserted into the box
:type label: str
:param callback: a function that is called when the value is changed
:type callback: function
:param minValue: minimal value
:type minValue: int or float
:param maxValue: maximal value
:type maxValue: int or float
:param step: step size
:type step: int or float
:param labelFormat: the label format; default is `" %d"`
:type labelFormat: str
:param ticks: if set to `True`, ticks are added below the slider
:type ticks: bool
:param divideFactor: a factor with which the displayed value is divided
:type divideFactor: float
:param vertical: if set to `True`, the slider is vertical
:type vertical: bool
:param createLabel: unless set to `False`, labels for minimal, maximal
and the current value are added to the widget
:type createLabel: bool
:param width: the width of the slider
:type width: int
:param intOnly: if `True`, the slider value is integer (the slider is
of type :obj:`PyQt4.QtGui.QSlider`) otherwise it is float
(:obj:`FloatSlider`, derived in turn from :obj:`PyQt4.QtQui.QSlider`).
:type intOnly: bool
:rtype: :obj:`PyQt4.QtGui.QSlider` or :obj:`FloatSlider`
"""
sliderBox = widgetBox(widget, box, orientation="horizontal",
addToLayout=False)
if label:
widgetLabel(sliderBox, label)
sliderOrient = Qt.Vertical if vertical else Qt.Horizontal
if intOnly:
slider = QtGui.QSlider(sliderOrient, sliderBox)
slider.setRange(minValue, maxValue)
if step:
slider.setSingleStep(step)
slider.setPageStep(step)
slider.setTickInterval(step)
signal = slider.valueChanged[int]
else:
slider = FloatSlider(sliderOrient, minValue, maxValue, step)
signal = slider.valueChangedFloat[float]
sliderBox.layout().addWidget(slider)
slider.setValue(getdeepattr(master, value))
if width:
slider.setFixedWidth(width)
if ticks:
slider.setTickPosition(QtGui.QSlider.TicksBelow)
slider.setTickInterval(ticks)
if createLabel:
label = QtGui.QLabel(sliderBox)
sliderBox.layout().addWidget(label)
label.setText(labelFormat % minValue)
width1 = label.sizeHint().width()
label.setText(labelFormat % maxValue)
width2 = label.sizeHint().width()
label.setFixedSize(max(width1, width2), label.sizeHint().height())
txt = labelFormat % (getdeepattr(master, value) / divideFactor)
label.setText(txt)
label.setLbl = lambda x: \
label.setText(labelFormat % (x / divideFactor))
signal.connect(label.setLbl)
connectControl(master, value, callback, signal, CallFrontHSlider(slider))
miscellanea(slider, sliderBox, widget, **misc)
return slider
def labeledSlider(widget, master, value, box=None,
label=None, labels=(), labelFormat=" %d", ticks=False,
callback=None, vertical=False, width=None, **misc):
"""
Construct a slider with labels instead of numbers.
:param widget: the widget into which the box is inserted
:type widget: PyQt4.QtGui.QWidget or None
:param master: master widget
:type master: OWWidget or OWComponent
:param value: the master's attribute with which the value is synchronized
:type value: str
:param box: tells whether the widget has a border, and its label
:type box: int or str or None
:param label: a label that is inserted into the box
:type label: str
:param labels: labels shown at different slider positions
:type labels: tuple of str
:param callback: a function that is called when the value is changed
:type callback: function
:param ticks: if set to `True`, ticks are added below the slider
:type ticks: bool
:param vertical: if set to `True`, the slider is vertical
:type vertical: bool
:param width: the width of the slider
:type width: int
:rtype: :obj:`PyQt4.QtGui.QSlider`
"""
sliderBox = widgetBox(widget, box, orientation="horizontal",
addToLayout=False)
if label:
widgetLabel(sliderBox, label)
sliderOrient = Qt.Vertical if vertical else Qt.Horizontal
slider = QtGui.QSlider(sliderOrient, sliderBox)
slider.ogValue = value
slider.setRange(0, len(labels) - 1)
slider.setSingleStep(1)
slider.setPageStep(1)
slider.setTickInterval(1)
sliderBox.layout().addWidget(slider)
slider.setValue(labels.index(getdeepattr(master, value)))
if width:
slider.setFixedWidth(width)
if ticks:
slider.setTickPosition(QtGui.QSlider.TicksBelow)
slider.setTickInterval(ticks)
max_label_size = 0
slider.value_label = value_label = QtGui.QLabel(sliderBox)
value_label.setAlignment(Qt.AlignRight)
sliderBox.layout().addWidget(value_label)
for lb in labels:
value_label.setText(labelFormat % lb)
max_label_size = max(max_label_size, value_label.sizeHint().width())
value_label.setFixedSize(max_label_size, value_label.sizeHint().height())
value_label.setText(getdeepattr(master, value))
if isinstance(labelFormat, str):
value_label.set_label = lambda x: \
value_label.setText(labelFormat % x)
else:
value_label.set_label = lambda x: value_label.setText(labelFormat(x))
slider.valueChanged[int].connect(value_label.set_label)
connectControl(master, value, callback, slider.valueChanged[int],
CallFrontLabeledSlider(slider, labels),
CallBackLabeledSlider(slider, master, labels))
miscellanea(slider, sliderBox, widget, **misc)
return slider
def valueSlider(widget, master, value, box=None, label=None,
values=(), labelFormat=" %d", ticks=False,
callback=None, vertical=False, width=None, **misc):
"""
Construct a slider with different values.
:param widget: the widget into which the box is inserted
:type widget: PyQt4.QtGui.QWidget or None
:param master: master widget
:type master: OWWidget or OWComponent
:param value: the master's attribute with which the value is synchronized
:type value: str
:param box: tells whether the widget has a border, and its label
:type box: int or str or None
:param label: a label that is inserted into the box
:type label: str
:param values: values at different slider positions
:type values: list of int
:param labelFormat: label format; default is `" %d"`; can also be a function
:type labelFormat: str or func
:param callback: a function that is called when the value is changed
:type callback: function
:param ticks: if set to `True`, ticks are added below the slider
:type ticks: bool
:param vertical: if set to `True`, the slider is vertical
:type vertical: bool
:param width: the width of the slider
:type width: int
:rtype: :obj:`PyQt4.QtGui.QSlider`
"""
if isinstance(labelFormat, str):
labelFormat = lambda x, f=labelFormat: f(x)
sliderBox = widgetBox(widget, box, orientation="horizontal",
addToLayout=False)
if label:
widgetLabel(sliderBox, label)
slider_orient = Qt.Vertical if vertical else Qt.Horizontal
slider = QtGui.QSlider(slider_orient, sliderBox)
slider.ogValue = value
slider.setRange(0, len(values) - 1)
slider.setSingleStep(1)
slider.setPageStep(1)
slider.setTickInterval(1)
sliderBox.layout().addWidget(slider)
slider.setValue(values.index(getdeepattr(master, value)))
if width:
slider.setFixedWidth(width)
if ticks:
slider.setTickPosition(QtGui.QSlider.TicksBelow)
slider.setTickInterval(ticks)
max_label_size = 0
slider.value_label = value_label = QtGui.QLabel(sliderBox)
value_label.setAlignment(Qt.AlignRight)
sliderBox.layout().addWidget(value_label)
for lb in values:
value_label.setText(labelFormat(lb))
max_label_size = max(max_label_size, value_label.sizeHint().width())
value_label.setFixedSize(max_label_size, value_label.sizeHint().height())
value_label.setText(labelFormat(getdeepattr(master, value)))
value_label.set_label = lambda x: value_label.setText(labelFormat(values[x]))
slider.valueChanged[int].connect(value_label.set_label)
connectControl(master, value, callback, slider.valueChanged[int],
CallFrontLabeledSlider(slider, values),
CallBackLabeledSlider(slider, master, values))
miscellanea(slider, sliderBox, widget, **misc)
return slider
class OrangeComboBox(QtGui.QComboBox):
"""
A QtGui.QComboBox subclass extened to support bounded contents width hint.
"""
def __init__(self, parent=None, maximumContentsLength=-1, **kwargs):
super().__init__(parent, **kwargs)
self.__maximumContentsLength = maximumContentsLength
def setMaximumContentsLength(self, length):
"""
Set the maximum contents length hint.
The hint specifies the upper bound on the `sizeHint` and
`minimumSizeHint` width specified in character length.
Set to 0 or negative value to disable.
.. note::
This property does not affect the widget's `maximumSize`.
The widget can still grow depending in it's sizePolicy.
Parameters
----------
lenght : int
Maximum contents length hint.
"""
if self.__maximumContentsLength != length:
self.__maximumContentsLength = length
self.updateGeometry()
def maximumContentsLength(self):
"""
Return the maximum contents length hint.
"""
return self.__maximumContentsLength
def sizeHint(self):
# reimplemented
sh = super().sizeHint()
if self.__maximumContentsLength > 0:
width = (self.fontMetrics().width("X") * self.__maximumContentsLength
+ self.iconSize().width() + 4)
sh = sh.boundedTo(QtCore.QSize(width, sh.height()))
return sh
def minimumSizeHint(self):
# reimplemented
sh = super().minimumSizeHint()
if self.__maximumContentsLength > 0:
width = (self.fontMetrics().width("X") * self.__maximumContentsLength
+ self.iconSize().width() + 4)
sh = sh.boundedTo(QtCore.QSize(width, sh.height()))
return sh
# TODO comboBox looks overly complicated:
# - is the argument control2attributeDict needed? doesn't emptyString do the
# job?
# - can valueType be anything else than str?
# - sendSelectedValue is not a great name
def comboBox(widget, master, value, box=None, label=None, labelWidth=None,
orientation='vertical', items=(), callback=None,
sendSelectedValue=False, valueType=str,
control2attributeDict=None, emptyString=None, editable=False,
contentsLength=None, maximumContentsLength=25,
**misc):
"""
Construct a combo box.
The `value` attribute of the `master` contains either the index of the
selected row (if `sendSelected` is left at default, `False`) or a value
converted to `valueType` (`str` by default).
Furthermore, the value is converted by looking up into dictionary
`control2attributeDict`.
:param widget: the widget into which the box is inserted
:type widget: PyQt4.QtGui.QWidget or None
:param master: master widget
:type master: OWWidget or OWComponent
:param value: the master's attribute with which the value is synchronized
:type value: str
:param box: tells whether the widget has a border, and its label
:type box: int or str or None
:param orientation: orientation of the layout in the box
:type orientation: str or int or bool
:param label: a label that is inserted into the box
:type label: str
:param labelWidth: the width of the label
:type labelWidth: int
:param callback: a function that is called when the value is changed
:type callback: function
:param items: items (optionally with data) that are put into the box
:type items: tuple of str or tuples
:param sendSelectedValue: flag telling whether to store/retrieve indices
or string values from `value`
:type sendSelectedValue: bool
:param valueType: the type into which the selected value is converted
if sentSelectedValue is `False`
:type valueType: type
:param control2attributeDict: a dictionary through which the value is
converted
:type control2attributeDict: dict or None
:param emptyString: the string value in the combo box that gets stored as
an empty string in `value`
:type emptyString: str
:param editable: a flag telling whether the combo is editable
:type editable: bool
:param int contentsLength: Contents character length to use as a
fixed size hint. When not None, equivalent to::
combo.setSizeAdjustPolicy(
QComboBox.AdjustToMinimumContentsLengthWithIcon)
combo.setMinimumContentsLength(contentsLength)
:param int maximumContentsLength: Specifies the upper bound on the
`sizeHint` and `minimumSizeHint` width specified in character
length (default: 25, use 0 to disable)
:rtype: PyQt4.QtGui.QComboBox
"""
if box or label:
hb = widgetBox(widget, box, orientation, addToLayout=False)
if label is not None:
widgetLabel(hb, label, labelWidth)
else:
hb = widget
combo = OrangeComboBox(
hb, maximumContentsLength=maximumContentsLength,
editable=editable)
if contentsLength is not None:
combo.setSizeAdjustPolicy(
QtGui.QComboBox.AdjustToMinimumContentsLengthWithIcon)
combo.setMinimumContentsLength(contentsLength)
combo.box = hb
for item in items:
if isinstance(item, (tuple, list)):
combo.addItem(*item)
else:
combo.addItem(str(item))
if value:
cindex = getdeepattr(master, value)
if isinstance(cindex, str):
if items and cindex in items:
cindex = items.index(getdeepattr(master, value))
else:
cindex = 0
if cindex > combo.count() - 1:
cindex = 0
combo.setCurrentIndex(cindex)
if sendSelectedValue:
if control2attributeDict is None:
control2attributeDict = {}
if emptyString:
control2attributeDict[emptyString] = ""
connectControl(
master, value, callback, combo.activated[str],
CallFrontComboBox(combo, valueType, control2attributeDict),
ValueCallbackCombo(master, value, valueType,
control2attributeDict))
else:
connectControl(
master, value, callback, combo.activated[int],
CallFrontComboBox(combo, None, control2attributeDict))
miscellanea(combo, hb, widget, **misc)
return combo
class OrangeListBox(QtGui.QListWidget):
"""
List box with drag and drop functionality. Function :obj:`listBox`
constructs instances of this class; do not use the class directly.
.. attribute:: master
The widget into which the listbox is inserted.
.. attribute:: ogLabels
The name of the master's attribute that holds the strings with items
in the list box.
.. attribute:: ogValue
The name of the master's attribute that holds the indices of selected
items.
.. attribute:: enableDragDrop
A flag telling whether drag-and-drop is enabled.
.. attribute:: dragDropCallback
A callback that is called at the end of drop event.
.. attribute:: dataValidityCallback
A callback that is called on dragEnter and dragMove events and returns
either `ev.accept()` or `ev.ignore()`.
.. attribute:: defaultSizeHint
The size returned by the `sizeHint` method.
"""
def __init__(self, master, enableDragDrop=False, dragDropCallback=None,
dataValidityCallback=None, sizeHint=None, *args):
"""
:param master: the master widget
:type master: OWWidget or OWComponent
:param enableDragDrop: flag telling whether drag and drop is enabled
:type enableDragDrop: bool
:param dragDropCallback: callback for the end of drop event
:type dragDropCallback: function
:param dataValidityCallback: callback that accepts or ignores dragEnter
and dragMove events
:type dataValidityCallback: function with one argument (event)
:param sizeHint: size hint
:type sizeHint: PyQt4.QtGui.QSize
:param args: optional arguments for the inherited constructor
"""
self.master = master
super().__init__(*args)
self.drop_callback = dragDropCallback
self.valid_data_callback = dataValidityCallback
if not sizeHint:
self.size_hint = QtCore.QSize(150, 100)
else:
self.size_hint = sizeHint
if enableDragDrop:
self.setDragEnabled(True)
self.setAcceptDrops(True)
self.setDropIndicatorShown(True)
def sizeHint(self):
return self.size_hint
def dragEnterEvent(self, ev):
super().dragEnterEvent(ev)
if self.valid_data_callback:
self.valid_data_callback(ev)
elif isinstance(ev.source(), OrangeListBox):
ev.setDropAction(Qt.MoveAction)
ev.accept()
else:
ev.ignore()
def dropEvent(self, ev):
ev.setDropAction(Qt.MoveAction)
super().dropEvent(ev)
items = self.update_master()
if ev.source() is not self:
ev.source().update_master(exclude=items)
if self.drop_callback:
self.drop_callback()
def update_master(self, exclude=()):
control_list = [self.item(i).data(Qt.UserRole) for i in range(self.count()) if self.item(i).data(Qt.UserRole) not in exclude]
if self.ogLabels:
master_list = getattr(self.master, self.ogLabels)
if master_list != control_list:
setattr(self.master, self.ogLabels, control_list)
return control_list
def updateGeometries(self):
# A workaround for a bug in Qt
# (see: http://bugreports.qt.nokia.com/browse/QTBUG-14412)
if getattr(self, "_updatingGeometriesNow", False):
return
self._updatingGeometriesNow = True
try:
return super().updateGeometries()
finally:
self._updatingGeometriesNow = False
# TODO: SmallWidgetButton is used only in OWkNNOptimization.py. (Re)Move.
# eliminated?
class SmallWidgetButton(QtGui.QPushButton):
def __init__(self, widget, text="", pixmap=None, box=None,
orientation='vertical', autoHideWidget=None, **misc):
#self.parent = parent
if pixmap is not None:
iconDir = os.path.join(os.path.dirname(__file__), "icons")
name = ""
if isinstance(pixmap, str):
if os.path.exists(pixmap):
name = pixmap
elif os.path.exists(os.path.join(iconDir, pixmap)):
name = os.path.join(iconDir, pixmap)
elif isinstance(pixmap, (QtGui.QPixmap, QtGui.QIcon)):
name = pixmap
name = name or os.path.join(iconDir, "arrow_down.png")
super().__init__(QtGui.QIcon(name), text, widget)
else:
super().__init__(text, widget)
if widget.layout() is not None:
widget.layout().addWidget(self)
# create autohide widget and set a layout
self.widget = self.autohideWidget = \
(autoHideWidget or AutoHideWidget)(None, Qt.Popup)
setLayout(self.widget, orientation)
if box:
self.widget = widgetBox(self.widget, box, orientation)
self.autohideWidget.hide()
miscellanea(self, self.widget, widget, **misc)
def mousePressEvent(self, ev):
super().mousePressEvent(ev)
if self.autohideWidget.isVisible():
self.autohideWidget.hide()
else:
self.autohideWidget.move(
self.mapToGlobal(QtCore.QPoint(0, self.height())))
self.autohideWidget.show()
class SmallWidgetLabel(QtGui.QLabel):
def __init__(self, widget, text="", pixmap=None, box=None,
orientation='vertical', **misc):
super().__init__(widget)
if text:
self.setText("<font color=\"#C10004\">" + text + "</font>")
elif pixmap is not None:
iconDir = os.path.join(os.path.dirname(__file__), "icons")
name = ""
if isinstance(pixmap, str):
if os.path.exists(pixmap):
name = pixmap
elif os.path.exists(os.path.join(iconDir, pixmap)):
name = os.path.join(iconDir, pixmap)
elif isinstance(pixmap, (QtGui.QPixmap, QtGui.QIcon)):
name = pixmap
name = name or os.path.join(iconDir, "arrow_down.png")
self.setPixmap(QtGui.QPixmap(name))
self.autohideWidget = self.widget = AutoHideWidget(None, Qt.Popup)
setLayout(self.widget, orientation)
if box:
self.widget = widgetBox(self.widget, box, orientation)
self.autohideWidget.hide()
miscellanea(self, self.widget, widget, **misc)
def mousePressEvent(self, ev):
super().mousePressEvent(ev)
if self.autohideWidget.isVisible():
self.autohideWidget.hide()
else:
self.autohideWidget.move(
self.mapToGlobal(QtCore.QPoint(0, self.height())))
self.autohideWidget.show()
class AutoHideWidget(QtGui.QWidget):
def leaveEvent(self, _):
self.hide()
# TODO Class SearchLineEdit: it doesn't seem to be used anywhere
# see widget DataDomain
class SearchLineEdit(QtGui.QLineEdit):
"""
QLineEdit for quick searches
"""
def __init__(self, t, searcher):
super().__init__(self, t)
self.searcher = searcher
def keyPressEvent(self, e):
"""
Handles keys up and down by selecting the previous and the next item
in the list, and the escape key, which hides the searcher.
"""
k = e.key()
if k == Qt.Key_Down:
curItem = self.searcher.lb.currentItem()
if curItem + 1 < self.searcher.lb.count():
self.searcher.lb.setCurrentItem(curItem + 1)
elif k == Qt.Key_Up:
curItem = self.searcher.lb.currentItem()
if curItem:
self.searcher.lb.setCurrentItem(curItem - 1)
elif k == Qt.Key_Escape:
self.searcher.window.hide()
else:
return super().keyPressEvent(e)
# TODO Class Searcher: it doesn't seem to be used anywhere
# see widget DataDomain
class Searcher:
"""
The searcher class for :obj:`SearchLineEdit`.
"""
def __init__(self, control, master):
self.control = control
self.master = master
def __call__(self):
_s = QtGui.QStyle
self.window = t = QtGui.QFrame(
self.master,
_s.WStyle_Dialog + _s.WStyle_Tool + _s.WStyle_Customize +
_s.WStyle_NormalBorder)
QtGui.QVBoxLayout(t).setAutoAdd(1)
gs = self.master.mapToGlobal(QtCore.QPoint(0, 0))
gl = self.control.mapToGlobal(QtCore.QPoint(0, 0))
t.move(gl.x() - gs.x(), gl.y() - gs.y())
self.allItems = [self.control.text(i)
for i in range(self.control.count())]
le = SearchLineEdit(t, self)
self.lb = QtGui.QListWidget(t)
for i in self.allItems:
self.lb.insertItem(i)
t.setFixedSize(self.control.width(), 200)
t.show()
le.setFocus()
le.textChanged.connect(self.textChanged)
le.returnPressed.connect(self.returnPressed)
self.lb.itemClicked.connect(self.mouseClicked)
def textChanged(self, s):
s = str(s)
self.lb.clear()
for i in self.allItems:
if s.lower() in i.lower():
self.lb.insertItem(i)
def returnPressed(self):
if self.lb.count():
self.conclude(self.lb.text(max(0, self.lb.currentItem())))
else:
self.window.hide()
def mouseClicked(self, item):
self.conclude(item.text())
def conclude(self, value):
index = self.allItems.index(value)
self.control.setCurrentItem(index)
if self.control.cback:
if self.control.sendSelectedValue:
self.control.cback(value)
else:
self.control.cback(index)
if self.control.cfunc:
self.control.cfunc()
self.window.hide()
# creates a widget box with a button in the top right edge that shows/hides all
# widgets in the box and collapse the box to its minimum height
# TODO collapsableWidgetBox is used only in OWMosaicDisplay.py; (re)move
class collapsableWidgetBox(QtGui.QGroupBox):
def __init__(self, widget, box="", master=None, value="",
orientation="vertical", callback=None):
super().__init__(widget)
self.setFlat(1)
setLayout(self, orientation)
if widget.layout() is not None:
widget.layout().addWidget(self)
if isinstance(box, str):
self.setTitle(" " + box.strip() + " ")
self.setCheckable(True)
self.master = master
self.value = value
self.callback = callback
self.clicked.connect(self.toggled)
def toggled(self, _=0):
if self.value:
self.master.__setattr__(self.value, self.isChecked())
self.updateControls()
if self.callback is not None:
self.callback()
def updateControls(self):
val = getdeepattr(self.master, self.value)
width = self.width()
self.setChecked(val)
self.setFlat(not val)
self.setMinimumSize(QtCore.QSize(width if not val else 0, 0))
for c in self.children():
if isinstance(c, QtGui.QLayout):
continue
if val:
c.show()
else:
c.hide()
# creates an icon that allows you to show/hide the widgets in the widgets list
# TODO Class widgetHider doesn't seem to be used anywhere; remove?
class widgetHider(QtGui.QWidget):
def __init__(self, widget, master, value, _=(19, 19), widgets=None,
tooltip=None):
super().__init__(widget)
if widget.layout() is not None:
widget.layout().addWidget(self)
self.value = value
self.master = master
if tooltip:
self.setToolTip(tooltip)
iconDir = os.path.join(os.path.dirname(__file__), "icons")
icon1 = os.path.join(iconDir, "arrow_down.png")
icon2 = os.path.join(iconDir, "arrow_up.png")
self.pixmaps = [QtGui.QPixmap(icon1), QtGui.QPixmap(icon2)]
self.setFixedSize(self.pixmaps[0].size())
self.disables = list(widgets or [])
self.makeConsistent = Disabler(self, master, value, type=HIDER)
if widgets:
self.setWidgets(widgets)
def mousePressEvent(self, ev):
self.master.__setattr__(self.value,
not getdeepattr(self.master, self.value))
self.makeConsistent()
def setWidgets(self, widgets):
self.disables = list(widgets)
self.makeConsistent()
def paintEvent(self, ev):
super().paintEvent(ev)
if self.pixmaps:
pix = self.pixmaps[getdeepattr(self.master, self.value)]
painter = QtGui.QPainter(self)
painter.drawPixmap(0, 0, pix)
##############################################################################
# callback handlers
def auto_commit(widget, master, value, label, auto_label=None, box=True,
checkbox_label=None, orientation=None, commit=None,
callback=None, **misc):
"""
Add a commit button with auto-commit check box.
The widget must have a commit method and a setting that stores whether
auto-commit is on.
The function replaces the commit method with a new commit method that
checks whether auto-commit is on. If it is, it passes the call to the
original commit, otherwise it sets the dirty flag.
The checkbox controls the auto-commit. When auto-commit is switched on, the
checkbox callback checks whether the dirty flag is on and calls the original
commit.
Important! Do not connect any signals to the commit before calling
auto_commit.
:param widget: the widget into which the box with the button is inserted
:type widget: PyQt4.QtGui.QWidget or None
:param value: the master's attribute which stores whether the auto-commit
is on
:type value: str
:param master: master widget
:type master: OWWidget or OWComponent
:param label: The button label
:type label: str
:param label: The label used when auto-commit is on; default is
`"Auto " + label`
:type label: str
:param commit: master's method to override ('commit' by default)
:type commit: function
:param callback: function to call whenever the checkbox's statechanged
:type callback: function
:param box: tells whether the widget has a border, and its label
:type box: int or str or None
:return: the box
"""
def checkbox_toggled():
if getattr(master, value):
btn.setText(auto_label)
btn.setEnabled(False)
if dirty:
do_commit()
else:
btn.setText(label)
btn.setEnabled(True)
if callback:
callback()
def unconditional_commit(*args, **kwargs):
nonlocal dirty
if getattr(master, value):
do_commit(*args, **kwargs)
else:
dirty = True
def do_commit(*args, **kwargs):
nonlocal dirty
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
commit(*args, **kwargs)
QApplication.restoreOverrideCursor()
dirty = False
dirty = False
commit = commit or getattr(master, 'commit')
commit_name = next(LAMBDA_NAME) if isinstance(commit, LambdaType) else commit.__name__
setattr(master, 'unconditional_' + commit_name, commit)
if not auto_label:
if checkbox_label:
auto_label = label
else:
auto_label = "Auto " + label.lower() + " is on"
if isinstance(box, QtGui.QWidget):
b = box
else:
if orientation is None:
orientation = bool(checkbox_label)
b = widgetBox(widget, box=box, orientation=orientation,
addToLayout=False)
b.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Maximum)
b.checkbox = cb = checkBox(b, master, value, checkbox_label,
callback=checkbox_toggled, tooltip=auto_label)
if checkbox_label and orientation == 'horizontal' or not orientation:
b.layout().insertSpacing(-1, 10)
cb.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
b.button = btn = button(b, master, label, callback=lambda: do_commit())
if not checkbox_label:
btn.setSizePolicy(QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Preferred)
checkbox_toggled()
setattr(master, commit_name, unconditional_commit)
miscellanea(b, widget, widget,
addToLayout=not isinstance(box, QtGui.QWidget), **misc)
return b
class ControlledList(list):
"""
A class derived from a list that is connected to a
:obj:`PyQt4.QtGui.QListBox`: the list contains indices of items that are
selected in the list box. Changing the list content changes the
selection in the list box.
"""
def __init__(self, content, listBox=None):
super().__init__(content)
self.listBox = listBox
def __reduce__(self):
# cannot pickle self.listBox, but can't discard it
# (ControlledList may live on)
import copyreg
return copyreg._reconstructor, (list, list, ()), None, self.__iter__()
# TODO ControllgedList.item2name is probably never used
def item2name(self, item):
item = self.listBox.labels[item]
if type(item) is tuple:
return item[1]
else:
return item
def __setitem__(self, index, item):
if isinstance(index, int):
self.listBox.item(self[index]).setSelected(0)
item.setSelected(1)
else:
for i in self[index]:
self.listBox.item(i).setSelected(0)
for i in item:
self.listBox.item(i).setSelected(1)
super().__setitem__(index, item)
def __delitem__(self, index):
if isinstance(index, int):
self.listBox.item(self[index]).setSelected(0)
else:
for i in self[index]:
self.listBox.item(i).setSelected(0)
super().__delitem__(index)
def append(self, item):
super().append(item)
item.setSelected(1)
def extend(self, items):
super().extend(items)
for i in items:
self.listBox.item(i).setSelected(1)
def insert(self, index, item):
item.setSelected(1)
super().insert(index, item)
def pop(self, index=-1):
i = super().pop(index)
self.listBox.item(i).setSelected(0)
def remove(self, item):
item.setSelected(0)
super().remove(item)
def connectControl(master, value, f, signal,
cfront, cback=None, cfunc=None, fvcb=None):
cback = cback or value and ValueCallback(master, value, fvcb)
if cback:
if signal:
signal.connect(cback)
cback.opposite = cfront
if value and cfront and hasattr(master, CONTROLLED_ATTRIBUTES):
getattr(master, CONTROLLED_ATTRIBUTES)[value] = cfront
cfunc = cfunc or f and FunctionCallback(master, f)
if cfunc:
if signal:
signal.connect(cfunc)
cfront.opposite = tuple(filter(None, (cback, cfunc)))
return cfront, cback, cfunc
class ControlledCallback:
def __init__(self, widget, attribute, f=None):
self.widget = widget
self.attribute = attribute
self.f = f
self.disabled = 0
if isinstance(widget, dict):
return # we can't assign attributes to dict
if not hasattr(widget, "callbackDeposit"):
widget.callbackDeposit = []
widget.callbackDeposit.append(self)
def acyclic_setattr(self, value):
if self.disabled:
return
if self.f:
if self.f in (int, float) and (
not value or isinstance(value, str) and value in "+-"):
value = self.f(0)
else:
value = self.f(value)
opposite = getattr(self, "opposite", None)
if opposite:
try:
opposite.disabled += 1
if type(self.widget) is dict:
self.widget[self.attribute] = value
else:
setattr(self.widget, self.attribute, value)
finally:
opposite.disabled -= 1
else:
if isinstance(self.widget, dict):
self.widget[self.attribute] = value
else:
setattr(self.widget, self.attribute, value)
class ValueCallback(ControlledCallback):
# noinspection PyBroadException
def __call__(self, value):
if value is None:
return
try:
self.acyclic_setattr(value)
except:
print("gui.ValueCallback: %s" % value)
import traceback
import sys
traceback.print_exception(*sys.exc_info())
class ValueCallbackCombo(ValueCallback):
def __init__(self, widget, attribute, f=None, control2attributeDict=None):
super().__init__(widget, attribute, f)
self.control2attributeDict = control2attributeDict or {}
def __call__(self, value):
value = str(value)
return super().__call__(self.control2attributeDict.get(value, value))
class ValueCallbackLineEdit(ControlledCallback):
def __init__(self, control, widget, attribute, f=None):
ControlledCallback.__init__(self, widget, attribute, f)
self.control = control
# noinspection PyBroadException
def __call__(self, value):
if value is None:
return
try:
pos = self.control.cursorPosition()
self.acyclic_setattr(value)
self.control.setCursorPosition(pos)
except:
print("invalid value ", value, type(value))
import traceback
import sys
traceback.print_exception(*sys.exc_info())
class SetLabelCallback:
def __init__(self, widget, label, format="%5.2f", f=None):
self.widget = widget
self.label = label
self.format = format
self.f = f
if hasattr(widget, "callbackDeposit"):
widget.callbackDeposit.append(self)
self.disabled = 0
def __call__(self, value):
if not self.disabled and value is not None:
if self.f:
value = self.f(value)
self.label.setText(self.format % value)
class FunctionCallback:
def __init__(self, master, f, widget=None, id=None, getwidget=False):
self.master = master
self.widget = widget
self.f = f
self.id = id
self.getwidget = getwidget
if hasattr(master, "callbackDeposit"):
master.callbackDeposit.append(self)
self.disabled = 0
def __call__(self, *value):
if not self.disabled and value is not None:
kwds = {}
if self.id is not None:
kwds['id'] = self.id
if self.getwidget:
kwds['widget'] = self.widget
if isinstance(self.f, list):
for f in self.f:
f(**kwds)
else:
self.f(**kwds)
class CallBackListBox:
def __init__(self, control, widget):
self.control = control
self.widget = widget
self.disabled = 0
def __call__(self, *_): # triggered by selectionChange()
if not self.disabled and self.control.ogValue is not None:
clist = getdeepattr(self.widget, self.control.ogValue)
# skip the overloaded method to avoid a cycle
list.__delitem__(clist, slice(0, len(clist)))
control = self.control
for i in range(control.count()):
if control.item(i).isSelected():
list.append(clist, i)
self.widget.__setattr__(self.control.ogValue, clist)
class CallBackRadioButton:
def __init__(self, control, widget):
self.control = control
self.widget = widget
self.disabled = False
def __call__(self, *_): # triggered by toggled()
if not self.disabled and self.control.ogValue is not None:
arr = [butt.isChecked() for butt in self.control.buttons]
self.widget.__setattr__(self.control.ogValue, arr.index(1))
class CallBackLabeledSlider:
def __init__(self, control, widget, lookup):
self.control = control
self.widget = widget
self.lookup = lookup
self.disabled = False
def __call__(self, *_):
if not self.disabled and self.control.ogValue is not None:
self.widget.__setattr__(self.control.ogValue,
self.lookup[self.control.value()])
##############################################################################
# call fronts (change of the attribute value changes the related control)
class ControlledCallFront:
def __init__(self, control):
self.control = control
self.disabled = 0
def action(self, *_):
pass
def __call__(self, *args):
if not self.disabled:
opposite = getattr(self, "opposite", None)
if opposite:
try:
for op in opposite:
op.disabled += 1
self.action(*args)
finally:
for op in opposite:
op.disabled -= 1
else:
self.action(*args)
class CallFrontSpin(ControlledCallFront):
def action(self, value):
if value is not None:
self.control.setValue(value)
class CallFrontDoubleSpin(ControlledCallFront):
def action(self, value):
if value is not None:
self.control.setValue(value)
class CallFrontCheckBox(ControlledCallFront):
def action(self, value):
if value is not None:
values = [Qt.Unchecked, Qt.Checked, Qt.PartiallyChecked]
self.control.setCheckState(values[value])
class CallFrontButton(ControlledCallFront):
def action(self, value):
if value is not None:
self.control.setChecked(bool(value))
class CallFrontComboBox(ControlledCallFront):
def __init__(self, control, valType=None, control2attributeDict=None):
super().__init__(control)
self.valType = valType
if control2attributeDict is None:
self.attribute2controlDict = {}
else:
self.attribute2controlDict = \
{y: x for x, y in control2attributeDict.items()}
def action(self, value):
if value is not None:
value = self.attribute2controlDict.get(value, value)
if self.valType:
for i in range(self.control.count()):
if self.valType(str(self.control.itemText(i))) == value:
self.control.setCurrentIndex(i)
return
values = ""
for i in range(self.control.count()):
values += str(self.control.itemText(i)) + \
(i < self.control.count() - 1 and ", " or ".")
print("unable to set %s to value '%s'. Possible values are %s"
% (self.control, value, values))
else:
if value < self.control.count():
self.control.setCurrentIndex(value)
class CallFrontHSlider(ControlledCallFront):
def action(self, value):
if value is not None:
self.control.setValue(value)
class CallFrontLabeledSlider(ControlledCallFront):
def __init__(self, control, lookup):
super().__init__(control)
self.lookup = lookup
def action(self, value):
if value is not None:
self.control.setValue(self.lookup.index(value))
class CallFrontLogSlider(ControlledCallFront):
def action(self, value):
if value is not None:
if value < 1e-30:
print("unable to set %s to %s (value too small)" %
(self.control, value))
else:
self.control.setValue(math.log10(value))
class CallFrontLineEdit(ControlledCallFront):
def action(self, value):
self.control.setText(str(value))
class CallFrontRadioButtons(ControlledCallFront):
def action(self, value):
if value < 0 or value >= len(self.control.buttons):
value = 0
self.control.buttons[value].setChecked(1)
class CallFrontListBox(ControlledCallFront):
def action(self, value):
if value is not None:
if not isinstance(value, ControlledList):
setattr(self.control.ogMaster, self.control.ogValue,
ControlledList(value, self.control))
for i in range(self.control.count()):
shouldBe = i in value
if shouldBe != self.control.item(i).isSelected():
self.control.item(i).setSelected(shouldBe)
class CallFrontListBoxLabels(ControlledCallFront):
unknownType = None
def action(self, values):
self.control.clear()
if values:
for value in values:
if isinstance(value, tuple):
text, icon = value
if isinstance(icon, int):
item = QtGui.QListWidgetItem(attributeIconDict[icon], text)
else:
item = QtGui.QListWidgetItem(icon, text)
elif isinstance(value, Variable):
item = QtGui.QListWidgetItem(*attributeItem(value))
else:
item = QtGui.QListWidgetItem(value)
item.setData(Qt.UserRole, value)
self.control.addItem(item)
class CallFrontLabel:
def __init__(self, control, label, master):
self.control = control
self.label = label
self.master = master
def __call__(self, *_):
self.control.setText(self.label % self.master.__dict__)
##############################################################################
## Disabler is a call-back class for check box that can disable/enable other
## widgets according to state (checked/unchecked, enabled/disable) of the
## given check box
##
## Tricky: if self.propagateState is True (default), then if check box is
## disabled the related widgets will be disabled (even if the checkbox is
## checked). If self.propagateState is False, the related widgets will be
## disabled/enabled if check box is checked/clear, disregarding whether the
## check box itself is enabled or not. (If you don't understand, see the
## code :-)
DISABLER = 1
HIDER = 2
# noinspection PyShadowingBuiltins
class Disabler:
def __init__(self, widget, master, valueName, propagateState=True,
type=DISABLER):
self.widget = widget
self.master = master
self.valueName = valueName
self.propagateState = propagateState
self.type = type
def __call__(self, *value):
currState = self.widget.isEnabled()
if currState or not self.propagateState:
if len(value):
disabled = not value[0]
else:
disabled = not getdeepattr(self.master, self.valueName)
else:
disabled = 1
for w in self.widget.disables:
if type(w) is tuple:
if isinstance(w[0], int):
i = 1
if w[0] == -1:
disabled = not disabled
else:
i = 0
if self.type == DISABLER:
w[i].setDisabled(disabled)
elif self.type == HIDER:
if disabled:
w[i].hide()
else:
w[i].show()
if hasattr(w[i], "makeConsistent"):
w[i].makeConsistent()
else:
if self.type == DISABLER:
w.setDisabled(disabled)
elif self.type == HIDER:
if disabled:
w.hide()
else:
w.show()
##############################################################################
# some table related widgets
# noinspection PyShadowingBuiltins
class tableItem(QtGui.QTableWidgetItem):
def __init__(self, table, x, y, text, editType=None, backColor=None,
icon=None, type=QtGui.QTableWidgetItem.Type):
super().__init__(type)
if icon:
self.setIcon(QtGui.QIcon(icon))
if editType is not None:
self.setFlags(editType)
else:
self.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable |
Qt.ItemIsSelectable)
if backColor is not None:
self.setBackground(QtGui.QBrush(backColor))
# we add it this way so that text can also be int and sorting will be
# done properly (as integers and not as text)
self.setData(Qt.DisplayRole, text)
table.setItem(x, y, self)
TableValueRole = next(OrangeUserRole) # Role to retrieve orange.Value
TableClassValueRole = next(OrangeUserRole) # Retrieve class value for the row
TableDistribution = next(OrangeUserRole) # Retrieve distribution of the column
TableVariable = next(OrangeUserRole) # Role to retrieve the column's variable
BarRatioRole = next(OrangeUserRole) # Ratio for drawing distribution bars
BarBrushRole = next(OrangeUserRole) # Brush for distribution bar
SortOrderRole = next(OrangeUserRole) # Used for sorting
class TableBarItem(QtGui.QItemDelegate):
BarRole = next(OrangeUserRole)
ColorRole = next(OrangeUserRole)
def __init__(self, parent=None, color=QtGui.QColor(255, 170, 127),
color_schema=None):
"""
:param QObject parent: Parent object.
:param QColor color: Default color of the distribution bar.
:param color_schema:
If not None it must be an instance of
:class:`OWColorPalette.ColorPaletteGenerator` (note: this
parameter, if set, overrides the ``color``)
:type color_schema: :class:`OWColorPalette.ColorPaletteGenerator`
"""
super().__init__(parent)
self.color = color
self.color_schema = color_schema
def paint(self, painter, option, index):
painter.save()
self.drawBackground(painter, option, index)
ratio = index.data(TableBarItem.BarRole)
if isinstance(ratio, float):
if math.isnan(ratio):
ratio = None
color = self.color
if self.color_schema is not None and ratio is not None:
class_ = index.data(TableClassValueRole)
if isinstance(class_, Orange.data.Value) and \
class_.variable.is_discrete and \
not math.isnan(class_):
color = self.color_schema[int(class_)]
if ratio is not None:
painter.save()
painter.setPen(QtGui.QPen(QtGui.QBrush(color), 5,
Qt.SolidLine, Qt.RoundCap))
rect = option.rect.adjusted(3, 0, -3, -5)
x, y = rect.x(), rect.y() + rect.height()
painter.drawLine(x, y, x + rect.width() * ratio, y)
painter.restore()
text_rect = option.rect.adjusted(0, 0, 0, -3)
else:
text_rect = option.rect
text = index.data(Qt.DisplayRole)
self.drawDisplay(painter, option, text_rect, text)
painter.restore()
class BarItemDelegate(QtGui.QStyledItemDelegate):
def __init__(self, parent, brush=QtGui.QBrush(QtGui.QColor(255, 170, 127)),
scale=(0.0, 1.0)):
super().__init__(parent)
self.brush = brush
self.scale = scale
def paint(self, painter, option, index):
if option.widget is not None:
style = option.widget.style()
else:
style = QtGui.QApplication.style()
style.drawPrimitive(
QtGui.QStyle.PE_PanelItemViewRow, option, painter,
option.widget)
style.drawPrimitive(
QtGui.QStyle.PE_PanelItemViewItem, option, painter,
option.widget)
rect = option.rect
val = index.data(Qt.DisplayRole)
if isinstance(val, float):
minv, maxv = self.scale
val = (val - minv) / (maxv - minv)
painter.save()
if option.state & QtGui.QStyle.State_Selected:
painter.setOpacity(0.75)
painter.setBrush(self.brush)
painter.drawRect(
rect.adjusted(1, 1, - rect.width() * (1.0 - val) - 2, -2))
painter.restore()
class IndicatorItemDelegate(QtGui.QStyledItemDelegate):
IndicatorRole = next(OrangeUserRole)
def __init__(self, parent, role=IndicatorRole, indicatorSize=2):
super().__init__(parent)
self.role = role
self.indicatorSize = indicatorSize
def paint(self, painter, option, index):
super().paint(painter, option, index)
rect = option.rect
indicator = index.data(self.role)
if indicator:
painter.save()
painter.setRenderHints(QtGui.QPainter.Antialiasing)
painter.setBrush(QtGui.QBrush(Qt.black))
painter.drawEllipse(rect.center(),
self.indicatorSize, self.indicatorSize)
painter.restore()
class LinkStyledItemDelegate(QtGui.QStyledItemDelegate):
LinkRole = next(OrangeUserRole)
def __init__(self, parent):
super().__init__(parent)
self.mousePressState = QtCore.QModelIndex(), QtCore.QPoint()
parent.entered.connect(self.onEntered)
def sizeHint(self, option, index):
size = super().sizeHint(option, index)
return QtCore.QSize(size.width(), max(size.height(), 20))
def linkRect(self, option, index):
if option.widget is not None:
style = option.widget.style()
else:
style = QtGui.QApplication.style()
text = self.displayText(index.data(Qt.DisplayRole),
QtCore.QLocale.system())
self.initStyleOption(option, index)
textRect = style.subElementRect(
QtGui.QStyle.SE_ItemViewItemText, option, option.widget)
if not textRect.isValid():
textRect = option.rect
margin = style.pixelMetric(
QtGui.QStyle.PM_FocusFrameHMargin, option, option.widget) + 1
textRect = textRect.adjusted(margin, 0, -margin, 0)
font = index.data(Qt.FontRole)
if not isinstance(font, QtGui.QFont):
font = option.font
metrics = QtGui.QFontMetrics(font)
elideText = metrics.elidedText(text, option.textElideMode,
textRect.width())
return metrics.boundingRect(textRect, option.displayAlignment,
elideText)
def editorEvent(self, event, model, option, index):
if event.type() == QtCore.QEvent.MouseButtonPress and \
self.linkRect(option, index).contains(event.pos()):
self.mousePressState = (QtCore.QPersistentModelIndex(index),
QtCore.QPoint(event.pos()))
elif event.type() == QtCore.QEvent.MouseButtonRelease:
link = index.data(LinkRole)
if not isinstance(link, str):
link = None
pressedIndex, pressPos = self.mousePressState
if pressedIndex == index and \
(pressPos - event.pos()).manhattanLength() < 5 and \
link is not None:
import webbrowser
webbrowser.open(link)
self.mousePressState = QtCore.QModelIndex(), event.pos()
elif event.type() == QtCore.QEvent.MouseMove:
link = index.data(LinkRole)
if not isinstance(link, str):
link = None
if link is not None and \
self.linkRect(option, index).contains(event.pos()):
self.parent().viewport().setCursor(Qt.PointingHandCursor)
else:
self.parent().viewport().setCursor(Qt.ArrowCursor)
return super().editorEvent(event, model, option, index)
def onEntered(self, index):
link = index.data(LinkRole)
if not isinstance(link, str):
link = None
if link is None:
self.parent().viewport().setCursor(Qt.ArrowCursor)
def paint(self, painter, option, index):
link = index.data(LinkRole)
if not isinstance(link, str):
link = None
if link is not None:
if option.widget is not None:
style = option.widget.style()
else:
style = QtGui.QApplication.style()
style.drawPrimitive(
QtGui.QStyle.PE_PanelItemViewRow, option, painter,
option.widget)
style.drawPrimitive(
QtGui.QStyle.PE_PanelItemViewItem, option, painter,
option.widget)
text = self.displayText(index.data(Qt.DisplayRole),
QtCore.QLocale.system())
textRect = style.subElementRect(
QtGui.QStyle.SE_ItemViewItemText, option, option.widget)
if not textRect.isValid():
textRect = option.rect
margin = style.pixelMetric(
QtGui.QStyle.PM_FocusFrameHMargin, option, option.widget) + 1
textRect = textRect.adjusted(margin, 0, -margin, 0)
elideText = QtGui.QFontMetrics(option.font).elidedText(
text, option.textElideMode, textRect.width())
painter.save()
font = index.data(Qt.FontRole)
if not isinstance(font, QtGui.QFont):
font = option.font
painter.setFont(font)
painter.setPen(QtGui.QPen(Qt.blue))
painter.drawText(textRect, option.displayAlignment, elideText)
painter.restore()
else:
super().paint(painter, option, index)
LinkRole = LinkStyledItemDelegate.LinkRole
class ColoredBarItemDelegate(QtGui.QStyledItemDelegate):
""" Item delegate that can also draws a distribution bar
"""
def __init__(self, parent=None, decimals=3, color=Qt.red):
super().__init__(parent)
self.decimals = decimals
self.float_fmt = "%%.%if" % decimals
self.color = QtGui.QColor(color)
def displayText(self, value, locale):
if isinstance(value, float):
return self.float_fmt % value
elif isinstance(value, str):
return value
elif value is None:
return "NA"
else:
return str(value)
def sizeHint(self, option, index):
font = self.get_font(option, index)
metrics = QtGui.QFontMetrics(font)
height = metrics.lineSpacing() + 8 # 4 pixel margin
width = metrics.width(self.displayText(index.data(Qt.DisplayRole),
QtCore.QLocale())) + 8
return QtCore.QSize(width, height)
def paint(self, painter, option, index):
self.initStyleOption(option, index)
text = self.displayText(index.data(Qt.DisplayRole), QtCore.QLocale())
ratio, have_ratio = self.get_bar_ratio(option, index)
rect = option.rect
if have_ratio:
# The text is raised 3 pixels above the bar.
# TODO: Style dependent margins?
text_rect = rect.adjusted(4, 1, -4, -4)
else:
text_rect = rect.adjusted(4, 4, -4, -4)
painter.save()
font = self.get_font(option, index)
painter.setFont(font)
if option.widget is not None:
style = option.widget.style()
else:
style = QtGui.QApplication.style()
style.drawPrimitive(
QtGui.QStyle.PE_PanelItemViewRow, option, painter,
option.widget)
style.drawPrimitive(
QtGui.QStyle.PE_PanelItemViewItem, option, painter,
option.widget)
# TODO: Check ForegroundRole.
if option.state & QtGui.QStyle.State_Selected:
color = option.palette.highlightedText().color()
else:
color = option.palette.text().color()
painter.setPen(QtGui.QPen(color))
align = self.get_text_align(option, index)
metrics = QtGui.QFontMetrics(font)
elide_text = metrics.elidedText(
text, option.textElideMode, text_rect.width())
painter.drawText(text_rect, align, elide_text)
painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
if have_ratio:
brush = self.get_bar_brush(option, index)
painter.setBrush(brush)
painter.setPen(QtGui.QPen(brush, 1))
bar_rect = QtCore.QRect(text_rect)
bar_rect.setTop(bar_rect.bottom() - 1)
bar_rect.setBottom(bar_rect.bottom() + 1)
w = text_rect.width()
bar_rect.setWidth(max(0, min(w * ratio, w)))
painter.drawRoundedRect(bar_rect, 2, 2)
painter.restore()
def get_font(self, option, index):
font = index.data(Qt.FontRole)
if not isinstance(font, QtGui.QFont):
font = option.font
return font
def get_text_align(self, _, index):
align = index.data(Qt.TextAlignmentRole)
if not isinstance(align, int):
align = Qt.AlignLeft | Qt.AlignVCenter
return align
def get_bar_ratio(self, _, index):
ratio = index.data(BarRatioRole)
return ratio, isinstance(ratio, float)
def get_bar_brush(self, _, index):
bar_brush = index.data(BarBrushRole)
if not isinstance(bar_brush, (QtGui.QColor, QtGui.QBrush)):
bar_brush = self.color
return QtGui.QBrush(bar_brush)
class VerticalLabel(QtGui.QLabel):
def __init__(self, text, parent=None):
super().__init__(text, parent)
self.setSizePolicy(QtGui.QSizePolicy.Preferred,
QtGui.QSizePolicy.MinimumExpanding)
self.setMaximumWidth(self.sizeHint().width() + 2)
self.setMargin(4)
def sizeHint(self):
metrics = QtGui.QFontMetrics(self.font())
rect = metrics.boundingRect(self.text())
size = QtCore.QSize(rect.height() + self.margin(),
rect.width() + self.margin())
return size
def setGeometry(self, rect):
super().setGeometry(rect)
def paintEvent(self, event):
painter = QtGui.QPainter(self)
rect = self.geometry()
text_rect = QtCore.QRect(0, 0, rect.width(), rect.height())
painter.translate(text_rect.bottomLeft())
painter.rotate(-90)
painter.drawText(
QtCore.QRect(QtCore.QPoint(0, 0),
QtCore.QSize(rect.height(), rect.width())),
Qt.AlignCenter, self.text())
painter.end()
class VerticalItemDelegate(QtGui.QStyledItemDelegate):
# Extra text top/bottom margin.
Margin = 6
def sizeHint(self, option, index):
sh = super().sizeHint(option, index)
return QtCore.QSize(sh.height() + self.Margin * 2, sh.width())
def paint(self, painter, option, index):
option = QtGui.QStyleOptionViewItemV4(option)
self.initStyleOption(option, index)
if not option.text:
return
if option.widget is not None:
style = option.widget.style()
else:
style = QtGui.QApplication.style()
style.drawPrimitive(
QtGui.QStyle.PE_PanelItemViewRow, option, painter,
option.widget)
cell_rect = option.rect
itemrect = QtCore.QRect(0, 0, cell_rect.height(), cell_rect.width())
opt = QtGui.QStyleOptionViewItemV4(option)
opt.rect = itemrect
textrect = style.subElementRect(
QtGui.QStyle.SE_ItemViewItemText, opt, opt.widget)
painter.save()
painter.setFont(option.font)
if option.displayAlignment & (Qt.AlignTop | Qt.AlignBottom):
brect = painter.boundingRect(
textrect, option.displayAlignment, option.text)
diff = textrect.height() - brect.height()
offset = max(min(diff / 2, self.Margin), 0)
if option.displayAlignment & Qt.AlignBottom:
offset = -offset
textrect.translate(0, offset)
painter.translate(option.rect.x(), option.rect.bottom())
painter.rotate(-90)
painter.drawText(textrect, option.displayAlignment, option.text)
painter.restore()
##############################################################################
# progress bar management
class ProgressBar:
def __init__(self, widget, iterations):
self.iter = iterations
self.widget = widget
self.count = 0
self.widget.progressBarInit()
def advance(self, count=1):
self.count += count
self.widget.progressBarSet(int(self.count * 100 / max(1, self.iter)))
def finish(self):
self.widget.progressBarFinished()
##############################################################################
def tabWidget(widget):
w = QtGui.QTabWidget(widget)
if widget.layout() is not None:
widget.layout().addWidget(w)
return w
def createTabPage(tabWidget, name, widgetToAdd=None, canScroll=False):
if widgetToAdd is None:
widgetToAdd = widgetBox(tabWidget, addToLayout=0, margin=4)
if canScroll:
scrollArea = QtGui.QScrollArea()
tabWidget.addTab(scrollArea, name)
scrollArea.setWidget(widgetToAdd)
scrollArea.setWidgetResizable(1)
scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
else:
tabWidget.addTab(widgetToAdd, name)
return widgetToAdd
def table(widget, rows=0, columns=0, selectionMode=-1, addToLayout=True):
w = QtGui.QTableWidget(rows, columns, widget)
if widget and addToLayout and widget.layout() is not None:
widget.layout().addWidget(w)
if selectionMode != -1:
w.setSelectionMode(selectionMode)
w.setHorizontalScrollMode(QtGui.QTableWidget.ScrollPerPixel)
w.horizontalHeader().setMovable(True)
return w
class VisibleHeaderSectionContextEventFilter(QtCore.QObject):
def __init__(self, parent, itemView=None):
super().__init__(parent)
self.itemView = itemView
def eventFilter(self, view, event):
if not isinstance(event, QtGui.QContextMenuEvent):
return False
model = view.model()
headers = [(view.isSectionHidden(i),
model.headerData(i, view.orientation(), Qt.DisplayRole)
) for i in range(view.count())]
menu = QtGui.QMenu("Visible headers", view)
for i, (checked, name) in enumerate(headers):
action = QtGui.QAction(name, menu)
action.setCheckable(True)
action.setChecked(not checked)
menu.addAction(action)
def toogleHidden(b, section=i):
view.setSectionHidden(section, not b)
if not b:
return
if self.itemView:
self.itemView.resizeColumnToContents(section)
else:
view.resizeSection(section,
max(view.sectionSizeHint(section), 10))
action.toggled.connect(toogleHidden)
menu.exec_(event.globalPos())
return True
def checkButtonOffsetHint(button, style=None):
option = QtGui.QStyleOptionButton()
option.initFrom(button)
if style is None:
style = button.style()
if isinstance(button, QtGui.QCheckBox):
pm_spacing = QtGui.QStyle.PM_CheckBoxLabelSpacing
pm_indicator_width = QtGui.QStyle.PM_IndicatorWidth
else:
pm_spacing = QtGui.QStyle.PM_RadioButtonLabelSpacing
pm_indicator_width = QtGui.QStyle.PM_ExclusiveIndicatorWidth
space = style.pixelMetric(pm_spacing, option, button)
width = style.pixelMetric(pm_indicator_width, option, button)
# TODO: add other styles (Maybe load corrections from .cfg file?)
style_correction = {"macintosh (aqua)": -2, "macintosh(aqua)": -2,
"plastique": 1, "cde": 1, "motif": 1}
return space + width + \
style_correction.get(QtGui.qApp.style().objectName().lower(), 0)
def toolButtonSizeHint(button=None, style=None):
if button is None and style is None:
style = QtGui.qApp.style()
elif style is None:
style = button.style()
button_size = \
style.pixelMetric(QtGui.QStyle.PM_SmallIconSize) + \
style.pixelMetric(QtGui.QStyle.PM_ButtonMargin)
return button_size
class FloatSlider(QtGui.QSlider):
valueChangedFloat = Signal(float)
def __init__(self, orientation, min_value, max_value, step, parent=None):
super().__init__(orientation, parent)
self.setScale(min_value, max_value, step)
self.valueChanged[int].connect(self.sendValue)
def update(self):
self.setSingleStep(1)
if self.min_value != self.max_value:
self.setEnabled(True)
self.setMinimum(int(self.min_value / self.step))
self.setMaximum(int(self.max_value / self.step))
else:
self.setEnabled(False)
def sendValue(self, slider_value):
value = min(max(slider_value * self.step, self.min_value),
self.max_value)
self.valueChangedFloat.emit(value)
def setValue(self, value):
super().setValue(value // self.step)
def setScale(self, minValue, maxValue, step=0):
if minValue >= maxValue:
## It would be more logical to disable the slider in this case
## (self.setEnabled(False))
## However, we do nothing to keep consistency with Qwt
# TODO If it's related to Qwt, remove it
return
if step <= 0 or step > (maxValue - minValue):
if isinstance(maxValue, int) and isinstance(minValue, int):
step = 1
else:
step = float(minValue - maxValue) / 100.0
self.min_value = float(minValue)
self.max_value = float(maxValue)
self.step = step
self.update()
def setRange(self, minValue, maxValue, step=1.0):
# For compatibility with qwtSlider
# TODO If it's related to Qwt, remove it
self.setScale(minValue, maxValue, step)<|fim▁end|> | for i, lab in enumerate(btnLabels): |
<|file_name|>zeroconf.go<|end_file_name|><|fim▁begin|>package main
import (
"fmt"
"log"
"os"
"strings"
"github.com/grandcat/zeroconf"
)<|fim▁hole|> zeroConfName = "Omxremote"
zeroconfService = "_omxremote._tcp"
zeroconfDomain = "local."
zeroconfPort = 8080
)
func startZeroConfAdvertisement(stop chan bool) {
hostname, err := os.Hostname()
if err == nil && hostname != "" {
zeroConfName = fmt.Sprintf("%s (%s)", zeroConfName, strings.Split(hostname, ".")[0])
}
log.Println("Starting zeroconf:", zeroConfName, zeroconfService, zeroconfPort)
defer log.Println("Zeroconf service terminated")
server, err := zeroconf.Register(
zeroConfName,
zeroconfService,
zeroconfDomain,
zeroconfPort,
[]string{"version=" + VERSION},
nil,
)
if err != nil {
log.Println("Zeroconf server error:", err)
return
}
defer server.Shutdown()
<-stop
}<|fim▁end|> |
var ( |
<|file_name|>streams.py<|end_file_name|><|fim▁begin|>from datetime import datetime
from django.contrib.contenttypes.models import ContentType
from actstream.managers import ActionManager, stream
class MyActionManager(ActionManager):<|fim▁hole|>
@stream
def testfoo(self, object, time=None):
if time is None:
time = datetime.now()
return object.actor_actions.filter(timestamp__lte = time)
@stream
def testbar(self, verb):
return self.filter(verb=verb)<|fim▁end|> | |
<|file_name|>voice.go<|end_file_name|><|fim▁begin|>package enums
import (
"encoding/json"
"fmt"
)
type VoiceType int
const (
VoiceType_FM VoiceType = iota
VoiceType_PCM
VoiceType_AL
)
func (t VoiceType) String() string {
s := "unknown"
switch t {
case 0:
s = "FM"
case 1:
s = "PCM"
case 2:
s = "AL"
}
return fmt.Sprintf("%s(%d)", s, t)
}
func (t VoiceType) MarshalJSON() ([]byte, error) {
return json.Marshal(t.String())
}
type Algorithm int
func (a Algorithm) String() string {
s := "unknown"
switch a {
case 0:
s = "FB(1)->2"
case 1:
s = "FB(1) + 2"
case 2:
s = "FB(1) + 2 + FB(3) + 4"
case 3:
s = "(FB(1) + 2->3) -> 4"
case 4:
s = "FB(1)->2->3->4"
case 5:
s = "FB(1)->2 + FB(3)->4"
case 6:
s = "FB(1) + 2->3->4"
case 7:
s = "FB(1) + 2->3 + 4"
}
return fmt.Sprintf("%d[ %s ]", int(a), s)
}
func (a Algorithm) OperatorCount() int {
if int(a) < 2 {
return 2
} else {
return 4
}
}
type BasicOctave int<|fim▁hole|> BasicOctave_Normal BasicOctave = 1
)
func (o BasicOctave) String() string {
switch o {
case 0:
return "1"
case 1:
return "0"
case 2:
return "-1"
case 3:
return "-2"
}
return "undefined"
}
func (o BasicOctave) NoteDiff() Note {
switch o {
case 0:
return Note(1 * 12)
case 2:
return Note(-1 * 12)
case 3:
return Note(-2 * 12)
default:
return Note(0 * 12)
}
}
type Panpot int
const (
Panpot_Center Panpot = 15
)
func (p Panpot) String() string {
v := int(p)
if v == 15 {
return "C"
} else if 0 <= v && v < 15 {
return fmt.Sprintf("L%d", 15-v)
} else if 15 < v && v < 32 {
return fmt.Sprintf("R%d", v-15)
} else {
return "undefined"
}
}
type Multiplier int
func (m Multiplier) String() string {
if m == 0 {
return "1/2"
} else {
return fmt.Sprintf("%d", m)
}
}<|fim▁end|> |
const ( |
<|file_name|>revisions_test.rs<|end_file_name|><|fim▁begin|>extern crate gitters;
use gitters::objects;
use gitters::revisions;
#[test]
fn full_sha1_resolves_to_self() {
assert_eq!(
Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())),
revisions::resolve("4ddb0025ef5914b51fb835495f5259a6d962df21"));
}
#[test]
fn partial_sha1_resolves_to_full_sha1_if_unambiguous() {
assert_eq!(
Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())),
revisions::resolve("4ddb0025e"));
}
#[test]<|fim▁hole|> revisions::resolve("d7698dd^^^"));
}
#[test]
fn ancestor_specification_resolves_to_ancestor_sha1() {
assert_eq!(
Ok(objects::Name("3e6a5d72d0ce0af8402c7d467d1b754b61b79d16".to_string())),
revisions::resolve("d7698dd~3"));
}
#[test]
fn branch_resolves_to_sha1() {
assert_eq!(
Ok(objects::Name("41cf28e8cac50f5cfeda40cfbfdd049763541c5a".to_string())),
revisions::resolve("introduce-tests"));
}
#[test]
fn invalid_revision_does_not_resolve() {
assert_eq!(
Err(revisions::Error::InvalidRevision),
revisions::resolve("invalid"));
}<|fim▁end|> | fn multiple_parent_specification_resolves_to_ancestor_sha1() {
assert_eq!(
Ok(objects::Name("3e6a5d72d0ce0af8402c7d467d1b754b61b79d16".to_string())), |
<|file_name|>source.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! Manages available sources of events for the main loop
use std::cell::RefCell;
use std::ops::DerefMut;
use std::mem::transmute;
use ffi::{gboolean, gpointer, g_idle_add_full, g_timeout_add_full, g_timeout_add_seconds_full};
use translate::ToGlib;
/// Return type of idle and timeout functions.
///
/// In the callback, return `Continue(true)` to continue scheduling the callback
/// in the main loop or `Continue(false)` to remove it from the main loop.
pub struct Continue(pub bool);
impl ToGlib for Continue {
type GlibType = gboolean;
#[inline]
fn to_glib(&self) -> gboolean {
self.0.to_glib()
}
}
// Box::into_raw stability workaround
unsafe fn into_raw<T>(b: Box<T>) -> *mut T { transmute(b) }
extern "C" fn trampoline(func: &RefCell<Box<FnMut() -> Continue + 'static>>) -> gboolean {
func.borrow_mut().deref_mut()().to_glib()
}
extern "C" fn destroy_closure(ptr: gpointer) {
unsafe {
// Box::from_raw API stability workaround
let ptr = ptr as *mut RefCell<Box<FnMut() -> Continue + 'static>>;
let _: Box<RefCell<Box<FnMut() -> Continue + 'static>>> = transmute(ptr);
}
}
const PRIORITY_DEFAULT: i32 = 0;
const PRIORITY_DEFAULT_IDLE: i32 = 200;
/// Adds a function to be called whenever there are no higher priority events pending to the default main loop.
///
/// The function is given the default idle priority, `PRIORITY_DEFAULT_IDLE`.
/// If the function returns `Continue(false)` it is automatically removed from
/// the list of event sources and will not be called again.
///
/// # Examples
///
/// ```ignore
/// let mut i = 0;
/// idle_add(move || {
/// println!("Idle: {}", i);
/// i += 1;
/// Continue(if i <= 10 { true } else { false })
/// });
/// ```
pub fn idle_add<F>(func: F) -> u32
where F: FnMut() -> Continue + 'static {
let f: Box<RefCell<Box<FnMut() -> Continue + 'static>>> = Box::new(RefCell::new(Box::new(func)));
unsafe {
g_idle_add_full(PRIORITY_DEFAULT_IDLE, transmute(trampoline),
into_raw(f) as gpointer, destroy_closure)
}
}
/// Sets a function to be called at regular intervals, with the default priority, `PRIORITY_DEFAULT`.
///
/// The function is called repeatedly until it returns `Continue(false)`, at which point the timeout is
/// automatically destroyed and the function will not be called again. The first call to the
/// function will be at the end of the first interval .
///
/// Note that timeout functions may be delayed, due to the processing of other event sources. Thus
/// they should not be relied on for precise timing. After each call to the timeout function, the
/// time of the next timeout is recalculated based on the current time and the given interval (it
/// does not try to 'catch up' time lost in delays).
///
/// If you want to have a timer in the "seconds" range and do not care about the exact time of the
/// first call of the timer, use the `timeout_add_seconds()` function; this function allows for more
/// optimizations and more efficient system power usage.
///
/// The interval given is in terms of monotonic time, not wall clock time.
/// See `g_get_monotonic_time()` in glib documentation.
///
/// # Examples
///
/// ```ignore
/// timeout_add(3000, || {
/// println!("This prints once every 3 seconds");
/// Continue(true)
/// });
/// ```
pub fn timeout_add<F>(interval: u32, func: F) -> u32
where F: FnMut() -> Continue + 'static {
let f: Box<RefCell<Box<FnMut() -> Continue + 'static>>> = Box::new(RefCell::new(Box::new(func)));
unsafe {
g_timeout_add_full(PRIORITY_DEFAULT, interval, transmute(trampoline),
into_raw(f) as gpointer, destroy_closure)
}
}
/// Sets a function to be called at regular intervals with the default priority, `PRIORITY_DEFAULT`.
///
/// The function is called repeatedly until it returns `Continue(false)`, at which point the timeout
/// is automatically destroyed and the function will not be called again.
///
/// Note that the first call of the timer may not be precise for timeouts of one second. If you need
/// finer precision and have such a timeout, you may want to use `timeout_add()` instead.
///
/// The interval given is in terms of monotonic time, not wall clock time.
/// See `g_get_monotonic_time()` in glib documentation.
///
/// # Examples
///
/// ```ignore
/// timeout_add_seconds(10, || {
/// println!("This prints once every 10 seconds");
/// Continue(true)
/// });
/// ```
pub fn timeout_add_seconds<F>(interval: u32, func: F) -> u32
where F: FnMut() -> Continue + 'static {
let f: Box<RefCell<Box<FnMut() -> Continue + 'static>>> = Box::new(RefCell::new(Box::new(func)));
unsafe {
g_timeout_add_seconds_full(PRIORITY_DEFAULT, interval, transmute(trampoline),
into_raw(f) as gpointer, destroy_closure)
}<|fim▁hole|><|fim▁end|> | } |
<|file_name|>cache_lru_test.go<|end_file_name|><|fim▁begin|>// Copyright 2015 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xorm
import (
"testing"
"github.com/go-xorm/core"
"github.com/stretchr/testify/assert"
)
func TestLRUCache(t *testing.T) {<|fim▁hole|> }
store := NewMemoryStore()
cacher := NewLRUCacher(store, 10000)
tableName := "cache_object1"
pks := []core.PK{
{1},
{2},
}
for _, pk := range pks {
sid, err := pk.ToString()
assert.NoError(t, err)
cacher.PutIds(tableName, "select * from cache_object1", sid)
ids := cacher.GetIds(tableName, "select * from cache_object1")
assert.EqualValues(t, sid, ids)
cacher.ClearIds(tableName)
ids2 := cacher.GetIds(tableName, "select * from cache_object1")
assert.Nil(t, ids2)
obj2 := cacher.GetBean(tableName, sid)
assert.Nil(t, obj2)
var obj = new(CacheObject1)
cacher.PutBean(tableName, sid, obj)
obj3 := cacher.GetBean(tableName, sid)
assert.EqualValues(t, obj, obj3)
cacher.DelBean(tableName, sid)
obj4 := cacher.GetBean(tableName, sid)
assert.Nil(t, obj4)
}
}<|fim▁end|> | type CacheObject1 struct {
Id int64 |
<|file_name|>impack_test.go<|end_file_name|><|fim▁begin|>// ImPack - CSS sprites maker
// Copyright (C) 2012 Dmitry Bratus
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package impack
import (
"image"
"math/rand"
"strconv"
"testing"
)
func TestArea(t *testing.T) {
r := image.Rect(0, 0, 10, 10)
a := area(r)
if a != 100 {
t.Errorf("Wrong area %d. Correct: 100.", a)
}
}
func TestAspectRatio(t *testing.T) {
r := image.Rect(0, 0, 120, 80)
ar := aspectRatio(r)
mustBe := float64(120) / 80
if ar != mustBe {
t.Errorf("Wrong aspect ratio %f. Correct: %f", ar, mustBe)
}
}
func TestIntersectAny(t *testing.T) {
rectsInt := []*image.Rectangle{
&image.Rectangle{image.Point{2, 1}, image.Point{4, 3}},
&image.Rectangle{image.Point{2, 4}, image.Point{4, 6}},
}
rectsNoInt := []*image.Rectangle{
&image.Rectangle{image.Point{5, 1}, image.Point{7, 4}},
&image.Rectangle{image.Point{5, 5}, image.Point{7, 6}},
}
r := image.Rect(1, 2, 3, 5)
if !intersectsAny(r, rectsInt, len(rectsInt)) {
t.Errorf("No intersection where must be.")
}
if intersectsAny(r, rectsNoInt, len(rectsNoInt)) {
t.Errorf("Intersection where must not be.")
}
}
<|fim▁hole|> out := make([]image.Rectangle, 8)
makePlacements(pivot, rect, out)
for i, r := range out {
t.Logf("%d: %s\n", i, r.String())
if r.Dx() != 2 || r.Dy() != 2 {
t.Errorf("Size of a placement is invalid.")
t.Fail()
}
if !pivot.Intersect(r).Empty() {
t.Errorf("Placement intersects the pivot.")
t.Fail()
}
}
}
func TestArrange(t *testing.T) {
rects := []image.Rectangle{
image.Rect(0, 0, 4, 12),
image.Rect(0, 0, 5, 15),
image.Rect(0, 0, 2, 6),
image.Rect(0, 0, 3, 9),
image.Rect(0, 0, 1, 3),
}
areas := []int{4 * 12, 5 * 15, 2 * 6, 3 * 9, 1 * 3}
union := Arrange(rects)
str := ""
for i := 0; i < union.Max.X; i++ {
for j := 0; j < union.Max.Y; j++ {
found := false
for k := 0; k < len(rects); k++ {
if !image.Rect(i, j, i+1, j+1).Intersect(rects[k]).Empty() {
str += strconv.Itoa(k)
found = true
break
}
}
if !found {
str += "X"
}
}
str += "\n"
}
t.Log(str)
for i, r := range rects {
if area(r) != areas[i] {
t.Errorf("Size of a placement is invalid.")
t.Fail()
}
}
}
func BenchmarkArrange(t *testing.B) {
rects := make([]image.Rectangle, 100)
minSize := 1
maxSize := 100
//Initializing random rectangles.
for i := 0; i < len(rects); i++ {
rects[i] = image.Rect(0, 0, minSize+int(rand.Float64()*float64(maxSize-minSize)), minSize+int(rand.Float64()*float64(maxSize-minSize)))
}
rectsWorking := make([]image.Rectangle, 100)
for i := 0; i < 100; i++ {
copy(rectsWorking, rects)
Arrange(rectsWorking)
}
}<|fim▁end|> | func TestMakePlacements(t *testing.T) {
pivot := image.Rect(3, 3, 6, 6)
rect := image.Rect(0, 0, 2, 2) |
<|file_name|>LoadableFragment.java<|end_file_name|><|fim▁begin|>package com.wangdaye.common.base.fragment;
import com.wangdaye.common.base.activity.LoadableActivity;
import java.util.List;
/**
* Loadable fragment.
* */
public abstract class LoadableFragment<T> extends MysplashFragment {
<|fim▁hole|> * */
public abstract List<T> loadMoreData(List<T> list, int headIndex, boolean headDirection);
}<|fim▁end|> | /**
* {@link LoadableActivity#loadMoreData(List, int, boolean)}. |
<|file_name|>send-message-suggested-action-dial.py<|end_file_name|><|fim▁begin|>## Copyright 2022 Google LLC
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## 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.
"""Sends a text mesage to the user with a suggestion action to dial a phone number.
Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#dial_action
This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""
import uuid
from businessmessages import businessmessages_v1_client as bm_client
from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest
from businessmessages.businessmessages_v1_messages import BusinessMessagesDialAction
from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage
from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative
from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestedAction
from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestion
from oauth2client.service_account import ServiceAccountCredentials
# Edit the values below:
path_to_service_account_key = './service_account_key.json'
conversation_id = 'EDIT_HERE'
credentials = ServiceAccountCredentials.from_json_keyfile_name(
path_to_service_account_key,
scopes=['https://www.googleapis.com/auth/businessmessages'])
client = bm_client.BusinessmessagesV1(credentials=credentials)
representative_type_as_string = 'BOT'
if representative_type_as_string == 'BOT':
representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT
else:
representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN
# Create a text message with a dial action and fallback text
message = BusinessMessagesMessage(
messageId=str(uuid.uuid4().int),
representative=BusinessMessagesRepresentative(<|fim▁hole|> representativeType=representative_type
),
text='Contact support for help with this issue.',
fallback='Give us a call at +12223334444.',
suggestions=[
BusinessMessagesSuggestion(
action=BusinessMessagesSuggestedAction(
text='Call support',
postbackData='call-support',
dialAction=BusinessMessagesDialAction(
phoneNumber='+12223334444'))
),
])
# Create the message request
create_request = BusinessmessagesConversationsMessagesCreateRequest(
businessMessagesMessage=message,
parent='conversations/' + conversation_id)
# Send the message
bm_client.BusinessmessagesV1.ConversationsMessagesService(
client=client).Create(request=create_request)<|fim▁end|> | |
<|file_name|>xdg.rs<|end_file_name|><|fim▁begin|>//! XDG Output advertising capabilities
//!
//! This protocol is meant for describing outputs in a way
//! which is more in line with the concept of an output on desktop oriented systems.
use std::{
ops::Deref as _,
sync::{Arc, Mutex},
};
use slog::{o, trace};
use wayland_protocols::unstable::xdg_output::v1::server::{
zxdg_output_manager_v1::{self, ZxdgOutputManagerV1},
zxdg_output_v1::ZxdgOutputV1,
};
use wayland_server::{protocol::wl_output::WlOutput, Display, Filter, Global, Main};
use crate::utils::{Logical, Physical, Point, Size};
use super::{Mode, Output};
#[derive(Debug)]
struct Inner {
name: String,
description: String,
logical_position: Point<i32, Logical>,
physical_size: Option<Size<i32, Physical>>,
scale: i32,
instances: Vec<ZxdgOutputV1>,
log: ::slog::Logger,
}
#[derive(Debug, Clone)]
pub(super) struct XdgOutput {
inner: Arc<Mutex<Inner>>,
}
impl XdgOutput {
fn new(output: &super::Inner, log: ::slog::Logger) -> Self {
trace!(log, "Creating new xdg_output"; "name" => &output.name);
let description = format!(
"{} - {} - {}",
output.physical.make, output.physical.model, output.name
);
let physical_size = output.current_mode.map(|mode| mode.size);
Self {
inner: Arc::new(Mutex::new(Inner {
name: output.name.clone(),
description,
logical_position: output.location,
physical_size,
scale: output.scale,
instances: Vec::new(),
log,
})),
}
}
fn add_instance(&self, xdg_output: Main<ZxdgOutputV1>, wl_output: &WlOutput) {
let mut inner = self.inner.lock().unwrap();
xdg_output.logical_position(inner.logical_position.x, inner.logical_position.y);
if let Some(size) = inner.physical_size {
let logical_size = size.to_logical(inner.scale);
xdg_output.logical_size(logical_size.w, logical_size.h);
}
if xdg_output.as_ref().version() >= 2 {
xdg_output.name(inner.name.clone());
xdg_output.description(inner.description.clone());
}
// xdg_output.done() is deprecated since version 3
if xdg_output.as_ref().version() < 3 {
xdg_output.done();
}
wl_output.done();
xdg_output.quick_assign(|_, _, _| {});
xdg_output.assign_destructor(Filter::new(|xdg_output: ZxdgOutputV1, _, _| {
let inner = &xdg_output.as_ref().user_data().get::<XdgOutput>().unwrap().inner;
inner
.lock()
.unwrap()
.instances
.retain(|o| !o.as_ref().equals(xdg_output.as_ref()));
}));
xdg_output.as_ref().user_data().set_threadsafe({
let xdg_output = self.clone();
move || xdg_output
});
inner.instances.push(xdg_output.deref().clone());
}
pub(super) fn change_current_state(
&self,
new_mode: Option<Mode>,
new_scale: Option<i32>,
new_location: Option<Point<i32, Logical>>,
) {
let mut output = self.inner.lock().unwrap();
if let Some(new_mode) = new_mode {
output.physical_size = Some(new_mode.size);
}
if let Some(new_scale) = new_scale {
output.scale = new_scale;
}
if let Some(new_location) = new_location {
output.logical_position = new_location;
}
for instance in output.instances.iter() {
if new_mode.is_some() | new_scale.is_some() {
if let Some(size) = output.physical_size {
let logical_size = size.to_logical(output.scale);
instance.logical_size(logical_size.w, logical_size.h);
}
}<|fim▁hole|> if new_location.is_some() {
instance.logical_position(output.logical_position.x, output.logical_position.y);
}
// xdg_output.done() is deprecated since version 3
if instance.as_ref().version() < 3 {
instance.done();
}
// No need for wl_output.done() here, it will be called by caller (super::Output::change_current_state)
}
}
}
/// Initialize a xdg output manager global.
pub fn init_xdg_output_manager<L>(display: &mut Display, logger: L) -> Global<ZxdgOutputManagerV1>
where
L: Into<Option<::slog::Logger>>,
{
let log = crate::slog_or_fallback(logger).new(o!("smithay_module" => "xdg_output_handler"));
display.create_global(
3,
Filter::new(move |(manager, _version): (Main<ZxdgOutputManagerV1>, _), _, _| {
let log = log.clone();
manager.quick_assign(move |_, req, _| match req {
zxdg_output_manager_v1::Request::GetXdgOutput {
id,
output: wl_output,
} => {
let output = Output::from_resource(&wl_output).unwrap();
let mut inner = output.inner.lock().unwrap();
if inner.xdg_output.is_none() {
inner.xdg_output = Some(XdgOutput::new(&inner, log.clone()));
}
inner.xdg_output.as_ref().unwrap().add_instance(id, &wl_output);
}
zxdg_output_manager_v1::Request::Destroy => {
// Nothing to do
}
_ => {}
});
}),
)
}<|fim▁end|> | |
<|file_name|>da.js<|end_file_name|><|fim▁begin|>videojs.addLanguage("da",{
"Play": "Afspil",
"Pause": "Pause",
"Current Time": "Aktuel tid",<|fim▁hole|> "Loaded": "Indlæst",
"Progress": "Status",
"Fullscreen": "Fuldskærm",
"Non-Fullscreen": "Luk fuldskærm",
"Mute": "Uden lyd",
"Unmuted": "Med lyd",
"Playback Rate": "Afspilningsrate",
"Subtitles": "Undertekster",
"subtitles off": "Uden undertekster",
"Captions": "Undertekster for hørehæmmede",
"captions off": "Uden undertekster for hørehæmmede",
"Chapters": "Kapitler",
"You aborted the video playback": "Du afbrød videoafspilningen.",
"A network error caused the video download to fail part-way.": "En netværksfejl fik download af videoen til at fejle.",
"The video could not be loaded, either because the server or network failed or because the format is not supported.": "Videoen kunne ikke indlæses, enten fordi serveren eller netværket fejlede, eller fordi formatet ikke er understøttet.",
"The video playback was aborted due to a corruption problem or because the video used features your browser did not support.": "Videoafspilningen blev afbrudt på grund af ødelagte data eller fordi videoen benyttede faciliteter som din browser ikke understøtter.",
"No compatible source was found for this video.": "Fandt ikke en kompatibel kilde for denne video."
});<|fim▁end|> | "Duration Time": "Varighed",
"Remaining Time": "Resterende tid",
"Stream Type": "Stream-type",
"LIVE": "LIVE", |
<|file_name|>helper.py<|end_file_name|><|fim▁begin|>import re
import os, sys
import json
import csv
import shutil
import ctypes
import logging
import datetime
import fileinput
import subprocess
import xml.etree.ElementTree as etree
DEFAULT_HELPER_PATH = "helper"
class Logger(object):
def __init__(self):
"""Init method
"""
self.terminal = sys.stdout
self.log = open("image-gen-logfile.log", "a")
def write(self, message):
"""Writes a log message
:param message:
:return:
"""
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S - ')
self.terminal.write(message)
self.log.write(message)
def flush(self):
"""Flushes a log message
:return:
"""
# this flush method is needed for python 3 compatibility.
# this handles the flush command by doing nothing.
pass
class helper(object):
@staticmethod
def executable_in_path(executable):
'''Returns the full path to an executable according to PATH,
otherwise None.'''
if os.name == 'nt':
return shutil.which('packer')
else:
path = os.environ.get('PATH')
if not path:
print >> sys.stderr, "Warning: No PATH could be searched"
paths = path.split(':')
for path in paths:
fullpath = os.path.join(path, executable)
if os.path.isfile(fullpath) and os.access(fullpath, os.X_OK):
return fullpath
return None
@staticmethod
def validate_argtype(arg, argtype):
"""Validates argument against given type
:param arg:
:param argtype:
:return:
"""
if not isinstance(arg, argtype):
raise HelperException('{0} argument must be of type {1}'.format(
arg, argtype))
return arg
@staticmethod
def get_guestos(os_string, os_arch, vm_provider):
"""Returns guest os type for a specific provider
:param os_string:
:param os_arch:
:param vm_provider:
:return:
"""
if "linux" in os_string.lower():
guestos = re.sub(r'\W+', ' ', re.sub(r'\d+', ' ', os_string)).strip()
if "windows" in os_string.lower():
guestos = os_string
if os_arch == '64':
guestos = guestos + "_" + str(os_arch)
guestos = guestos.replace(" ", "_")
data = ""
try:
guest_os_file = os.path.join(DEFAULT_HELPER_PATH, (vm_provider.lower() + '-guestos.json'))
with open(guest_os_file) as data_file:
data = json.load(data_file)
except (OSError, IOError) as ex:
print("error in opening packer template json file")
logging.error(ex.message)
print(str(ex.message))
assert isinstance(data, object)
if guestos in data:
return data[guestos]
elif "windows" in guestos.lower():
if os_arch == 32:
return data['Windows']
else:
return data['Windows_64']
elif "linux" in guestos.lower():
if os_arch == 32:
return data['Linux']
else:
return data['Linux_64']
@staticmethod
def run(cmd):
"""Runs a command
:param cmd: Command
:return: Execution status
"""
try:
'''
p = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(p.stdout.readline, ''):
print(line)
retval = p.wait()
return retval
'''
p = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1)
for line in iter(p.stdout.readline, b''):
print(line.rstrip().decode('utf-8')),
p.stdout.close()
p.wait()
#print(cmd)
#p = subprocess.run(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
#print('returncode:', p.returncode)
#print('{}'.format(p.stdout.decode('utf-8')))
except (subprocess.CalledProcessError, KeyboardInterrupt) as e:
print("Received keyboard interrupt, terminating the build process...")
'''
"""kill function for Win32"""
<|fim▁hole|>
logging.error("Error occured while running command {0}, Error: {1}".format(cmd, e.message))
raise subprocess.CalledProcessError
'''
@staticmethod
def SearchReplaceInFile(file, searchpattern, replacewith):
"""
:param file:
:param searchpattern:
:param replacewith:
:return:
"""
for line in fileinput.input(file, inplace=1):
if searchpattern in line:
line = line.replace(searchpattern, replacewith)
sys.stdout.write(line)
fileinput.close()
@staticmethod
def get_productkey(_dbms_query):
"""
:param _dbms_query:
:return:
"""
return " "
class HelperException(Exception):
"""Custom helper exception
"""
pass<|fim▁end|> | kernel32 = ctypes.windll.kernel32
handle = kernel32.OpenProcess(1, 0, p.pid)
return (0 != kernel32.TerminateProcess(handle, 0))
|
<|file_name|>_visible.py<|end_file_name|><|fim▁begin|>import _plotly_utils.basevalidators
class VisibleValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="visible", parent_name="heatmapgl", **kwargs):
super(VisibleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
role=kwargs.pop("role", "info"),<|fim▁hole|><|fim▁end|> | values=kwargs.pop("values", [True, False, "legendonly"]),
**kwargs
) |
<|file_name|>tracker_runner.go<|end_file_name|><|fim▁begin|>package builds
import (
"os"
"time"
"github.com/pivotal-golang/clock"
)
//go:generate counterfeiter . BuildTracker
type BuildTracker interface {
Track()
}
type TrackerRunner struct {
Tracker BuildTracker
Interval time.Duration
Clock clock.Clock
}
func (runner TrackerRunner) Run(signals <-chan os.Signal, ready chan<- struct{}) error {
ticker := runner.Clock.NewTicker(runner.Interval)
close(ready)
runner.Tracker.Track()<|fim▁hole|> for {
select {
case <-ticker.C():
runner.Tracker.Track()
case <-signals:
return nil
}
}
panic("unreachable")
}<|fim▁end|> | |
<|file_name|>mocks.ts<|end_file_name|><|fim▁begin|>import { MenuItem } from './menu-item-model'; //importo la classe MenuItem così posso usarla qui dentro
export const MENUITEMS: MenuItem[] = [ //esporto un oggetto costante di tipo MenuItem[] che si chiama MENUITEM che contiene
{ //tutte le proprietà degli item del menu di navigazione.
name: "Home",
description: "An overview page of my webapp",
path: "home"
},
{
name: "Trends",
description: "Some graphs about various things",
path: "trends"
},
{
name: "Controller",
description: "The button room",
path: "controller"
},
{
name: "Water Plant",
description: "This is where is represented the schema of the Water Treatement Plant; with heating, distributing, ecc.",<|fim▁hole|> },
{
name: "Docs",
description: "Home Docs Here!",
path: "docs"
}
]<|fim▁end|> | path: "waterplant" |
<|file_name|>clear_page_response.rs<|end_file_name|><|fim▁begin|>use azure_sdk_core::RequestId;
use chrono::{DateTime, Utc};
response_from_headers!(ClearPageResponse,
etag_from_headers -> etag: String,
last_modified_from_headers -> last_modified: DateTime<Utc>,
sequence_number_from_headers -> sequence_number: u64,
request_id_from_headers -> request_id: RequestId,<|fim▁hole|><|fim▁end|> | date_from_headers -> date: DateTime<Utc>
); |
<|file_name|>OptionalProcProvider.java<|end_file_name|><|fim▁begin|>/**
* Copyright (c) 2013, impossibl.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of impossibl.com nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.impossibl.postgres.system.procs;
/**
* Marker interface for dynamically loaded postgis data types, to be used by {@link ServiceLoader}.
*/
public interface OptionalProcProvider extends ProcProvider {<|fim▁hole|><|fim▁end|> | } |
<|file_name|>test_logdir.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
import apt_pkg
import logging
import os
import mock
import sys
import tempfile
import unittest
sys.path.insert(0, "..")
from unattended_upgrade import _setup_logging
class MockOptions:
dry_run = False
debug = False
class TestLogdir(unittest.TestCase):
def setUp(self):
self.tempdir = tempfile.mkdtemp()
apt_pkg.init()
self.mock_options = MockOptions()<|fim▁hole|> def test_logdir(self):
# test log
logdir = os.path.join(self.tempdir, "mylog")
apt_pkg.config.set("Unattended-Upgrade::LogDir", logdir)
logging.root.handlers = []
_setup_logging(self.mock_options)
self.assertTrue(os.path.exists(logdir))
def test_logdir_depreated(self):
# test if the deprecated APT::UnattendedUpgrades dir is not used
# if the new UnaUnattendedUpgrades::LogDir is given
logdir = os.path.join(self.tempdir, "mylog-use")
logdir2 = os.path.join(self.tempdir, "mylog-dontuse")
apt_pkg.config.set("Unattended-Upgrade::LogDir", logdir)
apt_pkg.config.set("APT::UnattendedUpgrades::LogDir", logdir2)
logging.root.handlers = []
_setup_logging(self.mock_options)
self.assertTrue(os.path.exists(logdir))
self.assertFalse(os.path.exists(logdir2))
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
unittest.main()<|fim▁end|> | |
<|file_name|>gtype.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2015, The Rust-GNOME Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! A numerical value which represents the unique identifier of a registered type.
// https://developer.gnome.org/gobject/unstable/gobject-Type-Information.html#GType
pub mod g_type {
use ffi;
use std::ffi::CString;
use std::slice;
use glib::translate::{FromGlibPtr, ToGlibPtr};
use glib_ffi::{self};
pub fn name(_type: glib_ffi::GType) -> Option<String> {
unsafe {
from_glib_none(ffi::g_type_name(_type))
}
}
pub fn from_name(name: &str) -> glib_ffi::GType {
unsafe {
ffi::g_type_from_name(name.to_glib_none().0)
}
}
pub fn parent(_type: glib_ffi::GType) -> glib_ffi::GType {
unsafe { ffi::g_type_parent(_type) }
}
pub fn depth(_type: glib_ffi::GType) -> u32 {
unsafe { ffi::g_type_depth(_type) }
}
pub fn next_base(leaf_type: glib_ffi::GType, root_type: glib_ffi::GType) -> glib_ffi::GType {
unsafe { ffi::g_type_next_base(leaf_type, root_type) }
}
<|fim▁hole|>
pub fn children(_type: glib_ffi::GType) -> Vec<glib_ffi::GType> {
let mut n_children = 0u32;
let tmp_vec = unsafe { ffi::g_type_children(_type, &mut n_children) };
if n_children == 0u32 || tmp_vec.is_null() {
Vec::new()
} else {
unsafe {
Vec::from(
slice::from_raw_parts(
tmp_vec as *const glib_ffi::GType,
n_children as usize))
}
}
}
pub fn interfaces(_type: glib_ffi::GType) -> Vec<glib_ffi::GType> {
let mut n_interfaces = 0u32;
let tmp_vec = unsafe { ffi::g_type_interfaces(_type, &mut n_interfaces) };
if n_interfaces == 0u32 || tmp_vec.is_null() {
Vec::new()
} else {
unsafe {
Vec::from(
slice::from_raw_parts(
tmp_vec as *const glib_ffi::GType,
n_interfaces as usize))
}
}
}
pub fn interface_prerequisites(interface_type: glib_ffi::GType) -> Vec<glib_ffi::GType> {
let mut n_prerequisites = 0u32;
let tmp_vec = unsafe { ffi::g_type_interface_prerequisites(interface_type, &mut n_prerequisites) };
if n_prerequisites == 0u32 || tmp_vec.is_null() {
Vec::new()
} else {
unsafe {
Vec::from(
slice::from_raw_parts(
tmp_vec as *const glib_ffi::GType, n_prerequisites as usize))
}
}
}
pub fn interface_add_prerequisite(interface_type: glib_ffi::GType, prerequisite_type: glib_ffi::GType) {
unsafe { ffi::g_type_interface_add_prerequisite(interface_type, prerequisite_type) }
}
pub fn fundamental_next() -> glib_ffi::GType {
unsafe { ffi::g_type_fundamental_next() }
}
pub fn fundamental(type_id: glib_ffi::GType) -> glib_ffi::GType {
unsafe { ffi::g_type_fundamental(type_id) }
}
pub fn ensure(_type: glib_ffi::GType) {
unsafe { ffi::g_type_ensure(_type) }
}
pub fn get_type_registration_serial() -> u32 {
unsafe { ffi::g_type_get_type_registration_serial() }
}
}<|fim▁end|> | pub fn is_a(_type: glib_ffi::GType, is_a_type: glib_ffi::GType) -> bool {
unsafe { to_bool(ffi::g_type_is_a(_type, is_a_type)) }
} |
<|file_name|>654121a84a33_.py<|end_file_name|><|fim▁begin|>"""Add Graph and GraphCache models
Revision ID: 654121a84a33
Revises: fc7bc5c66c63
Create Date: 2020-11-16 21:02:36.249989
"""
# revision identifiers, used by Alembic.
revision = '654121a84a33'
down_revision = 'fc7bc5c66c63'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('graph',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('sketch_id', sa.Integer(), nullable=True),
sa.Column('name', sa.UnicodeText(), nullable=True),
sa.Column('description', sa.UnicodeText(), nullable=True),
sa.Column('graph_config', sa.UnicodeText(), nullable=True),
sa.Column('graph_elements', sa.UnicodeText(), nullable=True),
sa.Column('graph_thumbnail', sa.UnicodeText(), nullable=True),
sa.Column('num_nodes', sa.Integer(), nullable=True),
sa.Column('num_edges', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['sketch_id'], ['sketch.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('graphcache',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('sketch_id', sa.Integer(), nullable=True),
sa.Column('graph_plugin', sa.UnicodeText(), nullable=True),
sa.Column('graph_config', sa.UnicodeText(), nullable=True),<|fim▁hole|> sa.PrimaryKeyConstraint('id')
)
op.create_table('graph_comment',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('comment', sa.UnicodeText(), nullable=True),
sa.Column('parent_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['parent_id'], ['graph.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('graph_label',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('label', sa.Unicode(length=255), nullable=True),
sa.Column('parent_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['parent_id'], ['graph.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('graph_label')
op.drop_table('graph_comment')
op.drop_table('graphcache')
op.drop_table('graph')
# ### end Alembic commands ###<|fim▁end|> | sa.Column('graph_elements', sa.UnicodeText(), nullable=True),
sa.Column('num_nodes', sa.Integer(), nullable=True),
sa.Column('num_edges', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['sketch_id'], ['sketch.id'], ), |
<|file_name|>startup.py<|end_file_name|><|fim▁begin|>"""
Module for code that should run during LMS startup
"""
# pylint: disable=unused-argument
from django.conf import settings
# Force settings to run so that the python path is modified
settings.INSTALLED_APPS # pylint: disable=pointless-statement
from openedx.core.lib.django_startup import autostartup
import edxmako
import logging
from monkey_patch import django_utils_translation
import analytics
log = logging.getLogger(__name__)
def run():
"""
Executed during django startup
"""
# Patch the xml libs.
from safe_lxml import defuse_xml_libs
defuse_xml_libs()
django_utils_translation.patch()
autostartup()
add_mimetypes()
if settings.FEATURES.get('USE_CUSTOM_THEME', False):
enable_theme()
if settings.FEATURES.get('USE_MICROSITES', False):
enable_microsites()
if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH', False):
enable_third_party_auth()
# Initialize Segment.io analytics module. Flushes first time a message is received and
# every 50 messages thereafter, or if 10 seconds have passed since last flush
if settings.FEATURES.get('SEGMENT_IO_LMS') and hasattr(settings, 'SEGMENT_IO_LMS_KEY'):
analytics.init(settings.SEGMENT_IO_LMS_KEY, flush_at=50)
def add_mimetypes():
"""
Add extra mimetypes. Used in xblock_resource.
If you add a mimetype here, be sure to also add it in cms/startup.py.
"""
import mimetypes
mimetypes.add_type('application/vnd.ms-fontobject', '.eot')
mimetypes.add_type('application/x-font-opentype', '.otf')
mimetypes.add_type('application/x-font-ttf', '.ttf')
mimetypes.add_type('application/font-woff', '.woff')
def enable_theme():
"""
Enable the settings for a custom theme, whose files should be stored
in ENV_ROOT/themes/THEME_NAME (e.g., edx_all/themes/stanford).
"""
# Workaround for setting THEME_NAME to an empty
# string which is the default due to this ansible
# bug: https://github.com/ansible/ansible/issues/4812
if settings.THEME_NAME == "":
settings.THEME_NAME = None
return
assert settings.FEATURES['USE_CUSTOM_THEME']
settings.FAVICON_PATH = 'themes/{name}/images/favicon.ico'.format(
name=settings.THEME_NAME
)
# Calculate the location of the theme's files
theme_root = settings.ENV_ROOT / "themes" / settings.THEME_NAME
# Include the theme's templates in the template search paths
settings.TEMPLATE_DIRS.insert(0, theme_root / 'templates')
edxmako.paths.add_lookup('main', theme_root / 'templates', prepend=True)
# Namespace the theme's static files to 'themes/<theme_name>' to
# avoid collisions with default edX static files
settings.STATICFILES_DIRS.append(
(u'themes/{}'.format(settings.THEME_NAME), theme_root / 'static')<|fim▁hole|> )
# Include theme locale path for django translations lookup
settings.LOCALE_PATHS = (theme_root / 'conf/locale',) + settings.LOCALE_PATHS
def enable_microsites():
"""
Enable the use of microsites, which are websites that allow
for subdomains for the edX platform, e.g. foo.edx.org
"""
microsites_root = settings.MICROSITE_ROOT_DIR
microsite_config_dict = settings.MICROSITE_CONFIGURATION
for ms_name, ms_config in microsite_config_dict.items():
# Calculate the location of the microsite's files
ms_root = microsites_root / ms_name
ms_config = microsite_config_dict[ms_name]
# pull in configuration information from each
# microsite root
if ms_root.isdir():
# store the path on disk for later use
ms_config['microsite_root'] = ms_root
template_dir = ms_root / 'templates'
ms_config['template_dir'] = template_dir
ms_config['microsite_name'] = ms_name
log.info('Loading microsite {0}'.format(ms_root))
else:
# not sure if we have application logging at this stage of
# startup
log.error('Error loading microsite {0}. Directory does not exist'.format(ms_root))
# remove from our configuration as it is not valid
del microsite_config_dict[ms_name]
# if we have any valid microsites defined, let's wire in the Mako and STATIC_FILES search paths
if microsite_config_dict:
settings.TEMPLATE_DIRS.append(microsites_root)
edxmako.paths.add_lookup('main', microsites_root)
settings.STATICFILES_DIRS.insert(0, microsites_root)
def enable_third_party_auth():
"""
Enable the use of third_party_auth, which allows users to sign in to edX
using other identity providers. For configuration details, see
common/djangoapps/third_party_auth/settings.py.
"""
from third_party_auth import settings as auth_settings
auth_settings.apply_settings(settings)<|fim▁end|> | |
<|file_name|>migration.go<|end_file_name|><|fim▁begin|>package core
import (
"database/sql"
"strconv"
)
//Migration represents migrations we will run up and down.
type Migration struct {
Identifier int64
Name string
Up func(tx *Tx)
Down func(tx *Tx)<|fim▁hole|>//GetID Returns a string representation of the migration identifier.
func (m *Migration) GetID() string {
return strconv.FormatInt(m.Identifier, 10)
}
//Pending returns if a particular migration is pending.
// TODO: move it to be vendor specific inside the managers.
func (m *Migration) Pending(db *sql.DB) bool {
rows, _ := db.Query("Select * from " + MigrationsTable + " WHERE identifier =" + m.GetID())
defer rows.Close()
count := 0
for rows.Next() {
count++
}
return count == 0
}
//ByIdentifier is a specific order that causes first-created migrations to run first based on the identifier.
type ByIdentifier []Migration
func (a ByIdentifier) Len() int { return len(a) }
func (a ByIdentifier) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByIdentifier) Less(i, j int) bool { return a[i].Identifier < a[j].Identifier }<|fim▁end|> | }
|
<|file_name|>circd.rs<|end_file_name|><|fim▁begin|>///////////////////////////////////////////////////////////////////////////////
#![feature(phase)]
extern crate circ_comms;
extern crate irc;
#[phase(plugin, link)] extern crate log;
extern crate time;
///////////////////////////////////////////////////////////////////////////////
use irc::data::config::Config;
use std::io::fs;
use std::io::net::pipe::UnixListener;
use std::io::{Listener, Acceptor};
use std::os;
use std::io::fs::PathExtensions;
mod connection;
mod irc_channel;
///////////////////////////////////////////////////////////////////////////////
fn process_args() -> Config
{
match os::args().tail()
{
[ref arg] =>
{
let filename = Path::new(arg.as_slice());
if !filename.exists()
{
panic!("File {} doesn't exist", arg);
}<|fim▁hole|> }
}
///////////////////////////////////////////////////////////////////////////////
fn main()
{
let config = process_args();
let connection = connection::Connection::new(config);
let socket = Path::new(circ_comms::address());
if socket.exists()
{
match fs::unlink(&socket)
{
Ok(_) => (),
Err(e) => panic!("Unable to remove {}: {}", circ_comms::address(), e)
}
}
let stream = UnixListener::bind(&socket);
for c in stream.listen().incoming()
{
let mut client = match c
{
Ok(x) => x,
Err(e) => { println!("Failed to get client: {}", e); continue }
};
let request = match circ_comms::read_request(&mut client)
{
Some(r) => r,
None => continue
};
match request
{
circ_comms::Request::ListChannels =>
circ_comms::write_response(&mut client,
connection.request_response(request)),
circ_comms::Request::GetStatus =>
circ_comms::write_response(&mut client,
connection.request_response(request)),
circ_comms::Request::GetMessages(_) =>
circ_comms::write_response(&mut client,
connection.request_response(request)),
circ_comms::Request::GetUsers(_) => (),
circ_comms::Request::Join(_) => connection.request(request),
circ_comms::Request::Part(_) => connection.request(request),
circ_comms::Request::SendMessage(_, _) => connection.request(request),
circ_comms::Request::Quit => {connection.request(request); break} // not a clean quit, but it works
}
}
}<|fim▁end|> |
Config::load(filename).unwrap()
},
_ => panic!("Configuration file must be specified") |
<|file_name|>gpu_mem_tracker.cpp<|end_file_name|><|fim▁begin|>#include "drape/utils/gpu_mem_tracker.hpp"
#include <iomanip>
#include <sstream>
namespace dp
{
std::string GPUMemTracker::GPUMemorySnapshot::ToString() const
{
std::ostringstream ss;
ss << " Summary Allocated = " << m_summaryAllocatedInMb << "Mb\n";
ss << " Summary Used = " << m_summaryUsedInMb << "Mb\n";
ss << " Tags registered = " << m_tagStats.size() << "\n";
for (auto const & it : m_tagStats)
{
ss << " Tag = " << it.first << " \n";
ss << " Object count = " << it.second.m_objectsCount << "\n";
ss << " Allocated = " << it.second.m_alocatedInMb << "Mb\n";
ss << " Used = " << it.second.m_usedInMb << "Mb\n";
}
ss << " Average allocations by hashes:\n";
for (auto const & it : m_averageAllocations)
{
ss << " " << std::hex << it.first;
ss << " : " << std::dec << it.second.GetAverage() << " bytes\n";
}
return ss.str();
}
GPUMemTracker & GPUMemTracker::Inst()
{
static GPUMemTracker s_inst;
return s_inst;
}
GPUMemTracker::GPUMemorySnapshot GPUMemTracker::GetMemorySnapshot()
{
GPUMemorySnapshot memStat;
{
std::lock_guard<std::mutex> g(m_mutex);
for (auto const & kv : m_memTracker)
{
TagMemorySnapshot & tagStat = memStat.m_tagStats[kv.first.first];
tagStat.m_objectsCount++;
tagStat.m_alocatedInMb += kv.second.first;
tagStat.m_usedInMb += kv.second.second;
memStat.m_summaryAllocatedInMb += kv.second.first;
memStat.m_summaryUsedInMb += kv.second.second;
}
memStat.m_averageAllocations = m_averageAllocations;
}
auto constexpr kByteToMb = static_cast<float>(1024 * 1024);
for (auto & it : memStat.m_tagStats)
{
it.second.m_alocatedInMb /= kByteToMb;
it.second.m_usedInMb /= kByteToMb;
}
memStat.m_summaryAllocatedInMb /= kByteToMb;
memStat.m_summaryUsedInMb /= kByteToMb;
return memStat;
}
void GPUMemTracker::AddAllocated(std::string const & tag, uint32_t id, uint32_t size)
{
std::lock_guard<std::mutex> g(m_mutex);
m_memTracker[make_pair(tag, id)].first = size;
}
void GPUMemTracker::SetUsed(std::string const & tag, uint32_t id, uint32_t size)
{
std::lock_guard<std::mutex> g(m_mutex);
TAlocUsedMem & node = m_memTracker[make_pair(tag, id)];
node.second = size;
ASSERT_LESS_OR_EQUAL(node.second, node.first, ("Can't use more than allocated"));
}
void GPUMemTracker::RemoveDeallocated(std::string const & tag, uint32_t id)
{
std::lock_guard<std::mutex> g(m_mutex);
m_memTracker.erase(make_pair(tag, id));
}
void GPUMemTracker::TrackAverageAllocation(uint64_t hash, uint64_t size)
{
uint32_t constexpr kBucketMask = 0x7;
std::lock_guard<std::mutex> g(m_mutex);
auto & allocation = m_averageAllocations[hash & kBucketMask];
allocation.m_totalSizeInBytes += size;<|fim▁hole|><|fim▁end|> | allocation.m_count++;
}
} // namespace dp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.