file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
test_determine_repository_should_use_local_repo.py | # -*- coding: utf-8 -*-
import os
from cookiecutter import repository, exceptions
import pytest
def test_finds_local_repo(tmpdir):
"""A valid local repository should be returned."""
project_dir = repository.determine_repo_dir(
'tests/fake-repo',
abbreviations={},
clone_to_dir=str(tmpdir),
checkout=None,
no_input=True
)
assert 'tests/fake-repo' == project_dir
def | (tmpdir):
"""A local repository without a cookiecutter.json should raise a
`RepositoryNotFound` exception.
"""
template_path = os.path.join('tests', 'fake-repo-bad')
with pytest.raises(exceptions.RepositoryNotFound) as err:
repository.determine_repo_dir(
template_path,
abbreviations={},
clone_to_dir=str(tmpdir),
checkout=None,
no_input=True
)
assert str(err.value) == (
'A valid repository for "{}" could not be found in the following '
'locations:\n{}'.format(
template_path,
'\n'.join([
template_path,
str(tmpdir / 'tests/fake-repo-bad')
]),
)
)
def test_local_repo_typo(tmpdir):
"""An unknown local repository should raise a `RepositoryNotFound`
exception.
"""
template_path = os.path.join('tests', 'unknown-repo')
with pytest.raises(exceptions.RepositoryNotFound) as err:
repository.determine_repo_dir(
template_path,
abbreviations={},
clone_to_dir=str(tmpdir),
checkout=None,
no_input=True
)
assert str(err.value) == (
'A valid repository for "{}" could not be found in the following '
'locations:\n{}'.format(
template_path,
'\n'.join([
template_path,
str(tmpdir / 'tests/unknown-repo')
]),
)
)
| test_local_repo_with_no_context_raises | identifier_name |
test_determine_repository_should_use_local_repo.py | # -*- coding: utf-8 -*-
import os
from cookiecutter import repository, exceptions
import pytest
def test_finds_local_repo(tmpdir):
"""A valid local repository should be returned."""
project_dir = repository.determine_repo_dir(
'tests/fake-repo',
abbreviations={},
clone_to_dir=str(tmpdir),
checkout=None,
no_input=True |
assert 'tests/fake-repo' == project_dir
def test_local_repo_with_no_context_raises(tmpdir):
"""A local repository without a cookiecutter.json should raise a
`RepositoryNotFound` exception.
"""
template_path = os.path.join('tests', 'fake-repo-bad')
with pytest.raises(exceptions.RepositoryNotFound) as err:
repository.determine_repo_dir(
template_path,
abbreviations={},
clone_to_dir=str(tmpdir),
checkout=None,
no_input=True
)
assert str(err.value) == (
'A valid repository for "{}" could not be found in the following '
'locations:\n{}'.format(
template_path,
'\n'.join([
template_path,
str(tmpdir / 'tests/fake-repo-bad')
]),
)
)
def test_local_repo_typo(tmpdir):
"""An unknown local repository should raise a `RepositoryNotFound`
exception.
"""
template_path = os.path.join('tests', 'unknown-repo')
with pytest.raises(exceptions.RepositoryNotFound) as err:
repository.determine_repo_dir(
template_path,
abbreviations={},
clone_to_dir=str(tmpdir),
checkout=None,
no_input=True
)
assert str(err.value) == (
'A valid repository for "{}" could not be found in the following '
'locations:\n{}'.format(
template_path,
'\n'.join([
template_path,
str(tmpdir / 'tests/unknown-repo')
]),
)
) | ) | random_line_split |
test_determine_repository_should_use_local_repo.py | # -*- coding: utf-8 -*-
import os
from cookiecutter import repository, exceptions
import pytest
def test_finds_local_repo(tmpdir):
"""A valid local repository should be returned."""
project_dir = repository.determine_repo_dir(
'tests/fake-repo',
abbreviations={},
clone_to_dir=str(tmpdir),
checkout=None,
no_input=True
)
assert 'tests/fake-repo' == project_dir
def test_local_repo_with_no_context_raises(tmpdir):
|
def test_local_repo_typo(tmpdir):
"""An unknown local repository should raise a `RepositoryNotFound`
exception.
"""
template_path = os.path.join('tests', 'unknown-repo')
with pytest.raises(exceptions.RepositoryNotFound) as err:
repository.determine_repo_dir(
template_path,
abbreviations={},
clone_to_dir=str(tmpdir),
checkout=None,
no_input=True
)
assert str(err.value) == (
'A valid repository for "{}" could not be found in the following '
'locations:\n{}'.format(
template_path,
'\n'.join([
template_path,
str(tmpdir / 'tests/unknown-repo')
]),
)
)
| """A local repository without a cookiecutter.json should raise a
`RepositoryNotFound` exception.
"""
template_path = os.path.join('tests', 'fake-repo-bad')
with pytest.raises(exceptions.RepositoryNotFound) as err:
repository.determine_repo_dir(
template_path,
abbreviations={},
clone_to_dir=str(tmpdir),
checkout=None,
no_input=True
)
assert str(err.value) == (
'A valid repository for "{}" could not be found in the following '
'locations:\n{}'.format(
template_path,
'\n'.join([
template_path,
str(tmpdir / 'tests/fake-repo-bad')
]),
)
) | identifier_body |
timeout.rs | // 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.
use libc::c_int;
use std::mem;
use std::rt::task::BlockedTask;
use std::rt::rtio::IoResult;
use access;
use homing::{HomeHandle, HomingMissile};
use timer::TimerWatcher;
use uvll;
use uvio::UvIoFactory;
use {Loop, UvError, uv_error_to_io_error, Request, wakeup};
use {UvHandle, wait_until_woken_after};
/// Management of a timeout when gaining access to a portion of a duplex stream.
pub struct AccessTimeout<T> {
state: TimeoutState,
timer: Option<Box<TimerWatcher>>,
pub access: access::Access<T>,
}
pub struct Guard<'a, T> {
state: &'a mut TimeoutState,
pub access: access::Guard<'a, T>,
pub can_timeout: bool,
}
#[deriving(PartialEq)]
enum TimeoutState {
NoTimeout,
TimeoutPending(ClientState),
TimedOut,
}
#[deriving(PartialEq)]
enum ClientState {
NoWaiter,
AccessPending,
RequestPending,
}
struct TimerContext {
timeout: *mut AccessTimeout<()>,
callback: fn(*mut AccessTimeout<()>, &TimerContext),
user_unblock: fn(uint) -> Option<BlockedTask>,
user_payload: uint,
}
impl<T: Send> AccessTimeout<T> {
pub fn new(data: T) -> AccessTimeout<T> {
AccessTimeout {
state: NoTimeout,
timer: None,
access: access::Access::new(data),
}
}
/// Grants access to half of a duplex stream, timing out if necessary.
///
/// On success, Ok(Guard) is returned and access has been granted to the
/// stream. If a timeout occurs, then Err is returned with an appropriate
/// error.
pub fn grant<'a>(&'a mut self, m: HomingMissile) -> IoResult<Guard<'a, T>> {
// First, flag that we're attempting to acquire access. This will allow
// us to cancel the pending grant if we timeout out while waiting for a
// grant.
match self.state {
NoTimeout => {},
TimeoutPending(ref mut client) => *client = AccessPending,
TimedOut => return Err(uv_error_to_io_error(UvError(uvll::ECANCELED)))
}
let access = self.access.grant(self as *mut _ as uint, m);
// After acquiring the grant, we need to flag ourselves as having a
// pending request so the timeout knows to cancel the request.
let can_timeout = match self.state {
NoTimeout => false,
TimeoutPending(ref mut client) => { *client = RequestPending; true }
TimedOut => return Err(uv_error_to_io_error(UvError(uvll::ECANCELED)))
};
Ok(Guard {
access: access,
state: &mut self.state,
can_timeout: can_timeout
})
}
pub fn timed_out(&self) -> bool {
match self.state {
TimedOut => true,
_ => false,
}
}
/// Sets the pending timeout to the value specified.
///
/// The home/loop variables are used to construct a timer if one has not
/// been previously constructed.
///
/// The callback will be invoked if the timeout elapses, and the data of
/// the time will be set to `data`.
pub fn set_timeout(&mut self, ms: Option<u64>,
home: &HomeHandle,
loop_: &Loop,
cb: fn(uint) -> Option<BlockedTask>,
data: uint) {
self.state = NoTimeout;
let ms = match ms {
Some(ms) => ms,
None => return match self.timer {
Some(ref mut t) => t.stop(),
None => {}
}
};
// If we have a timeout, lazily initialize the timer which will be used
// to fire when the timeout runs out.
if self.timer.is_none() {
let mut timer = box TimerWatcher::new_home(loop_, home.clone());
let mut cx = box TimerContext {
timeout: self as *mut _ as *mut AccessTimeout<()>,
callback: real_cb::<T>,
user_unblock: cb,
user_payload: data,
};
unsafe {
timer.set_data(&mut *cx);
mem::forget(cx);
}
self.timer = Some(timer);
}
let timer = self.timer.get_mut_ref();
unsafe {
let cx = uvll::get_data_for_uv_handle(timer.handle);
let cx = cx as *mut TimerContext;
(*cx).user_unblock = cb;
(*cx).user_payload = data;
}
timer.stop();
timer.start(timer_cb, ms, 0);
self.state = TimeoutPending(NoWaiter);
extern fn timer_cb(timer: *mut uvll::uv_timer_t) {
let cx: &TimerContext = unsafe {
&*(uvll::get_data_for_uv_handle(timer) as *const TimerContext)
};
(cx.callback)(cx.timeout, cx);
}
fn real_cb<T: Send>(timeout: *mut AccessTimeout<()>, cx: &TimerContext) {
let timeout = timeout as *mut AccessTimeout<T>;
let me = unsafe { &mut *timeout };
match mem::replace(&mut me.state, TimedOut) {
TimedOut | NoTimeout => unreachable!(),
TimeoutPending(NoWaiter) => {}
TimeoutPending(AccessPending) => {
match unsafe { me.access.dequeue(me as *mut _ as uint) } {
Some(task) => task.reawaken(),
None => unreachable!(),
}
}
TimeoutPending(RequestPending) => {
match (cx.user_unblock)(cx.user_payload) {
Some(task) => task.reawaken(),
None => unreachable!(),
}
}
}
}
}
}
impl<T: Send> Clone for AccessTimeout<T> {
fn clone(&self) -> AccessTimeout<T> {
AccessTimeout {
access: self.access.clone(),
state: NoTimeout,
timer: None,
}
}
}
#[unsafe_destructor]
impl<'a, T> Drop for Guard<'a, T> {
fn drop(&mut self) |
}
#[unsafe_destructor]
impl<T> Drop for AccessTimeout<T> {
fn drop(&mut self) {
match self.timer {
Some(ref timer) => unsafe {
let data = uvll::get_data_for_uv_handle(timer.handle);
let _data: Box<TimerContext> = mem::transmute(data);
},
None => {}
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Connect timeouts
////////////////////////////////////////////////////////////////////////////////
pub struct ConnectCtx {
pub status: c_int,
pub task: Option<BlockedTask>,
pub timer: Option<Box<TimerWatcher>>,
}
impl ConnectCtx {
pub fn connect<T>(
mut self, obj: T, timeout: Option<u64>, io: &mut UvIoFactory,
f: |&Request, &T, uvll::uv_connect_cb| -> c_int
) -> Result<T, UvError> {
let mut req = Request::new(uvll::UV_CONNECT);
let r = f(&req, &obj, connect_cb);
return match r {
0 => {
req.defuse(); // uv callback now owns this request
match timeout {
Some(t) => {
let mut timer = TimerWatcher::new(io);
timer.start(timer_cb, t, 0);
self.timer = Some(timer);
}
None => {}
}
wait_until_woken_after(&mut self.task, &io.loop_, || {
let data = &self as *const _ as *mut ConnectCtx;
match self.timer {
Some(ref mut timer) => unsafe { timer.set_data(data) },
None => {}
}
req.set_data(data);
});
// Make sure an erroneously fired callback doesn't have access
// to the context any more.
req.set_data(0 as *mut int);
// If we failed because of a timeout, drop the TcpWatcher as
// soon as possible because it's data is now set to null and we
// want to cancel the callback ASAP.
match self.status {
0 => Ok(obj),
n => { drop(obj); Err(UvError(n)) }
}
}
n => Err(UvError(n))
};
extern fn timer_cb(handle: *mut uvll::uv_timer_t) {
// Don't close the corresponding tcp request, just wake up the task
// and let RAII take care of the pending watcher.
let cx: &mut ConnectCtx = unsafe {
&mut *(uvll::get_data_for_uv_handle(handle) as *mut ConnectCtx)
};
cx.status = uvll::ECANCELED;
wakeup(&mut cx.task);
}
extern fn connect_cb(req: *mut uvll::uv_connect_t, status: c_int) {
// This callback can be invoked with ECANCELED if the watcher is
// closed by the timeout callback. In that case we just want to free
// the request and be along our merry way.
let req = Request::wrap(req);
if status == uvll::ECANCELED { return }
// Apparently on windows when the handle is closed this callback may
// not be invoked with ECANCELED but rather another error code.
// Either ways, if the data is null, then our timeout has expired
// and there's nothing we can do.
let data = unsafe { uvll::get_data_for_req(req.handle) };
if data.is_null() { return }
let cx: &mut ConnectCtx = unsafe { &mut *(data as *mut ConnectCtx) };
cx.status = status;
match cx.timer {
Some(ref mut t) => t.stop(),
None => {}
}
// Note that the timer callback doesn't cancel the connect request
// (that's the job of uv_close()), so it's possible for this
// callback to get triggered after the timeout callback fires, but
// before the task wakes up. In that case, we did indeed
// successfully connect, but we don't need to wake someone up. We
// updated the status above (correctly so), and the task will pick
// up on this when it wakes up.
if cx.task.is_some() {
wakeup(&mut cx.task);
}
}
}
}
pub struct AcceptTimeout<T> {
access: AccessTimeout<AcceptorState<T>>,
}
struct AcceptorState<T> {
blocked_acceptor: Option<BlockedTask>,
pending: Vec<IoResult<T>>,
}
impl<T: Send> AcceptTimeout<T> {
pub fn new() -> AcceptTimeout<T> {
AcceptTimeout {
access: AccessTimeout::new(AcceptorState {
blocked_acceptor: None,
pending: Vec::new(),
})
}
}
pub fn accept(&mut self,
missile: HomingMissile,
loop_: &Loop) -> IoResult<T> {
// If we've timed out but we're not closed yet, poll the state of the
// queue to see if we can peel off a connection.
if self.access.timed_out() && !self.access.access.is_closed(&missile) {
let tmp = self.access.access.get_mut(&missile);
return match tmp.pending.remove(0) {
Some(msg) => msg,
None => Err(uv_error_to_io_error(UvError(uvll::ECANCELED)))
}
}
// Now that we're not polling, attempt to gain access and then peel off
// a connection. If we have no pending connections, then we need to go
// to sleep and wait for one.
//
// Note that if we're woken up for a pending connection then we're
// guaranteed that the check above will not steal our connection due to
// the single-threaded nature of the event loop.
let mut guard = try!(self.access.grant(missile));
if guard.access.is_closed() {
return Err(uv_error_to_io_error(UvError(uvll::EOF)))
}
match guard.access.pending.remove(0) {
Some(msg) => return msg,
None => {}
}
wait_until_woken_after(&mut guard.access.blocked_acceptor, loop_, || {});
match guard.access.pending.remove(0) {
_ if guard.access.is_closed() => {
Err(uv_error_to_io_error(UvError(uvll::EOF)))
}
Some(msg) => msg,
None => Err(uv_error_to_io_error(UvError(uvll::ECANCELED)))
}
}
pub unsafe fn push(&mut self, t: IoResult<T>) {
let state = self.access.access.unsafe_get();
(*state).pending.push(t);
let _ = (*state).blocked_acceptor.take().map(|t| t.reawaken());
}
pub fn set_timeout(&mut self,
ms: Option<u64>,
loop_: &Loop,
home: &HomeHandle) {
self.access.set_timeout(ms, home, loop_, cancel_accept::<T>,
self as *mut _ as uint);
fn cancel_accept<T: Send>(me: uint) -> Option<BlockedTask> {
unsafe {
let me: &mut AcceptTimeout<T> = mem::transmute(me);
(*me.access.access.unsafe_get()).blocked_acceptor.take()
}
}
}
pub fn close(&mut self, m: HomingMissile) {
self.access.access.close(&m);
let task = self.access.access.get_mut(&m).blocked_acceptor.take();
drop(m);
let _ = task.map(|t| t.reawaken());
}
}
impl<T: Send> Clone for AcceptTimeout<T> {
fn clone(&self) -> AcceptTimeout<T> {
AcceptTimeout { access: self.access.clone() }
}
}
| {
match *self.state {
TimeoutPending(NoWaiter) | TimeoutPending(AccessPending) =>
unreachable!(),
NoTimeout | TimedOut => {}
TimeoutPending(RequestPending) => {
*self.state = TimeoutPending(NoWaiter);
}
}
} | identifier_body |
timeout.rs | // 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.
use libc::c_int;
use std::mem;
use std::rt::task::BlockedTask;
use std::rt::rtio::IoResult;
use access;
use homing::{HomeHandle, HomingMissile};
use timer::TimerWatcher;
use uvll;
use uvio::UvIoFactory;
use {Loop, UvError, uv_error_to_io_error, Request, wakeup};
use {UvHandle, wait_until_woken_after};
/// Management of a timeout when gaining access to a portion of a duplex stream.
pub struct AccessTimeout<T> {
state: TimeoutState,
timer: Option<Box<TimerWatcher>>,
pub access: access::Access<T>,
}
pub struct Guard<'a, T> {
state: &'a mut TimeoutState,
pub access: access::Guard<'a, T>,
pub can_timeout: bool,
}
#[deriving(PartialEq)]
enum TimeoutState {
NoTimeout,
TimeoutPending(ClientState),
TimedOut,
}
#[deriving(PartialEq)]
enum ClientState {
NoWaiter,
AccessPending,
RequestPending,
}
struct TimerContext {
timeout: *mut AccessTimeout<()>,
callback: fn(*mut AccessTimeout<()>, &TimerContext),
user_unblock: fn(uint) -> Option<BlockedTask>,
user_payload: uint,
}
impl<T: Send> AccessTimeout<T> {
pub fn new(data: T) -> AccessTimeout<T> {
AccessTimeout {
state: NoTimeout,
timer: None,
access: access::Access::new(data),
}
}
/// Grants access to half of a duplex stream, timing out if necessary.
///
/// On success, Ok(Guard) is returned and access has been granted to the
/// stream. If a timeout occurs, then Err is returned with an appropriate
/// error.
pub fn grant<'a>(&'a mut self, m: HomingMissile) -> IoResult<Guard<'a, T>> {
// First, flag that we're attempting to acquire access. This will allow
// us to cancel the pending grant if we timeout out while waiting for a
// grant.
match self.state {
NoTimeout => {},
TimeoutPending(ref mut client) => *client = AccessPending,
TimedOut => return Err(uv_error_to_io_error(UvError(uvll::ECANCELED)))
}
let access = self.access.grant(self as *mut _ as uint, m);
// After acquiring the grant, we need to flag ourselves as having a
// pending request so the timeout knows to cancel the request.
let can_timeout = match self.state {
NoTimeout => false,
TimeoutPending(ref mut client) => { *client = RequestPending; true }
TimedOut => return Err(uv_error_to_io_error(UvError(uvll::ECANCELED)))
};
Ok(Guard {
access: access,
state: &mut self.state,
can_timeout: can_timeout
})
}
pub fn timed_out(&self) -> bool {
match self.state {
TimedOut => true,
_ => false,
}
}
/// Sets the pending timeout to the value specified.
///
/// The home/loop variables are used to construct a timer if one has not
/// been previously constructed.
///
/// The callback will be invoked if the timeout elapses, and the data of
/// the time will be set to `data`.
pub fn set_timeout(&mut self, ms: Option<u64>,
home: &HomeHandle,
loop_: &Loop,
cb: fn(uint) -> Option<BlockedTask>,
data: uint) {
self.state = NoTimeout;
let ms = match ms {
Some(ms) => ms,
None => return match self.timer {
Some(ref mut t) => t.stop(),
None => {}
}
};
// If we have a timeout, lazily initialize the timer which will be used
// to fire when the timeout runs out.
if self.timer.is_none() {
let mut timer = box TimerWatcher::new_home(loop_, home.clone());
let mut cx = box TimerContext {
timeout: self as *mut _ as *mut AccessTimeout<()>,
callback: real_cb::<T>,
user_unblock: cb,
user_payload: data,
};
unsafe {
timer.set_data(&mut *cx);
mem::forget(cx);
}
self.timer = Some(timer);
}
let timer = self.timer.get_mut_ref();
unsafe {
let cx = uvll::get_data_for_uv_handle(timer.handle);
let cx = cx as *mut TimerContext;
(*cx).user_unblock = cb;
(*cx).user_payload = data;
}
timer.stop();
timer.start(timer_cb, ms, 0);
self.state = TimeoutPending(NoWaiter);
extern fn timer_cb(timer: *mut uvll::uv_timer_t) {
let cx: &TimerContext = unsafe {
&*(uvll::get_data_for_uv_handle(timer) as *const TimerContext)
};
(cx.callback)(cx.timeout, cx);
}
fn real_cb<T: Send>(timeout: *mut AccessTimeout<()>, cx: &TimerContext) {
let timeout = timeout as *mut AccessTimeout<T>;
let me = unsafe { &mut *timeout };
match mem::replace(&mut me.state, TimedOut) {
TimedOut | NoTimeout => unreachable!(),
TimeoutPending(NoWaiter) => {}
TimeoutPending(AccessPending) => {
match unsafe { me.access.dequeue(me as *mut _ as uint) } {
Some(task) => task.reawaken(),
None => unreachable!(),
}
}
TimeoutPending(RequestPending) => {
match (cx.user_unblock)(cx.user_payload) {
Some(task) => task.reawaken(),
None => unreachable!(),
}
}
}
}
}
}
impl<T: Send> Clone for AccessTimeout<T> {
fn clone(&self) -> AccessTimeout<T> {
AccessTimeout {
access: self.access.clone(),
state: NoTimeout,
timer: None,
}
}
}
#[unsafe_destructor]
impl<'a, T> Drop for Guard<'a, T> {
fn | (&mut self) {
match *self.state {
TimeoutPending(NoWaiter) | TimeoutPending(AccessPending) =>
unreachable!(),
NoTimeout | TimedOut => {}
TimeoutPending(RequestPending) => {
*self.state = TimeoutPending(NoWaiter);
}
}
}
}
#[unsafe_destructor]
impl<T> Drop for AccessTimeout<T> {
fn drop(&mut self) {
match self.timer {
Some(ref timer) => unsafe {
let data = uvll::get_data_for_uv_handle(timer.handle);
let _data: Box<TimerContext> = mem::transmute(data);
},
None => {}
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Connect timeouts
////////////////////////////////////////////////////////////////////////////////
pub struct ConnectCtx {
pub status: c_int,
pub task: Option<BlockedTask>,
pub timer: Option<Box<TimerWatcher>>,
}
impl ConnectCtx {
pub fn connect<T>(
mut self, obj: T, timeout: Option<u64>, io: &mut UvIoFactory,
f: |&Request, &T, uvll::uv_connect_cb| -> c_int
) -> Result<T, UvError> {
let mut req = Request::new(uvll::UV_CONNECT);
let r = f(&req, &obj, connect_cb);
return match r {
0 => {
req.defuse(); // uv callback now owns this request
match timeout {
Some(t) => {
let mut timer = TimerWatcher::new(io);
timer.start(timer_cb, t, 0);
self.timer = Some(timer);
}
None => {}
}
wait_until_woken_after(&mut self.task, &io.loop_, || {
let data = &self as *const _ as *mut ConnectCtx;
match self.timer {
Some(ref mut timer) => unsafe { timer.set_data(data) },
None => {}
}
req.set_data(data);
});
// Make sure an erroneously fired callback doesn't have access
// to the context any more.
req.set_data(0 as *mut int);
// If we failed because of a timeout, drop the TcpWatcher as
// soon as possible because it's data is now set to null and we
// want to cancel the callback ASAP.
match self.status {
0 => Ok(obj),
n => { drop(obj); Err(UvError(n)) }
}
}
n => Err(UvError(n))
};
extern fn timer_cb(handle: *mut uvll::uv_timer_t) {
// Don't close the corresponding tcp request, just wake up the task
// and let RAII take care of the pending watcher.
let cx: &mut ConnectCtx = unsafe {
&mut *(uvll::get_data_for_uv_handle(handle) as *mut ConnectCtx)
};
cx.status = uvll::ECANCELED;
wakeup(&mut cx.task);
}
extern fn connect_cb(req: *mut uvll::uv_connect_t, status: c_int) {
// This callback can be invoked with ECANCELED if the watcher is
// closed by the timeout callback. In that case we just want to free
// the request and be along our merry way.
let req = Request::wrap(req);
if status == uvll::ECANCELED { return }
// Apparently on windows when the handle is closed this callback may
// not be invoked with ECANCELED but rather another error code.
// Either ways, if the data is null, then our timeout has expired
// and there's nothing we can do.
let data = unsafe { uvll::get_data_for_req(req.handle) };
if data.is_null() { return }
let cx: &mut ConnectCtx = unsafe { &mut *(data as *mut ConnectCtx) };
cx.status = status;
match cx.timer {
Some(ref mut t) => t.stop(),
None => {}
}
// Note that the timer callback doesn't cancel the connect request
// (that's the job of uv_close()), so it's possible for this
// callback to get triggered after the timeout callback fires, but
// before the task wakes up. In that case, we did indeed
// successfully connect, but we don't need to wake someone up. We
// updated the status above (correctly so), and the task will pick
// up on this when it wakes up.
if cx.task.is_some() {
wakeup(&mut cx.task);
}
}
}
}
pub struct AcceptTimeout<T> {
access: AccessTimeout<AcceptorState<T>>,
}
struct AcceptorState<T> {
blocked_acceptor: Option<BlockedTask>,
pending: Vec<IoResult<T>>,
}
impl<T: Send> AcceptTimeout<T> {
pub fn new() -> AcceptTimeout<T> {
AcceptTimeout {
access: AccessTimeout::new(AcceptorState {
blocked_acceptor: None,
pending: Vec::new(),
})
}
}
pub fn accept(&mut self,
missile: HomingMissile,
loop_: &Loop) -> IoResult<T> {
// If we've timed out but we're not closed yet, poll the state of the
// queue to see if we can peel off a connection.
if self.access.timed_out() && !self.access.access.is_closed(&missile) {
let tmp = self.access.access.get_mut(&missile);
return match tmp.pending.remove(0) {
Some(msg) => msg,
None => Err(uv_error_to_io_error(UvError(uvll::ECANCELED)))
}
}
// Now that we're not polling, attempt to gain access and then peel off
// a connection. If we have no pending connections, then we need to go
// to sleep and wait for one.
//
// Note that if we're woken up for a pending connection then we're
// guaranteed that the check above will not steal our connection due to
// the single-threaded nature of the event loop.
let mut guard = try!(self.access.grant(missile));
if guard.access.is_closed() {
return Err(uv_error_to_io_error(UvError(uvll::EOF)))
}
match guard.access.pending.remove(0) {
Some(msg) => return msg,
None => {}
}
wait_until_woken_after(&mut guard.access.blocked_acceptor, loop_, || {});
match guard.access.pending.remove(0) {
_ if guard.access.is_closed() => {
Err(uv_error_to_io_error(UvError(uvll::EOF)))
}
Some(msg) => msg,
None => Err(uv_error_to_io_error(UvError(uvll::ECANCELED)))
}
}
pub unsafe fn push(&mut self, t: IoResult<T>) {
let state = self.access.access.unsafe_get();
(*state).pending.push(t);
let _ = (*state).blocked_acceptor.take().map(|t| t.reawaken());
}
pub fn set_timeout(&mut self,
ms: Option<u64>,
loop_: &Loop,
home: &HomeHandle) {
self.access.set_timeout(ms, home, loop_, cancel_accept::<T>,
self as *mut _ as uint);
fn cancel_accept<T: Send>(me: uint) -> Option<BlockedTask> {
unsafe {
let me: &mut AcceptTimeout<T> = mem::transmute(me);
(*me.access.access.unsafe_get()).blocked_acceptor.take()
}
}
}
pub fn close(&mut self, m: HomingMissile) {
self.access.access.close(&m);
let task = self.access.access.get_mut(&m).blocked_acceptor.take();
drop(m);
let _ = task.map(|t| t.reawaken());
}
}
impl<T: Send> Clone for AcceptTimeout<T> {
fn clone(&self) -> AcceptTimeout<T> {
AcceptTimeout { access: self.access.clone() }
}
}
| drop | identifier_name |
timeout.rs | // 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.
use libc::c_int;
use std::mem;
use std::rt::task::BlockedTask;
use std::rt::rtio::IoResult;
use access;
use homing::{HomeHandle, HomingMissile};
use timer::TimerWatcher;
use uvll;
use uvio::UvIoFactory;
use {Loop, UvError, uv_error_to_io_error, Request, wakeup};
use {UvHandle, wait_until_woken_after};
/// Management of a timeout when gaining access to a portion of a duplex stream.
pub struct AccessTimeout<T> {
state: TimeoutState,
timer: Option<Box<TimerWatcher>>,
pub access: access::Access<T>,
}
pub struct Guard<'a, T> {
state: &'a mut TimeoutState,
pub access: access::Guard<'a, T>,
pub can_timeout: bool,
}
#[deriving(PartialEq)]
enum TimeoutState {
NoTimeout,
TimeoutPending(ClientState),
TimedOut,
}
#[deriving(PartialEq)]
enum ClientState {
NoWaiter,
AccessPending,
RequestPending,
}
struct TimerContext {
timeout: *mut AccessTimeout<()>,
callback: fn(*mut AccessTimeout<()>, &TimerContext),
user_unblock: fn(uint) -> Option<BlockedTask>,
user_payload: uint,
}
impl<T: Send> AccessTimeout<T> {
pub fn new(data: T) -> AccessTimeout<T> {
AccessTimeout {
state: NoTimeout,
timer: None,
access: access::Access::new(data),
}
}
/// Grants access to half of a duplex stream, timing out if necessary.
///
/// On success, Ok(Guard) is returned and access has been granted to the
/// stream. If a timeout occurs, then Err is returned with an appropriate
/// error.
pub fn grant<'a>(&'a mut self, m: HomingMissile) -> IoResult<Guard<'a, T>> {
// First, flag that we're attempting to acquire access. This will allow
// us to cancel the pending grant if we timeout out while waiting for a
// grant.
match self.state {
NoTimeout => {},
TimeoutPending(ref mut client) => *client = AccessPending,
TimedOut => return Err(uv_error_to_io_error(UvError(uvll::ECANCELED)))
}
let access = self.access.grant(self as *mut _ as uint, m);
// After acquiring the grant, we need to flag ourselves as having a
// pending request so the timeout knows to cancel the request.
let can_timeout = match self.state {
NoTimeout => false,
TimeoutPending(ref mut client) => { *client = RequestPending; true }
TimedOut => return Err(uv_error_to_io_error(UvError(uvll::ECANCELED)))
};
Ok(Guard {
access: access,
state: &mut self.state,
can_timeout: can_timeout
})
}
pub fn timed_out(&self) -> bool {
match self.state {
TimedOut => true,
_ => false,
}
}
/// Sets the pending timeout to the value specified.
///
/// The home/loop variables are used to construct a timer if one has not
/// been previously constructed.
///
/// The callback will be invoked if the timeout elapses, and the data of
/// the time will be set to `data`.
pub fn set_timeout(&mut self, ms: Option<u64>,
home: &HomeHandle,
loop_: &Loop,
cb: fn(uint) -> Option<BlockedTask>,
data: uint) {
self.state = NoTimeout;
let ms = match ms {
Some(ms) => ms,
None => return match self.timer {
Some(ref mut t) => t.stop(),
None => {}
}
};
// If we have a timeout, lazily initialize the timer which will be used
// to fire when the timeout runs out.
if self.timer.is_none() {
let mut timer = box TimerWatcher::new_home(loop_, home.clone());
let mut cx = box TimerContext {
timeout: self as *mut _ as *mut AccessTimeout<()>,
callback: real_cb::<T>,
user_unblock: cb,
user_payload: data,
};
unsafe {
timer.set_data(&mut *cx);
mem::forget(cx);
}
self.timer = Some(timer);
}
let timer = self.timer.get_mut_ref();
unsafe {
let cx = uvll::get_data_for_uv_handle(timer.handle);
let cx = cx as *mut TimerContext;
(*cx).user_unblock = cb;
(*cx).user_payload = data;
}
timer.stop();
timer.start(timer_cb, ms, 0);
self.state = TimeoutPending(NoWaiter);
extern fn timer_cb(timer: *mut uvll::uv_timer_t) {
let cx: &TimerContext = unsafe {
&*(uvll::get_data_for_uv_handle(timer) as *const TimerContext)
};
(cx.callback)(cx.timeout, cx);
}
fn real_cb<T: Send>(timeout: *mut AccessTimeout<()>, cx: &TimerContext) {
let timeout = timeout as *mut AccessTimeout<T>;
let me = unsafe { &mut *timeout };
match mem::replace(&mut me.state, TimedOut) {
TimedOut | NoTimeout => unreachable!(),
TimeoutPending(NoWaiter) => {}
TimeoutPending(AccessPending) => {
match unsafe { me.access.dequeue(me as *mut _ as uint) } {
Some(task) => task.reawaken(),
None => unreachable!(),
}
}
TimeoutPending(RequestPending) => {
match (cx.user_unblock)(cx.user_payload) {
Some(task) => task.reawaken(),
None => unreachable!(),
}
}
}
}
}
}
impl<T: Send> Clone for AccessTimeout<T> {
fn clone(&self) -> AccessTimeout<T> {
AccessTimeout {
access: self.access.clone(),
state: NoTimeout,
timer: None,
}
}
}
#[unsafe_destructor]
impl<'a, T> Drop for Guard<'a, T> {
fn drop(&mut self) {
match *self.state {
TimeoutPending(NoWaiter) | TimeoutPending(AccessPending) =>
unreachable!(),
NoTimeout | TimedOut => {}
TimeoutPending(RequestPending) => {
*self.state = TimeoutPending(NoWaiter);
}
}
}
}
#[unsafe_destructor]
impl<T> Drop for AccessTimeout<T> {
fn drop(&mut self) { | match self.timer {
Some(ref timer) => unsafe {
let data = uvll::get_data_for_uv_handle(timer.handle);
let _data: Box<TimerContext> = mem::transmute(data);
},
None => {}
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Connect timeouts
////////////////////////////////////////////////////////////////////////////////
pub struct ConnectCtx {
pub status: c_int,
pub task: Option<BlockedTask>,
pub timer: Option<Box<TimerWatcher>>,
}
impl ConnectCtx {
pub fn connect<T>(
mut self, obj: T, timeout: Option<u64>, io: &mut UvIoFactory,
f: |&Request, &T, uvll::uv_connect_cb| -> c_int
) -> Result<T, UvError> {
let mut req = Request::new(uvll::UV_CONNECT);
let r = f(&req, &obj, connect_cb);
return match r {
0 => {
req.defuse(); // uv callback now owns this request
match timeout {
Some(t) => {
let mut timer = TimerWatcher::new(io);
timer.start(timer_cb, t, 0);
self.timer = Some(timer);
}
None => {}
}
wait_until_woken_after(&mut self.task, &io.loop_, || {
let data = &self as *const _ as *mut ConnectCtx;
match self.timer {
Some(ref mut timer) => unsafe { timer.set_data(data) },
None => {}
}
req.set_data(data);
});
// Make sure an erroneously fired callback doesn't have access
// to the context any more.
req.set_data(0 as *mut int);
// If we failed because of a timeout, drop the TcpWatcher as
// soon as possible because it's data is now set to null and we
// want to cancel the callback ASAP.
match self.status {
0 => Ok(obj),
n => { drop(obj); Err(UvError(n)) }
}
}
n => Err(UvError(n))
};
extern fn timer_cb(handle: *mut uvll::uv_timer_t) {
// Don't close the corresponding tcp request, just wake up the task
// and let RAII take care of the pending watcher.
let cx: &mut ConnectCtx = unsafe {
&mut *(uvll::get_data_for_uv_handle(handle) as *mut ConnectCtx)
};
cx.status = uvll::ECANCELED;
wakeup(&mut cx.task);
}
extern fn connect_cb(req: *mut uvll::uv_connect_t, status: c_int) {
// This callback can be invoked with ECANCELED if the watcher is
// closed by the timeout callback. In that case we just want to free
// the request and be along our merry way.
let req = Request::wrap(req);
if status == uvll::ECANCELED { return }
// Apparently on windows when the handle is closed this callback may
// not be invoked with ECANCELED but rather another error code.
// Either ways, if the data is null, then our timeout has expired
// and there's nothing we can do.
let data = unsafe { uvll::get_data_for_req(req.handle) };
if data.is_null() { return }
let cx: &mut ConnectCtx = unsafe { &mut *(data as *mut ConnectCtx) };
cx.status = status;
match cx.timer {
Some(ref mut t) => t.stop(),
None => {}
}
// Note that the timer callback doesn't cancel the connect request
// (that's the job of uv_close()), so it's possible for this
// callback to get triggered after the timeout callback fires, but
// before the task wakes up. In that case, we did indeed
// successfully connect, but we don't need to wake someone up. We
// updated the status above (correctly so), and the task will pick
// up on this when it wakes up.
if cx.task.is_some() {
wakeup(&mut cx.task);
}
}
}
}
pub struct AcceptTimeout<T> {
access: AccessTimeout<AcceptorState<T>>,
}
struct AcceptorState<T> {
blocked_acceptor: Option<BlockedTask>,
pending: Vec<IoResult<T>>,
}
impl<T: Send> AcceptTimeout<T> {
pub fn new() -> AcceptTimeout<T> {
AcceptTimeout {
access: AccessTimeout::new(AcceptorState {
blocked_acceptor: None,
pending: Vec::new(),
})
}
}
pub fn accept(&mut self,
missile: HomingMissile,
loop_: &Loop) -> IoResult<T> {
// If we've timed out but we're not closed yet, poll the state of the
// queue to see if we can peel off a connection.
if self.access.timed_out() && !self.access.access.is_closed(&missile) {
let tmp = self.access.access.get_mut(&missile);
return match tmp.pending.remove(0) {
Some(msg) => msg,
None => Err(uv_error_to_io_error(UvError(uvll::ECANCELED)))
}
}
// Now that we're not polling, attempt to gain access and then peel off
// a connection. If we have no pending connections, then we need to go
// to sleep and wait for one.
//
// Note that if we're woken up for a pending connection then we're
// guaranteed that the check above will not steal our connection due to
// the single-threaded nature of the event loop.
let mut guard = try!(self.access.grant(missile));
if guard.access.is_closed() {
return Err(uv_error_to_io_error(UvError(uvll::EOF)))
}
match guard.access.pending.remove(0) {
Some(msg) => return msg,
None => {}
}
wait_until_woken_after(&mut guard.access.blocked_acceptor, loop_, || {});
match guard.access.pending.remove(0) {
_ if guard.access.is_closed() => {
Err(uv_error_to_io_error(UvError(uvll::EOF)))
}
Some(msg) => msg,
None => Err(uv_error_to_io_error(UvError(uvll::ECANCELED)))
}
}
pub unsafe fn push(&mut self, t: IoResult<T>) {
let state = self.access.access.unsafe_get();
(*state).pending.push(t);
let _ = (*state).blocked_acceptor.take().map(|t| t.reawaken());
}
pub fn set_timeout(&mut self,
ms: Option<u64>,
loop_: &Loop,
home: &HomeHandle) {
self.access.set_timeout(ms, home, loop_, cancel_accept::<T>,
self as *mut _ as uint);
fn cancel_accept<T: Send>(me: uint) -> Option<BlockedTask> {
unsafe {
let me: &mut AcceptTimeout<T> = mem::transmute(me);
(*me.access.access.unsafe_get()).blocked_acceptor.take()
}
}
}
pub fn close(&mut self, m: HomingMissile) {
self.access.access.close(&m);
let task = self.access.access.get_mut(&m).blocked_acceptor.take();
drop(m);
let _ = task.map(|t| t.reawaken());
}
}
impl<T: Send> Clone for AcceptTimeout<T> {
fn clone(&self) -> AcceptTimeout<T> {
AcceptTimeout { access: self.access.clone() }
}
} | random_line_split | |
test.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: test.py
#
# Copyright 2018 Costas Tyfoxylos
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
import argparse
import logging
import json
import os
from bootstrap import bootstrap
from library import execute_command, tempdir
# This is the main prefix used for logging
LOGGER_BASENAME = '''_CI.test'''
LOGGER = logging.getLogger(LOGGER_BASENAME)
LOGGER.addHandler(logging.NullHandler())
def get_arguments():
parser = argparse.ArgumentParser(description='Accepts stages for testing')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--lint', help='Test the lint stage of the template', action='store_true')
group.add_argument('--test', help='Test the test stage of the template', action='store_true')
group.add_argument('--build', help='Test the build stage of the template', action='store_true')
group.add_argument('--document', help='Test the document stage of the template', action='store_true')
args = parser.parse_args()
return args
def _test(stage):
|
def test(stage):
emojize = bootstrap()
exit_code = _test(stage)
success = not exit_code
if success:
LOGGER.info('%s Tested stage "%s" successfully! %s',
emojize(':white_heavy_check_mark:'),
stage,
emojize(':thumbs_up:'))
else:
LOGGER.error('%s Errors found testing stage "%s"! %s',
emojize(':cross_mark:'),
stage,
emojize(':crying_face:'))
raise SystemExit(exit_code)
if __name__ == '__main__':
args = get_arguments()
stage = next((argument for argument in ('lint', 'test', 'build', 'document')
if getattr(args, argument)), None)
test(stage)
| from cookiecutter.main import cookiecutter
template = os.path.abspath('.')
context = os.path.abspath('cookiecutter.json')
with tempdir():
cookiecutter(template,
extra_context=json.loads(open(context).read()),
no_input=True)
os.chdir(os.listdir('.')[0])
del os.environ['PIPENV_PIPFILE']
return execute_command(os.path.join('_CI', 'scripts', f'{stage}.py')) | identifier_body |
test.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: test.py
#
# Copyright 2018 Costas Tyfoxylos
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
import argparse
import logging
import json
import os
from bootstrap import bootstrap
from library import execute_command, tempdir
# This is the main prefix used for logging
LOGGER_BASENAME = '''_CI.test'''
LOGGER = logging.getLogger(LOGGER_BASENAME)
LOGGER.addHandler(logging.NullHandler())
def get_arguments():
parser = argparse.ArgumentParser(description='Accepts stages for testing')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--lint', help='Test the lint stage of the template', action='store_true')
group.add_argument('--test', help='Test the test stage of the template', action='store_true')
group.add_argument('--build', help='Test the build stage of the template', action='store_true')
group.add_argument('--document', help='Test the document stage of the template', action='store_true')
args = parser.parse_args()
return args
def _test(stage):
from cookiecutter.main import cookiecutter
template = os.path.abspath('.')
context = os.path.abspath('cookiecutter.json')
with tempdir():
cookiecutter(template,
extra_context=json.loads(open(context).read()),
no_input=True)
os.chdir(os.listdir('.')[0])
del os.environ['PIPENV_PIPFILE']
return execute_command(os.path.join('_CI', 'scripts', f'{stage}.py'))
def | (stage):
emojize = bootstrap()
exit_code = _test(stage)
success = not exit_code
if success:
LOGGER.info('%s Tested stage "%s" successfully! %s',
emojize(':white_heavy_check_mark:'),
stage,
emojize(':thumbs_up:'))
else:
LOGGER.error('%s Errors found testing stage "%s"! %s',
emojize(':cross_mark:'),
stage,
emojize(':crying_face:'))
raise SystemExit(exit_code)
if __name__ == '__main__':
args = get_arguments()
stage = next((argument for argument in ('lint', 'test', 'build', 'document')
if getattr(args, argument)), None)
test(stage)
| test | identifier_name |
test.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: test.py
#
# Copyright 2018 Costas Tyfoxylos
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
import argparse
import logging
import json
import os
from bootstrap import bootstrap
from library import execute_command, tempdir
# This is the main prefix used for logging
LOGGER_BASENAME = '''_CI.test'''
LOGGER = logging.getLogger(LOGGER_BASENAME)
LOGGER.addHandler(logging.NullHandler())
def get_arguments():
parser = argparse.ArgumentParser(description='Accepts stages for testing')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--lint', help='Test the lint stage of the template', action='store_true')
group.add_argument('--test', help='Test the test stage of the template', action='store_true')
group.add_argument('--build', help='Test the build stage of the template', action='store_true')
group.add_argument('--document', help='Test the document stage of the template', action='store_true')
args = parser.parse_args()
return args
def _test(stage):
from cookiecutter.main import cookiecutter
template = os.path.abspath('.')
context = os.path.abspath('cookiecutter.json')
with tempdir():
cookiecutter(template,
extra_context=json.loads(open(context).read()),
no_input=True)
os.chdir(os.listdir('.')[0])
del os.environ['PIPENV_PIPFILE']
return execute_command(os.path.join('_CI', 'scripts', f'{stage}.py'))
def test(stage):
emojize = bootstrap()
exit_code = _test(stage)
success = not exit_code
if success:
LOGGER.info('%s Tested stage "%s" successfully! %s',
emojize(':white_heavy_check_mark:'),
stage,
emojize(':thumbs_up:'))
else:
LOGGER.error('%s Errors found testing stage "%s"! %s',
emojize(':cross_mark:'),
stage,
emojize(':crying_face:'))
raise SystemExit(exit_code)
if __name__ == '__main__':
| args = get_arguments()
stage = next((argument for argument in ('lint', 'test', 'build', 'document')
if getattr(args, argument)), None)
test(stage) | conditional_block | |
test.py | # File: test.py
#
# Copyright 2018 Costas Tyfoxylos
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
import argparse
import logging
import json
import os
from bootstrap import bootstrap
from library import execute_command, tempdir
# This is the main prefix used for logging
LOGGER_BASENAME = '''_CI.test'''
LOGGER = logging.getLogger(LOGGER_BASENAME)
LOGGER.addHandler(logging.NullHandler())
def get_arguments():
parser = argparse.ArgumentParser(description='Accepts stages for testing')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--lint', help='Test the lint stage of the template', action='store_true')
group.add_argument('--test', help='Test the test stage of the template', action='store_true')
group.add_argument('--build', help='Test the build stage of the template', action='store_true')
group.add_argument('--document', help='Test the document stage of the template', action='store_true')
args = parser.parse_args()
return args
def _test(stage):
from cookiecutter.main import cookiecutter
template = os.path.abspath('.')
context = os.path.abspath('cookiecutter.json')
with tempdir():
cookiecutter(template,
extra_context=json.loads(open(context).read()),
no_input=True)
os.chdir(os.listdir('.')[0])
del os.environ['PIPENV_PIPFILE']
return execute_command(os.path.join('_CI', 'scripts', f'{stage}.py'))
def test(stage):
emojize = bootstrap()
exit_code = _test(stage)
success = not exit_code
if success:
LOGGER.info('%s Tested stage "%s" successfully! %s',
emojize(':white_heavy_check_mark:'),
stage,
emojize(':thumbs_up:'))
else:
LOGGER.error('%s Errors found testing stage "%s"! %s',
emojize(':cross_mark:'),
stage,
emojize(':crying_face:'))
raise SystemExit(exit_code)
if __name__ == '__main__':
args = get_arguments()
stage = next((argument for argument in ('lint', 'test', 'build', 'document')
if getattr(args, argument)), None)
test(stage) | #!/usr/bin/env python
# -*- coding: utf-8 -*- | random_line_split | |
doc.py | # (c) 2014, James Tanner <tanner.jc@gmail.com>
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
# ansible-vault is a script that encrypts/decrypts YAML files. See
# http://docs.ansible.com/playbooks_vault.html for more details.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import datetime
import os
import traceback
import textwrap
from ansible.compat.six import iteritems, string_types
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleOptionsError
from ansible.plugins import module_loader, action_loader
from ansible.cli import CLI
from ansible.utils import module_docs
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
class DocCLI(CLI):
""" Vault command line class """
def __init__(self, args):
super(DocCLI, self).__init__(args)
self.module_list = []
def parse(self):
self.parser = CLI.base_parser(
usage='usage: %prog [options] [module...]',
epilog='Show Ansible module documentation',
module_opts=True,
)
self.parser.add_option("-l", "--list", action="store_true", default=False, dest='list_dir',
help='List available modules')
self.parser.add_option("-s", "--snippet", action="store_true", default=False, dest='show_snippet',
help='Show playbook snippet for specified module(s)')
self.parser.add_option("-a", "--all", action="store_true", default=False, dest='all_modules',
help='Show documentation for all modules')
super(DocCLI, self).parse()
display.verbosity = self.options.verbosity
def run(self):
super(DocCLI, self).run()
if self.options.module_path is not None:
for i in self.options.module_path.split(os.pathsep):
module_loader.add_directory(i)
# list modules
if self.options.list_dir:
paths = module_loader._get_paths()
for path in paths:
self.find_modules(path)
self.pager(self.get_module_list_text())
return 0
# process all modules
if self.options.all_modules:
paths = module_loader._get_paths()
for path in paths:
self.find_modules(path)
self.args = sorted(set(self.module_list) - module_docs.BLACKLIST_MODULES)
if len(self.args) == 0:
raise AnsibleOptionsError("Incorrect options passed")
# process command line module list
text = ''
for module in self.args:
try:
# if the module lives in a non-python file (eg, win_X.ps1), require the corresponding python file for docs
filename = module_loader.find_plugin(module, mod_type='.py')
if filename is None:
display.warning("module %s not found in %s\n" % (module, DocCLI.print_paths(module_loader)))
continue
if any(filename.endswith(x) for x in C.BLACKLIST_EXTS):
continue
try:
doc, plainexamples, returndocs, metadata = module_docs.get_docstring(filename, verbose=(self.options.verbosity > 0))
except:
display.vvv(traceback.format_exc())
display.error("module %s has a documentation error formatting or is missing documentation\nTo see exact traceback use -vvv" % module)
continue
if doc is not None:
# is there corresponding action plugin?
if module in action_loader:
doc['action'] = True
else:
doc['action'] = False
all_keys = []
for (k,v) in iteritems(doc['options']):
all_keys.append(k)
all_keys = sorted(all_keys)
doc['option_keys'] = all_keys
doc['filename'] = filename
doc['docuri'] = doc['module'].replace('_', '-')
doc['now_date'] = datetime.date.today().strftime('%Y-%m-%d')
doc['plainexamples'] = plainexamples
doc['returndocs'] = returndocs
doc['metadata'] = metadata
if self.options.show_snippet:
text += self.get_snippet_text(doc)
else:
text += self.get_man_text(doc)
else:
# this typically means we couldn't even parse the docstring, not just that the YAML is busted,
# probably a quoting issue.
raise AnsibleError("Parsing produced an empty object.")
except Exception as e:
display.vvv(traceback.format_exc())
raise AnsibleError("module %s missing documentation (or could not parse documentation): %s\n" % (module, str(e)))
if text:
self.pager(text)
return 0
def find_modules(self, path):
for module in os.listdir(path):
full_path = '/'.join([path, module])
if module.startswith('.'):
continue
elif os.path.isdir(full_path):
continue
elif any(module.endswith(x) for x in C.BLACKLIST_EXTS):
continue
elif module.startswith('__'):
continue
elif module in C.IGNORE_FILES:
continue
elif module.startswith('_'):
if os.path.islink(full_path): # avoids aliases
continue
module = os.path.splitext(module)[0] # removes the extension
module = module.lstrip('_') # remove underscore from deprecated modules
self.module_list.append(module)
def get_module_list_text(self):
columns = display.columns
displace = max(len(x) for x in self.module_list)
linelimit = columns - displace - 5
text = []
deprecated = []
for module in sorted(set(self.module_list)):
if module in module_docs.BLACKLIST_MODULES:
continue
# if the module lives in a non-python file (eg, win_X.ps1), require the corresponding python file for docs
filename = module_loader.find_plugin(module, mod_type='.py')
if filename is None:
continue
if filename.endswith(".ps1"):
continue
if os.path.isdir(filename):
continue
try:
doc, plainexamples, returndocs, metadata = module_docs.get_docstring(filename)
desc = self.tty_ify(doc.get('short_description', '?')).strip()
if len(desc) > linelimit:
desc = desc[:linelimit] + '...'
if module.startswith('_'): # Handle deprecated
deprecated.append("%-*s %-*.*s" % (displace, module[1:], linelimit, len(desc), desc))
else:
text.append("%-*s %-*.*s" % (displace, module, linelimit, len(desc), desc))
except:
raise AnsibleError("module %s has a documentation error formatting or is missing documentation\n" % module)
if len(deprecated) > 0:
text.append("\nDEPRECATED:")
text.extend(deprecated)
return "\n".join(text)
@staticmethod
def print_paths(finder):
''' Returns a string suitable for printing of the search path '''
# Uses a list to get the order right
ret = []
for i in finder._get_paths():
if i not in ret:
ret.append(i)
return os.pathsep.join(ret)
def get_snippet_text(self, doc):
text = []
desc = CLI.tty_ify(doc['short_description'])
text.append("- name: %s" % (desc))
text.append(" action: %s" % (doc['module']))
pad = 31
subdent = " " * pad
limit = display.columns - pad
for o in sorted(doc['options'].keys()):
opt = doc['options'][o]
desc = CLI.tty_ify(" ".join(opt['description']))
required = opt.get('required', False)
if not isinstance(required, bool):
raise("Incorrect value for 'Required', a boolean is needed.: %s" % required)
if required:
s = o + "="
else:
s = o
text.append(" %-20s # %s" % (s, textwrap.fill(desc, limit, subsequent_indent=subdent)))
text.append('')
return "\n".join(text)
def get_man_text(self, doc):
opt_indent=" "
text = []
text.append("> %s\n" % doc['module'].upper())
pad = display.columns * 0.20
limit = max(display.columns - int(pad), 70)
if isinstance(doc['description'], list):
desc = " ".join(doc['description'])
else:
desc = doc['description']
text.append("%s\n" % textwrap.fill(CLI.tty_ify(desc), limit, initial_indent=" ", subsequent_indent=" "))
# FUTURE: move deprecation to metadata-only
if 'deprecated' in doc and doc['deprecated'] is not None and len(doc['deprecated']) > 0:
text.append("DEPRECATED: \n%s\n" % doc['deprecated'])
metadata = doc['metadata']
supported_by = metadata['supported_by']
text.append("Supported by: %s\n" % supported_by)
status = metadata['status']
text.append("Status: %s\n" % ", ".join(status))
if 'action' in doc and doc['action']:
text.append(" * note: %s\n" % "This module has a corresponding action plugin.")
if 'option_keys' in doc and len(doc['option_keys']) > 0:
text.append("Options (= is mandatory):\n")
for o in sorted(doc['option_keys']):
opt = doc['options'][o]
required = opt.get('required', False)
if not isinstance(required, bool):
raise("Incorrect value for 'Required', a boolean is needed.: %s" % required)
if required:
opt_leadin = "="
else:
opt_leadin = "-"
text.append("%s %s" % (opt_leadin, o))
if isinstance(opt['description'], list):
for entry in opt['description']:
text.append(textwrap.fill(CLI.tty_ify(entry), limit, initial_indent=opt_indent, subsequent_indent=opt_indent))
else:
text.append(textwrap.fill(CLI.tty_ify(opt['description']), limit, initial_indent=opt_indent, subsequent_indent=opt_indent))
choices = ''
if 'choices' in opt:
choices = "(Choices: " + ", ".join(str(i) for i in opt['choices']) + ")"
default = ''
if 'default' in opt or not required:
default = "[Default: " + str(opt.get('default', '(null)')) + "]"
text.append(textwrap.fill(CLI.tty_ify(choices + default), limit, initial_indent=opt_indent, subsequent_indent=opt_indent))
if 'notes' in doc and doc['notes'] and len(doc['notes']) > 0:
text.append("Notes:")
for note in doc['notes']:
text.append(textwrap.fill(CLI.tty_ify(note), limit-6, initial_indent=" * ", subsequent_indent=opt_indent))
if 'requirements' in doc and doc['requirements'] is not None and len(doc['requirements']) > 0:
req = ", ".join(doc['requirements'])
text.append("Requirements:%s\n" % textwrap.fill(CLI.tty_ify(req), limit-16, initial_indent=" ", subsequent_indent=opt_indent))
if 'examples' in doc and len(doc['examples']) > 0:
text.append("Example%s:\n" % ('' if len(doc['examples']) < 2 else 's'))
for ex in doc['examples']:
text.append("%s\n" % (ex['code']))
if 'plainexamples' in doc and doc['plainexamples'] is not None:
text.append("EXAMPLES:")
text.append(doc['plainexamples'])
if 'returndocs' in doc and doc['returndocs'] is not None:
text.append("RETURN VALUES:")
text.append(doc['returndocs'])
text.append('')
maintainers = set()
if 'author' in doc:
if isinstance(doc['author'], string_types):
maintainers.add(doc['author'])
else: | maintainers.update(doc['author'])
if 'maintainers' in doc:
if isinstance(doc['maintainers'], string_types):
maintainers.add(doc['author'])
else:
maintainers.update(doc['author'])
text.append('MAINTAINERS: ' + ', '.join(maintainers))
text.append('')
return "\n".join(text) | random_line_split | |
doc.py | # (c) 2014, James Tanner <tanner.jc@gmail.com>
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
# ansible-vault is a script that encrypts/decrypts YAML files. See
# http://docs.ansible.com/playbooks_vault.html for more details.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import datetime
import os
import traceback
import textwrap
from ansible.compat.six import iteritems, string_types
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleOptionsError
from ansible.plugins import module_loader, action_loader
from ansible.cli import CLI
from ansible.utils import module_docs
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
class DocCLI(CLI):
""" Vault command line class """
def __init__(self, args):
super(DocCLI, self).__init__(args)
self.module_list = []
def parse(self):
self.parser = CLI.base_parser(
usage='usage: %prog [options] [module...]',
epilog='Show Ansible module documentation',
module_opts=True,
)
self.parser.add_option("-l", "--list", action="store_true", default=False, dest='list_dir',
help='List available modules')
self.parser.add_option("-s", "--snippet", action="store_true", default=False, dest='show_snippet',
help='Show playbook snippet for specified module(s)')
self.parser.add_option("-a", "--all", action="store_true", default=False, dest='all_modules',
help='Show documentation for all modules')
super(DocCLI, self).parse()
display.verbosity = self.options.verbosity
def run(self):
|
def find_modules(self, path):
for module in os.listdir(path):
full_path = '/'.join([path, module])
if module.startswith('.'):
continue
elif os.path.isdir(full_path):
continue
elif any(module.endswith(x) for x in C.BLACKLIST_EXTS):
continue
elif module.startswith('__'):
continue
elif module in C.IGNORE_FILES:
continue
elif module.startswith('_'):
if os.path.islink(full_path): # avoids aliases
continue
module = os.path.splitext(module)[0] # removes the extension
module = module.lstrip('_') # remove underscore from deprecated modules
self.module_list.append(module)
def get_module_list_text(self):
columns = display.columns
displace = max(len(x) for x in self.module_list)
linelimit = columns - displace - 5
text = []
deprecated = []
for module in sorted(set(self.module_list)):
if module in module_docs.BLACKLIST_MODULES:
continue
# if the module lives in a non-python file (eg, win_X.ps1), require the corresponding python file for docs
filename = module_loader.find_plugin(module, mod_type='.py')
if filename is None:
continue
if filename.endswith(".ps1"):
continue
if os.path.isdir(filename):
continue
try:
doc, plainexamples, returndocs, metadata = module_docs.get_docstring(filename)
desc = self.tty_ify(doc.get('short_description', '?')).strip()
if len(desc) > linelimit:
desc = desc[:linelimit] + '...'
if module.startswith('_'): # Handle deprecated
deprecated.append("%-*s %-*.*s" % (displace, module[1:], linelimit, len(desc), desc))
else:
text.append("%-*s %-*.*s" % (displace, module, linelimit, len(desc), desc))
except:
raise AnsibleError("module %s has a documentation error formatting or is missing documentation\n" % module)
if len(deprecated) > 0:
text.append("\nDEPRECATED:")
text.extend(deprecated)
return "\n".join(text)
@staticmethod
def print_paths(finder):
''' Returns a string suitable for printing of the search path '''
# Uses a list to get the order right
ret = []
for i in finder._get_paths():
if i not in ret:
ret.append(i)
return os.pathsep.join(ret)
def get_snippet_text(self, doc):
text = []
desc = CLI.tty_ify(doc['short_description'])
text.append("- name: %s" % (desc))
text.append(" action: %s" % (doc['module']))
pad = 31
subdent = " " * pad
limit = display.columns - pad
for o in sorted(doc['options'].keys()):
opt = doc['options'][o]
desc = CLI.tty_ify(" ".join(opt['description']))
required = opt.get('required', False)
if not isinstance(required, bool):
raise("Incorrect value for 'Required', a boolean is needed.: %s" % required)
if required:
s = o + "="
else:
s = o
text.append(" %-20s # %s" % (s, textwrap.fill(desc, limit, subsequent_indent=subdent)))
text.append('')
return "\n".join(text)
def get_man_text(self, doc):
opt_indent=" "
text = []
text.append("> %s\n" % doc['module'].upper())
pad = display.columns * 0.20
limit = max(display.columns - int(pad), 70)
if isinstance(doc['description'], list):
desc = " ".join(doc['description'])
else:
desc = doc['description']
text.append("%s\n" % textwrap.fill(CLI.tty_ify(desc), limit, initial_indent=" ", subsequent_indent=" "))
# FUTURE: move deprecation to metadata-only
if 'deprecated' in doc and doc['deprecated'] is not None and len(doc['deprecated']) > 0:
text.append("DEPRECATED: \n%s\n" % doc['deprecated'])
metadata = doc['metadata']
supported_by = metadata['supported_by']
text.append("Supported by: %s\n" % supported_by)
status = metadata['status']
text.append("Status: %s\n" % ", ".join(status))
if 'action' in doc and doc['action']:
text.append(" * note: %s\n" % "This module has a corresponding action plugin.")
if 'option_keys' in doc and len(doc['option_keys']) > 0:
text.append("Options (= is mandatory):\n")
for o in sorted(doc['option_keys']):
opt = doc['options'][o]
required = opt.get('required', False)
if not isinstance(required, bool):
raise("Incorrect value for 'Required', a boolean is needed.: %s" % required)
if required:
opt_leadin = "="
else:
opt_leadin = "-"
text.append("%s %s" % (opt_leadin, o))
if isinstance(opt['description'], list):
for entry in opt['description']:
text.append(textwrap.fill(CLI.tty_ify(entry), limit, initial_indent=opt_indent, subsequent_indent=opt_indent))
else:
text.append(textwrap.fill(CLI.tty_ify(opt['description']), limit, initial_indent=opt_indent, subsequent_indent=opt_indent))
choices = ''
if 'choices' in opt:
choices = "(Choices: " + ", ".join(str(i) for i in opt['choices']) + ")"
default = ''
if 'default' in opt or not required:
default = "[Default: " + str(opt.get('default', '(null)')) + "]"
text.append(textwrap.fill(CLI.tty_ify(choices + default), limit, initial_indent=opt_indent, subsequent_indent=opt_indent))
if 'notes' in doc and doc['notes'] and len(doc['notes']) > 0:
text.append("Notes:")
for note in doc['notes']:
text.append(textwrap.fill(CLI.tty_ify(note), limit-6, initial_indent=" * ", subsequent_indent=opt_indent))
if 'requirements' in doc and doc['requirements'] is not None and len(doc['requirements']) > 0:
req = ", ".join(doc['requirements'])
text.append("Requirements:%s\n" % textwrap.fill(CLI.tty_ify(req), limit-16, initial_indent=" ", subsequent_indent=opt_indent))
if 'examples' in doc and len(doc['examples']) > 0:
text.append("Example%s:\n" % ('' if len(doc['examples']) < 2 else 's'))
for ex in doc['examples']:
text.append("%s\n" % (ex['code']))
if 'plainexamples' in doc and doc['plainexamples'] is not None:
text.append("EXAMPLES:")
text.append(doc['plainexamples'])
if 'returndocs' in doc and doc['returndocs'] is not None:
text.append("RETURN VALUES:")
text.append(doc['returndocs'])
text.append('')
maintainers = set()
if 'author' in doc:
if isinstance(doc['author'], string_types):
maintainers.add(doc['author'])
else:
maintainers.update(doc['author'])
if 'maintainers' in doc:
if isinstance(doc['maintainers'], string_types):
maintainers.add(doc['author'])
else:
maintainers.update(doc['author'])
text.append('MAINTAINERS: ' + ', '.join(maintainers))
text.append('')
return "\n".join(text)
| super(DocCLI, self).run()
if self.options.module_path is not None:
for i in self.options.module_path.split(os.pathsep):
module_loader.add_directory(i)
# list modules
if self.options.list_dir:
paths = module_loader._get_paths()
for path in paths:
self.find_modules(path)
self.pager(self.get_module_list_text())
return 0
# process all modules
if self.options.all_modules:
paths = module_loader._get_paths()
for path in paths:
self.find_modules(path)
self.args = sorted(set(self.module_list) - module_docs.BLACKLIST_MODULES)
if len(self.args) == 0:
raise AnsibleOptionsError("Incorrect options passed")
# process command line module list
text = ''
for module in self.args:
try:
# if the module lives in a non-python file (eg, win_X.ps1), require the corresponding python file for docs
filename = module_loader.find_plugin(module, mod_type='.py')
if filename is None:
display.warning("module %s not found in %s\n" % (module, DocCLI.print_paths(module_loader)))
continue
if any(filename.endswith(x) for x in C.BLACKLIST_EXTS):
continue
try:
doc, plainexamples, returndocs, metadata = module_docs.get_docstring(filename, verbose=(self.options.verbosity > 0))
except:
display.vvv(traceback.format_exc())
display.error("module %s has a documentation error formatting or is missing documentation\nTo see exact traceback use -vvv" % module)
continue
if doc is not None:
# is there corresponding action plugin?
if module in action_loader:
doc['action'] = True
else:
doc['action'] = False
all_keys = []
for (k,v) in iteritems(doc['options']):
all_keys.append(k)
all_keys = sorted(all_keys)
doc['option_keys'] = all_keys
doc['filename'] = filename
doc['docuri'] = doc['module'].replace('_', '-')
doc['now_date'] = datetime.date.today().strftime('%Y-%m-%d')
doc['plainexamples'] = plainexamples
doc['returndocs'] = returndocs
doc['metadata'] = metadata
if self.options.show_snippet:
text += self.get_snippet_text(doc)
else:
text += self.get_man_text(doc)
else:
# this typically means we couldn't even parse the docstring, not just that the YAML is busted,
# probably a quoting issue.
raise AnsibleError("Parsing produced an empty object.")
except Exception as e:
display.vvv(traceback.format_exc())
raise AnsibleError("module %s missing documentation (or could not parse documentation): %s\n" % (module, str(e)))
if text:
self.pager(text)
return 0 | identifier_body |
doc.py | # (c) 2014, James Tanner <tanner.jc@gmail.com>
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
# ansible-vault is a script that encrypts/decrypts YAML files. See
# http://docs.ansible.com/playbooks_vault.html for more details.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import datetime
import os
import traceback
import textwrap
from ansible.compat.six import iteritems, string_types
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleOptionsError
from ansible.plugins import module_loader, action_loader
from ansible.cli import CLI
from ansible.utils import module_docs
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
class DocCLI(CLI):
""" Vault command line class """
def __init__(self, args):
super(DocCLI, self).__init__(args)
self.module_list = []
def parse(self):
self.parser = CLI.base_parser(
usage='usage: %prog [options] [module...]',
epilog='Show Ansible module documentation',
module_opts=True,
)
self.parser.add_option("-l", "--list", action="store_true", default=False, dest='list_dir',
help='List available modules')
self.parser.add_option("-s", "--snippet", action="store_true", default=False, dest='show_snippet',
help='Show playbook snippet for specified module(s)')
self.parser.add_option("-a", "--all", action="store_true", default=False, dest='all_modules',
help='Show documentation for all modules')
super(DocCLI, self).parse()
display.verbosity = self.options.verbosity
def run(self):
super(DocCLI, self).run()
if self.options.module_path is not None:
for i in self.options.module_path.split(os.pathsep):
module_loader.add_directory(i)
# list modules
if self.options.list_dir:
paths = module_loader._get_paths()
for path in paths:
self.find_modules(path)
self.pager(self.get_module_list_text())
return 0
# process all modules
if self.options.all_modules:
paths = module_loader._get_paths()
for path in paths:
self.find_modules(path)
self.args = sorted(set(self.module_list) - module_docs.BLACKLIST_MODULES)
if len(self.args) == 0:
raise AnsibleOptionsError("Incorrect options passed")
# process command line module list
text = ''
for module in self.args:
try:
# if the module lives in a non-python file (eg, win_X.ps1), require the corresponding python file for docs
filename = module_loader.find_plugin(module, mod_type='.py')
if filename is None:
display.warning("module %s not found in %s\n" % (module, DocCLI.print_paths(module_loader)))
continue
if any(filename.endswith(x) for x in C.BLACKLIST_EXTS):
continue
try:
doc, plainexamples, returndocs, metadata = module_docs.get_docstring(filename, verbose=(self.options.verbosity > 0))
except:
display.vvv(traceback.format_exc())
display.error("module %s has a documentation error formatting or is missing documentation\nTo see exact traceback use -vvv" % module)
continue
if doc is not None:
# is there corresponding action plugin?
if module in action_loader:
doc['action'] = True
else:
doc['action'] = False
all_keys = []
for (k,v) in iteritems(doc['options']):
all_keys.append(k)
all_keys = sorted(all_keys)
doc['option_keys'] = all_keys
doc['filename'] = filename
doc['docuri'] = doc['module'].replace('_', '-')
doc['now_date'] = datetime.date.today().strftime('%Y-%m-%d')
doc['plainexamples'] = plainexamples
doc['returndocs'] = returndocs
doc['metadata'] = metadata
if self.options.show_snippet:
text += self.get_snippet_text(doc)
else:
text += self.get_man_text(doc)
else:
# this typically means we couldn't even parse the docstring, not just that the YAML is busted,
# probably a quoting issue.
raise AnsibleError("Parsing produced an empty object.")
except Exception as e:
display.vvv(traceback.format_exc())
raise AnsibleError("module %s missing documentation (or could not parse documentation): %s\n" % (module, str(e)))
if text:
self.pager(text)
return 0
def find_modules(self, path):
for module in os.listdir(path):
full_path = '/'.join([path, module])
if module.startswith('.'):
continue
elif os.path.isdir(full_path):
continue
elif any(module.endswith(x) for x in C.BLACKLIST_EXTS):
continue
elif module.startswith('__'):
|
elif module in C.IGNORE_FILES:
continue
elif module.startswith('_'):
if os.path.islink(full_path): # avoids aliases
continue
module = os.path.splitext(module)[0] # removes the extension
module = module.lstrip('_') # remove underscore from deprecated modules
self.module_list.append(module)
def get_module_list_text(self):
columns = display.columns
displace = max(len(x) for x in self.module_list)
linelimit = columns - displace - 5
text = []
deprecated = []
for module in sorted(set(self.module_list)):
if module in module_docs.BLACKLIST_MODULES:
continue
# if the module lives in a non-python file (eg, win_X.ps1), require the corresponding python file for docs
filename = module_loader.find_plugin(module, mod_type='.py')
if filename is None:
continue
if filename.endswith(".ps1"):
continue
if os.path.isdir(filename):
continue
try:
doc, plainexamples, returndocs, metadata = module_docs.get_docstring(filename)
desc = self.tty_ify(doc.get('short_description', '?')).strip()
if len(desc) > linelimit:
desc = desc[:linelimit] + '...'
if module.startswith('_'): # Handle deprecated
deprecated.append("%-*s %-*.*s" % (displace, module[1:], linelimit, len(desc), desc))
else:
text.append("%-*s %-*.*s" % (displace, module, linelimit, len(desc), desc))
except:
raise AnsibleError("module %s has a documentation error formatting or is missing documentation\n" % module)
if len(deprecated) > 0:
text.append("\nDEPRECATED:")
text.extend(deprecated)
return "\n".join(text)
@staticmethod
def print_paths(finder):
''' Returns a string suitable for printing of the search path '''
# Uses a list to get the order right
ret = []
for i in finder._get_paths():
if i not in ret:
ret.append(i)
return os.pathsep.join(ret)
def get_snippet_text(self, doc):
text = []
desc = CLI.tty_ify(doc['short_description'])
text.append("- name: %s" % (desc))
text.append(" action: %s" % (doc['module']))
pad = 31
subdent = " " * pad
limit = display.columns - pad
for o in sorted(doc['options'].keys()):
opt = doc['options'][o]
desc = CLI.tty_ify(" ".join(opt['description']))
required = opt.get('required', False)
if not isinstance(required, bool):
raise("Incorrect value for 'Required', a boolean is needed.: %s" % required)
if required:
s = o + "="
else:
s = o
text.append(" %-20s # %s" % (s, textwrap.fill(desc, limit, subsequent_indent=subdent)))
text.append('')
return "\n".join(text)
def get_man_text(self, doc):
opt_indent=" "
text = []
text.append("> %s\n" % doc['module'].upper())
pad = display.columns * 0.20
limit = max(display.columns - int(pad), 70)
if isinstance(doc['description'], list):
desc = " ".join(doc['description'])
else:
desc = doc['description']
text.append("%s\n" % textwrap.fill(CLI.tty_ify(desc), limit, initial_indent=" ", subsequent_indent=" "))
# FUTURE: move deprecation to metadata-only
if 'deprecated' in doc and doc['deprecated'] is not None and len(doc['deprecated']) > 0:
text.append("DEPRECATED: \n%s\n" % doc['deprecated'])
metadata = doc['metadata']
supported_by = metadata['supported_by']
text.append("Supported by: %s\n" % supported_by)
status = metadata['status']
text.append("Status: %s\n" % ", ".join(status))
if 'action' in doc and doc['action']:
text.append(" * note: %s\n" % "This module has a corresponding action plugin.")
if 'option_keys' in doc and len(doc['option_keys']) > 0:
text.append("Options (= is mandatory):\n")
for o in sorted(doc['option_keys']):
opt = doc['options'][o]
required = opt.get('required', False)
if not isinstance(required, bool):
raise("Incorrect value for 'Required', a boolean is needed.: %s" % required)
if required:
opt_leadin = "="
else:
opt_leadin = "-"
text.append("%s %s" % (opt_leadin, o))
if isinstance(opt['description'], list):
for entry in opt['description']:
text.append(textwrap.fill(CLI.tty_ify(entry), limit, initial_indent=opt_indent, subsequent_indent=opt_indent))
else:
text.append(textwrap.fill(CLI.tty_ify(opt['description']), limit, initial_indent=opt_indent, subsequent_indent=opt_indent))
choices = ''
if 'choices' in opt:
choices = "(Choices: " + ", ".join(str(i) for i in opt['choices']) + ")"
default = ''
if 'default' in opt or not required:
default = "[Default: " + str(opt.get('default', '(null)')) + "]"
text.append(textwrap.fill(CLI.tty_ify(choices + default), limit, initial_indent=opt_indent, subsequent_indent=opt_indent))
if 'notes' in doc and doc['notes'] and len(doc['notes']) > 0:
text.append("Notes:")
for note in doc['notes']:
text.append(textwrap.fill(CLI.tty_ify(note), limit-6, initial_indent=" * ", subsequent_indent=opt_indent))
if 'requirements' in doc and doc['requirements'] is not None and len(doc['requirements']) > 0:
req = ", ".join(doc['requirements'])
text.append("Requirements:%s\n" % textwrap.fill(CLI.tty_ify(req), limit-16, initial_indent=" ", subsequent_indent=opt_indent))
if 'examples' in doc and len(doc['examples']) > 0:
text.append("Example%s:\n" % ('' if len(doc['examples']) < 2 else 's'))
for ex in doc['examples']:
text.append("%s\n" % (ex['code']))
if 'plainexamples' in doc and doc['plainexamples'] is not None:
text.append("EXAMPLES:")
text.append(doc['plainexamples'])
if 'returndocs' in doc and doc['returndocs'] is not None:
text.append("RETURN VALUES:")
text.append(doc['returndocs'])
text.append('')
maintainers = set()
if 'author' in doc:
if isinstance(doc['author'], string_types):
maintainers.add(doc['author'])
else:
maintainers.update(doc['author'])
if 'maintainers' in doc:
if isinstance(doc['maintainers'], string_types):
maintainers.add(doc['author'])
else:
maintainers.update(doc['author'])
text.append('MAINTAINERS: ' + ', '.join(maintainers))
text.append('')
return "\n".join(text)
| continue | conditional_block |
doc.py | # (c) 2014, James Tanner <tanner.jc@gmail.com>
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
# ansible-vault is a script that encrypts/decrypts YAML files. See
# http://docs.ansible.com/playbooks_vault.html for more details.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import datetime
import os
import traceback
import textwrap
from ansible.compat.six import iteritems, string_types
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleOptionsError
from ansible.plugins import module_loader, action_loader
from ansible.cli import CLI
from ansible.utils import module_docs
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
class DocCLI(CLI):
""" Vault command line class """
def __init__(self, args):
super(DocCLI, self).__init__(args)
self.module_list = []
def parse(self):
self.parser = CLI.base_parser(
usage='usage: %prog [options] [module...]',
epilog='Show Ansible module documentation',
module_opts=True,
)
self.parser.add_option("-l", "--list", action="store_true", default=False, dest='list_dir',
help='List available modules')
self.parser.add_option("-s", "--snippet", action="store_true", default=False, dest='show_snippet',
help='Show playbook snippet for specified module(s)')
self.parser.add_option("-a", "--all", action="store_true", default=False, dest='all_modules',
help='Show documentation for all modules')
super(DocCLI, self).parse()
display.verbosity = self.options.verbosity
def run(self):
super(DocCLI, self).run()
if self.options.module_path is not None:
for i in self.options.module_path.split(os.pathsep):
module_loader.add_directory(i)
# list modules
if self.options.list_dir:
paths = module_loader._get_paths()
for path in paths:
self.find_modules(path)
self.pager(self.get_module_list_text())
return 0
# process all modules
if self.options.all_modules:
paths = module_loader._get_paths()
for path in paths:
self.find_modules(path)
self.args = sorted(set(self.module_list) - module_docs.BLACKLIST_MODULES)
if len(self.args) == 0:
raise AnsibleOptionsError("Incorrect options passed")
# process command line module list
text = ''
for module in self.args:
try:
# if the module lives in a non-python file (eg, win_X.ps1), require the corresponding python file for docs
filename = module_loader.find_plugin(module, mod_type='.py')
if filename is None:
display.warning("module %s not found in %s\n" % (module, DocCLI.print_paths(module_loader)))
continue
if any(filename.endswith(x) for x in C.BLACKLIST_EXTS):
continue
try:
doc, plainexamples, returndocs, metadata = module_docs.get_docstring(filename, verbose=(self.options.verbosity > 0))
except:
display.vvv(traceback.format_exc())
display.error("module %s has a documentation error formatting or is missing documentation\nTo see exact traceback use -vvv" % module)
continue
if doc is not None:
# is there corresponding action plugin?
if module in action_loader:
doc['action'] = True
else:
doc['action'] = False
all_keys = []
for (k,v) in iteritems(doc['options']):
all_keys.append(k)
all_keys = sorted(all_keys)
doc['option_keys'] = all_keys
doc['filename'] = filename
doc['docuri'] = doc['module'].replace('_', '-')
doc['now_date'] = datetime.date.today().strftime('%Y-%m-%d')
doc['plainexamples'] = plainexamples
doc['returndocs'] = returndocs
doc['metadata'] = metadata
if self.options.show_snippet:
text += self.get_snippet_text(doc)
else:
text += self.get_man_text(doc)
else:
# this typically means we couldn't even parse the docstring, not just that the YAML is busted,
# probably a quoting issue.
raise AnsibleError("Parsing produced an empty object.")
except Exception as e:
display.vvv(traceback.format_exc())
raise AnsibleError("module %s missing documentation (or could not parse documentation): %s\n" % (module, str(e)))
if text:
self.pager(text)
return 0
def find_modules(self, path):
for module in os.listdir(path):
full_path = '/'.join([path, module])
if module.startswith('.'):
continue
elif os.path.isdir(full_path):
continue
elif any(module.endswith(x) for x in C.BLACKLIST_EXTS):
continue
elif module.startswith('__'):
continue
elif module in C.IGNORE_FILES:
continue
elif module.startswith('_'):
if os.path.islink(full_path): # avoids aliases
continue
module = os.path.splitext(module)[0] # removes the extension
module = module.lstrip('_') # remove underscore from deprecated modules
self.module_list.append(module)
def get_module_list_text(self):
columns = display.columns
displace = max(len(x) for x in self.module_list)
linelimit = columns - displace - 5
text = []
deprecated = []
for module in sorted(set(self.module_list)):
if module in module_docs.BLACKLIST_MODULES:
continue
# if the module lives in a non-python file (eg, win_X.ps1), require the corresponding python file for docs
filename = module_loader.find_plugin(module, mod_type='.py')
if filename is None:
continue
if filename.endswith(".ps1"):
continue
if os.path.isdir(filename):
continue
try:
doc, plainexamples, returndocs, metadata = module_docs.get_docstring(filename)
desc = self.tty_ify(doc.get('short_description', '?')).strip()
if len(desc) > linelimit:
desc = desc[:linelimit] + '...'
if module.startswith('_'): # Handle deprecated
deprecated.append("%-*s %-*.*s" % (displace, module[1:], linelimit, len(desc), desc))
else:
text.append("%-*s %-*.*s" % (displace, module, linelimit, len(desc), desc))
except:
raise AnsibleError("module %s has a documentation error formatting or is missing documentation\n" % module)
if len(deprecated) > 0:
text.append("\nDEPRECATED:")
text.extend(deprecated)
return "\n".join(text)
@staticmethod
def print_paths(finder):
''' Returns a string suitable for printing of the search path '''
# Uses a list to get the order right
ret = []
for i in finder._get_paths():
if i not in ret:
ret.append(i)
return os.pathsep.join(ret)
def get_snippet_text(self, doc):
text = []
desc = CLI.tty_ify(doc['short_description'])
text.append("- name: %s" % (desc))
text.append(" action: %s" % (doc['module']))
pad = 31
subdent = " " * pad
limit = display.columns - pad
for o in sorted(doc['options'].keys()):
opt = doc['options'][o]
desc = CLI.tty_ify(" ".join(opt['description']))
required = opt.get('required', False)
if not isinstance(required, bool):
raise("Incorrect value for 'Required', a boolean is needed.: %s" % required)
if required:
s = o + "="
else:
s = o
text.append(" %-20s # %s" % (s, textwrap.fill(desc, limit, subsequent_indent=subdent)))
text.append('')
return "\n".join(text)
def | (self, doc):
opt_indent=" "
text = []
text.append("> %s\n" % doc['module'].upper())
pad = display.columns * 0.20
limit = max(display.columns - int(pad), 70)
if isinstance(doc['description'], list):
desc = " ".join(doc['description'])
else:
desc = doc['description']
text.append("%s\n" % textwrap.fill(CLI.tty_ify(desc), limit, initial_indent=" ", subsequent_indent=" "))
# FUTURE: move deprecation to metadata-only
if 'deprecated' in doc and doc['deprecated'] is not None and len(doc['deprecated']) > 0:
text.append("DEPRECATED: \n%s\n" % doc['deprecated'])
metadata = doc['metadata']
supported_by = metadata['supported_by']
text.append("Supported by: %s\n" % supported_by)
status = metadata['status']
text.append("Status: %s\n" % ", ".join(status))
if 'action' in doc and doc['action']:
text.append(" * note: %s\n" % "This module has a corresponding action plugin.")
if 'option_keys' in doc and len(doc['option_keys']) > 0:
text.append("Options (= is mandatory):\n")
for o in sorted(doc['option_keys']):
opt = doc['options'][o]
required = opt.get('required', False)
if not isinstance(required, bool):
raise("Incorrect value for 'Required', a boolean is needed.: %s" % required)
if required:
opt_leadin = "="
else:
opt_leadin = "-"
text.append("%s %s" % (opt_leadin, o))
if isinstance(opt['description'], list):
for entry in opt['description']:
text.append(textwrap.fill(CLI.tty_ify(entry), limit, initial_indent=opt_indent, subsequent_indent=opt_indent))
else:
text.append(textwrap.fill(CLI.tty_ify(opt['description']), limit, initial_indent=opt_indent, subsequent_indent=opt_indent))
choices = ''
if 'choices' in opt:
choices = "(Choices: " + ", ".join(str(i) for i in opt['choices']) + ")"
default = ''
if 'default' in opt or not required:
default = "[Default: " + str(opt.get('default', '(null)')) + "]"
text.append(textwrap.fill(CLI.tty_ify(choices + default), limit, initial_indent=opt_indent, subsequent_indent=opt_indent))
if 'notes' in doc and doc['notes'] and len(doc['notes']) > 0:
text.append("Notes:")
for note in doc['notes']:
text.append(textwrap.fill(CLI.tty_ify(note), limit-6, initial_indent=" * ", subsequent_indent=opt_indent))
if 'requirements' in doc and doc['requirements'] is not None and len(doc['requirements']) > 0:
req = ", ".join(doc['requirements'])
text.append("Requirements:%s\n" % textwrap.fill(CLI.tty_ify(req), limit-16, initial_indent=" ", subsequent_indent=opt_indent))
if 'examples' in doc and len(doc['examples']) > 0:
text.append("Example%s:\n" % ('' if len(doc['examples']) < 2 else 's'))
for ex in doc['examples']:
text.append("%s\n" % (ex['code']))
if 'plainexamples' in doc and doc['plainexamples'] is not None:
text.append("EXAMPLES:")
text.append(doc['plainexamples'])
if 'returndocs' in doc and doc['returndocs'] is not None:
text.append("RETURN VALUES:")
text.append(doc['returndocs'])
text.append('')
maintainers = set()
if 'author' in doc:
if isinstance(doc['author'], string_types):
maintainers.add(doc['author'])
else:
maintainers.update(doc['author'])
if 'maintainers' in doc:
if isinstance(doc['maintainers'], string_types):
maintainers.add(doc['author'])
else:
maintainers.update(doc['author'])
text.append('MAINTAINERS: ' + ', '.join(maintainers))
text.append('')
return "\n".join(text)
| get_man_text | identifier_name |
q2_sigmoid.py | import numpy as np
def | (x):
"""
Compute the sigmoid function for the input here.
"""
x = 1. / (1. + np.exp(-x))
return x
def sigmoid_grad(f):
"""
Compute the gradient for the sigmoid function here. Note that
for this implementation, the input f should be the sigmoid
function value of your original input x.
"""
f = f * (1. - f)
return f
def test_sigmoid_basic():
"""
Some simple tests to get you started.
Warning: these are not exhaustive.
"""
print "Running basic tests..."
x = np.array([[1, 2], [-1, -2]])
f = sigmoid(x)
g = sigmoid_grad(f)
print f
assert np.amax(f - np.array([[0.73105858, 0.88079708],
[0.26894142, 0.11920292]])) <= 1e-6
print g
assert np.amax(g - np.array([[0.19661193, 0.10499359],
[0.19661193, 0.10499359]])) <= 1e-6
print "You should verify these results!\n"
def test_sigmoid():
"""
Use this space to test your sigmoid implementation by running:
python q2_sigmoid.py
This function will not be called by the autograder, nor will
your tests be graded.
"""
print "Running your tests..."
### YOUR CODE HERE
raise NotImplementedError
### END YOUR CODE
if __name__ == "__main__":
test_sigmoid_basic();
#test_sigmoid()
| sigmoid | identifier_name |
q2_sigmoid.py | import numpy as np
def sigmoid(x):
"""
Compute the sigmoid function for the input here.
"""
x = 1. / (1. + np.exp(-x))
return x
def sigmoid_grad(f):
|
def test_sigmoid_basic():
"""
Some simple tests to get you started.
Warning: these are not exhaustive.
"""
print "Running basic tests..."
x = np.array([[1, 2], [-1, -2]])
f = sigmoid(x)
g = sigmoid_grad(f)
print f
assert np.amax(f - np.array([[0.73105858, 0.88079708],
[0.26894142, 0.11920292]])) <= 1e-6
print g
assert np.amax(g - np.array([[0.19661193, 0.10499359],
[0.19661193, 0.10499359]])) <= 1e-6
print "You should verify these results!\n"
def test_sigmoid():
"""
Use this space to test your sigmoid implementation by running:
python q2_sigmoid.py
This function will not be called by the autograder, nor will
your tests be graded.
"""
print "Running your tests..."
### YOUR CODE HERE
raise NotImplementedError
### END YOUR CODE
if __name__ == "__main__":
test_sigmoid_basic();
#test_sigmoid()
| """
Compute the gradient for the sigmoid function here. Note that
for this implementation, the input f should be the sigmoid
function value of your original input x.
"""
f = f * (1. - f)
return f | identifier_body |
q2_sigmoid.py | import numpy as np
def sigmoid(x):
"""
Compute the sigmoid function for the input here.
"""
x = 1. / (1. + np.exp(-x))
return x
def sigmoid_grad(f):
"""
Compute the gradient for the sigmoid function here. Note that
for this implementation, the input f should be the sigmoid
function value of your original input x.
"""
f = f * (1. - f)
return f
def test_sigmoid_basic():
"""
Some simple tests to get you started.
Warning: these are not exhaustive.
"""
print "Running basic tests..."
x = np.array([[1, 2], [-1, -2]])
f = sigmoid(x)
g = sigmoid_grad(f)
print f
assert np.amax(f - np.array([[0.73105858, 0.88079708],
[0.26894142, 0.11920292]])) <= 1e-6
print g
assert np.amax(g - np.array([[0.19661193, 0.10499359],
[0.19661193, 0.10499359]])) <= 1e-6
print "You should verify these results!\n"
def test_sigmoid():
"""
Use this space to test your sigmoid implementation by running:
python q2_sigmoid.py
This function will not be called by the autograder, nor will
your tests be graded.
"""
print "Running your tests..."
### YOUR CODE HERE
raise NotImplementedError
### END YOUR CODE
if __name__ == "__main__":
| test_sigmoid_basic();
#test_sigmoid() | conditional_block | |
q2_sigmoid.py | import numpy as np
def sigmoid(x):
"""
Compute the sigmoid function for the input here.
"""
x = 1. / (1. + np.exp(-x))
return x
def sigmoid_grad(f):
"""
Compute the gradient for the sigmoid function here. Note that
for this implementation, the input f should be the sigmoid
function value of your original input x.
"""
f = f * (1. - f)
return f
def test_sigmoid_basic():
"""
Some simple tests to get you started.
Warning: these are not exhaustive.
"""
print "Running basic tests..."
x = np.array([[1, 2], [-1, -2]])
f = sigmoid(x)
g = sigmoid_grad(f)
print f
assert np.amax(f - np.array([[0.73105858, 0.88079708],
[0.26894142, 0.11920292]])) <= 1e-6
print g
assert np.amax(g - np.array([[0.19661193, 0.10499359],
[0.19661193, 0.10499359]])) <= 1e-6
print "You should verify these results!\n"
def test_sigmoid():
"""
Use this space to test your sigmoid implementation by running:
python q2_sigmoid.py
This function will not be called by the autograder, nor will
your tests be graded.
"""
print "Running your tests..."
### YOUR CODE HERE
raise NotImplementedError
### END YOUR CODE
if __name__ == "__main__":
test_sigmoid_basic(); | #test_sigmoid() | random_line_split | |
views.py | # -*- coding: utf-8 -*-
#
# Copyright 2015, Foxugly. All rights reserved.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
from patient.models import Patient
from django.http import HttpResponse
import json
from agenda.models import Slot
from django.shortcuts import render
from django.shortcuts import get_object_or_404
def search_patient(request):
if request.is_ajax():
email = request.GET['email']
if len(email) > 5:
p = Patient.objects.filter(email=email)
if len(p):
return HttpResponse(json.dumps({'return': True, 'patient': p[0].as_json()}))
else:
return HttpResponse(json.dumps({'return': False}))
else:
return HttpResponse(json.dumps({'return': False}))
def | (request, patient_id, text):
p = get_object_or_404(Patient, id=patient_id, confirm=text)
if p:
p.active = True
p.confirm = None
p.save()
return render(request, 'valid.tpl')
def confirm_remove(request, patient_id, slot_id):
s = get_object_or_404(Slot, id=slot_id, patient__id=patient_id)
# s = Slot.objects.get(id=slot_id, patient__id=patient_id)
# TODO SEND MAIL PATIENT_REMOVE_BOOKING
s.clean_slot()
s.save()
return render(request, 'valid.tpl')
| confirm_create | identifier_name |
views.py | # -*- coding: utf-8 -*-
#
# Copyright 2015, Foxugly. All rights reserved.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
from patient.models import Patient
from django.http import HttpResponse |
def search_patient(request):
if request.is_ajax():
email = request.GET['email']
if len(email) > 5:
p = Patient.objects.filter(email=email)
if len(p):
return HttpResponse(json.dumps({'return': True, 'patient': p[0].as_json()}))
else:
return HttpResponse(json.dumps({'return': False}))
else:
return HttpResponse(json.dumps({'return': False}))
def confirm_create(request, patient_id, text):
p = get_object_or_404(Patient, id=patient_id, confirm=text)
if p:
p.active = True
p.confirm = None
p.save()
return render(request, 'valid.tpl')
def confirm_remove(request, patient_id, slot_id):
s = get_object_or_404(Slot, id=slot_id, patient__id=patient_id)
# s = Slot.objects.get(id=slot_id, patient__id=patient_id)
# TODO SEND MAIL PATIENT_REMOVE_BOOKING
s.clean_slot()
s.save()
return render(request, 'valid.tpl') | import json
from agenda.models import Slot
from django.shortcuts import render
from django.shortcuts import get_object_or_404
| random_line_split |
views.py | # -*- coding: utf-8 -*-
#
# Copyright 2015, Foxugly. All rights reserved.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
from patient.models import Patient
from django.http import HttpResponse
import json
from agenda.models import Slot
from django.shortcuts import render
from django.shortcuts import get_object_or_404
def search_patient(request):
if request.is_ajax():
|
def confirm_create(request, patient_id, text):
p = get_object_or_404(Patient, id=patient_id, confirm=text)
if p:
p.active = True
p.confirm = None
p.save()
return render(request, 'valid.tpl')
def confirm_remove(request, patient_id, slot_id):
s = get_object_or_404(Slot, id=slot_id, patient__id=patient_id)
# s = Slot.objects.get(id=slot_id, patient__id=patient_id)
# TODO SEND MAIL PATIENT_REMOVE_BOOKING
s.clean_slot()
s.save()
return render(request, 'valid.tpl')
| email = request.GET['email']
if len(email) > 5:
p = Patient.objects.filter(email=email)
if len(p):
return HttpResponse(json.dumps({'return': True, 'patient': p[0].as_json()}))
else:
return HttpResponse(json.dumps({'return': False}))
else:
return HttpResponse(json.dumps({'return': False})) | conditional_block |
views.py | # -*- coding: utf-8 -*-
#
# Copyright 2015, Foxugly. All rights reserved.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
from patient.models import Patient
from django.http import HttpResponse
import json
from agenda.models import Slot
from django.shortcuts import render
from django.shortcuts import get_object_or_404
def search_patient(request):
if request.is_ajax():
email = request.GET['email']
if len(email) > 5:
p = Patient.objects.filter(email=email)
if len(p):
return HttpResponse(json.dumps({'return': True, 'patient': p[0].as_json()}))
else:
return HttpResponse(json.dumps({'return': False}))
else:
return HttpResponse(json.dumps({'return': False}))
def confirm_create(request, patient_id, text):
p = get_object_or_404(Patient, id=patient_id, confirm=text)
if p:
p.active = True
p.confirm = None
p.save()
return render(request, 'valid.tpl')
def confirm_remove(request, patient_id, slot_id):
| s = get_object_or_404(Slot, id=slot_id, patient__id=patient_id)
# s = Slot.objects.get(id=slot_id, patient__id=patient_id)
# TODO SEND MAIL PATIENT_REMOVE_BOOKING
s.clean_slot()
s.save()
return render(request, 'valid.tpl') | identifier_body | |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import setuptools
from setuptools import setup, find_packages
if setuptools.__version__ < '0.7':
raise RuntimeError("setuptools must be newer than 0.7")
version = "0.1.3"
setup(
name="pinger",
version=version,
author="Pedro Palhares (pedrospdc)",
author_email="pedrospdc@gmail.com",
description="Website monitoring tool",
url="https://github.com/pedrospdc/pinger",
download_url="https://github.com/pedrospdc/pinger/tarball/{}".format(version),
packages=find_packages(),
zip_safe=False,
license="MIT",
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: Developers", | ],
install_requires=[
"requests>=2.4.3",
"peewee>=2.4.0"
],
scripts=["bin/pinger"],
) | "Operating System :: OS Independent",
"Programming Language :: Python", | random_line_split |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import setuptools
from setuptools import setup, find_packages
if setuptools.__version__ < '0.7':
|
version = "0.1.3"
setup(
name="pinger",
version=version,
author="Pedro Palhares (pedrospdc)",
author_email="pedrospdc@gmail.com",
description="Website monitoring tool",
url="https://github.com/pedrospdc/pinger",
download_url="https://github.com/pedrospdc/pinger/tarball/{}".format(version),
packages=find_packages(),
zip_safe=False,
license="MIT",
classifiers=[
"Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python",
],
install_requires=[
"requests>=2.4.3",
"peewee>=2.4.0"
],
scripts=["bin/pinger"],
)
| raise RuntimeError("setuptools must be newer than 0.7") | conditional_block |
app.component.ts | import { ScheduleService } from './services/schedule.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Component, HostListener } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import * as XLSX from 'xlsx';
@Component({
selector: 'sch-app',
templateUrl: 'app.component.html',
})
export class AppComponent {
authError: boolean;
search: string;
constructor(private route: ActivatedRoute,
private router: Router,
private sanitizer: DomSanitizer,
private scheduleService: ScheduleService) { }
@HostListener('window:beforeunload') beforeUnloadHander() {
// return confirm("noo");
}
fileChanged($event): void {
//get file
//need to cast html tag
//reference: http://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement
var file = (<HTMLInputElement>document.getElementById("file")).files[0];
//new fileReader
let fileReader = new FileReader();
fileReader.readAsText(file);
//try to read file, this part does not work at all, need a solution
fileReader.onloadend = (e) => {
this.scheduleService.config=(JSON.parse(fileReader.result));
this.scheduleService.trigger.next();
};
}
xlsChanged($event): void { | //need to cast html tag
//reference: http://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement
var file = (<HTMLInputElement>document.getElementById("xls")).files[0];
//new fileReader
let fileReader = new FileReader();
fileReader.readAsBinaryString(file);
//try to read file, this part does not work at all, need a solution
fileReader.onloadend = (e:any) => {
const wb = XLSX.read(e.target.result, {type:'binary'});
console.log(wb);
};
}
downloadConfig(): void {
var blob = new Blob([JSON.stringify(this.scheduleService.config, null, 1)], { "type": "text/plain;charset=utf-8" });
if (window.navigator.msSaveOrOpenBlob) // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
window.navigator.msSaveBlob(blob, "config.json");
else {
var a = window.document.createElement("a");
a.href = window.URL.createObjectURL(blob);
a.download = "config.json";
document.body.appendChild(a);
a.click(); // IE: "Access is denied"; see: https://connect.microsoft.com/IE/feedback/details/797361/ie-10-treats-blob-url-as-cross-origin-and-denies-access
document.body.removeChild(a);
}
}
} | //get file | random_line_split |
app.component.ts | import { ScheduleService } from './services/schedule.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Component, HostListener } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import * as XLSX from 'xlsx';
@Component({
selector: 'sch-app',
templateUrl: 'app.component.html',
})
export class AppComponent {
authError: boolean;
search: string;
constructor(private route: ActivatedRoute,
private router: Router,
private sanitizer: DomSanitizer,
private scheduleService: ScheduleService) { }
@HostListener('window:beforeunload') beforeUnloadHander() {
// return confirm("noo");
}
fileChanged($event): void {
//get file
//need to cast html tag
//reference: http://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement
var file = (<HTMLInputElement>document.getElementById("file")).files[0];
//new fileReader
let fileReader = new FileReader();
fileReader.readAsText(file);
//try to read file, this part does not work at all, need a solution
fileReader.onloadend = (e) => {
this.scheduleService.config=(JSON.parse(fileReader.result));
this.scheduleService.trigger.next();
};
}
xlsChanged($event): void {
| downloadConfig(): void {
var blob = new Blob([JSON.stringify(this.scheduleService.config, null, 1)], { "type": "text/plain;charset=utf-8" });
if (window.navigator.msSaveOrOpenBlob) // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
window.navigator.msSaveBlob(blob, "config.json");
else {
var a = window.document.createElement("a");
a.href = window.URL.createObjectURL(blob);
a.download = "config.json";
document.body.appendChild(a);
a.click(); // IE: "Access is denied"; see: https://connect.microsoft.com/IE/feedback/details/797361/ie-10-treats-blob-url-as-cross-origin-and-denies-access
document.body.removeChild(a);
}
}
}
| //get file
//need to cast html tag
//reference: http://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement
var file = (<HTMLInputElement>document.getElementById("xls")).files[0];
//new fileReader
let fileReader = new FileReader();
fileReader.readAsBinaryString(file);
//try to read file, this part does not work at all, need a solution
fileReader.onloadend = (e:any) => {
const wb = XLSX.read(e.target.result, {type:'binary'});
console.log(wb);
};
}
| identifier_body |
app.component.ts | import { ScheduleService } from './services/schedule.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Component, HostListener } from '@angular/core';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import * as XLSX from 'xlsx';
@Component({
selector: 'sch-app',
templateUrl: 'app.component.html',
})
export class AppComponent {
authError: boolean;
search: string;
constructor(private route: ActivatedRoute,
private router: Router,
private sanitizer: DomSanitizer,
private scheduleService: ScheduleService) { }
@HostListener('window:beforeunload') beforeUnloadHander() {
// return confirm("noo");
}
| ($event): void {
//get file
//need to cast html tag
//reference: http://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement
var file = (<HTMLInputElement>document.getElementById("file")).files[0];
//new fileReader
let fileReader = new FileReader();
fileReader.readAsText(file);
//try to read file, this part does not work at all, need a solution
fileReader.onloadend = (e) => {
this.scheduleService.config=(JSON.parse(fileReader.result));
this.scheduleService.trigger.next();
};
}
xlsChanged($event): void {
//get file
//need to cast html tag
//reference: http://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement
var file = (<HTMLInputElement>document.getElementById("xls")).files[0];
//new fileReader
let fileReader = new FileReader();
fileReader.readAsBinaryString(file);
//try to read file, this part does not work at all, need a solution
fileReader.onloadend = (e:any) => {
const wb = XLSX.read(e.target.result, {type:'binary'});
console.log(wb);
};
}
downloadConfig(): void {
var blob = new Blob([JSON.stringify(this.scheduleService.config, null, 1)], { "type": "text/plain;charset=utf-8" });
if (window.navigator.msSaveOrOpenBlob) // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
window.navigator.msSaveBlob(blob, "config.json");
else {
var a = window.document.createElement("a");
a.href = window.URL.createObjectURL(blob);
a.download = "config.json";
document.body.appendChild(a);
a.click(); // IE: "Access is denied"; see: https://connect.microsoft.com/IE/feedback/details/797361/ie-10-treats-blob-url-as-cross-origin-and-denies-access
document.body.removeChild(a);
}
}
}
| fileChanged | identifier_name |
wikiPlugin.ts | /**
* @module Wiki
* @main Wiki
*/
/// <reference path="wikiHelpers.ts"/>
/// <reference path="../../ui/js/dropDown.ts"/>
/// <reference path="../../core/js/workspace.ts"/>
/// <reference path="../../git/js/git.ts"/>
/// <reference path="../../git/js/gitHelpers.ts"/>
/// <reference path="../../helpers/js/pluginHelpers.ts"/>
/// <reference path="../../helpers/js/urlHelpers.ts"/>
/// <reference path="./wikiRepository.ts"/>
module Wiki {
export var pluginName = 'wiki';
export var templatePath = 'app/wiki/html/';
export var tab:any = null;
export var _module = angular.module(pluginName, ['bootstrap', 'ui.bootstrap.dialog', 'ui.bootstrap.tabs', 'ngResource', 'hawtioCore', 'hawtio-ui', 'tree', 'camel']);
export var controller = PluginHelpers.createControllerFunction(_module, 'Wiki');
export var route = PluginHelpers.createRoutingFunction(templatePath);
_module.config(["$routeProvider", ($routeProvider) => {
// allow optional branch paths...
angular.forEach(["", "/branch/:branch"], (path) => {
$routeProvider.
when(UrlHelpers.join('/wiki', path, 'view'), route('viewPage.html', false)).
when(UrlHelpers.join('/wiki', path, 'create/*page'), route('create.html', false)).
when('/wiki' + path + '/view/*page', {templateUrl: 'app/wiki/html/viewPage.html', reloadOnSearch: false}).
when('/wiki' + path + '/book/*page', {templateUrl: 'app/wiki/html/viewBook.html', reloadOnSearch: false}).
when('/wiki' + path + '/edit/*page', {templateUrl: 'app/wiki/html/editPage.html'}).
when('/wiki' + path + '/version/*page/:objectId', {templateUrl: 'app/wiki/html/viewPage.html'}).
when('/wiki' + path + '/history/*page', {templateUrl: 'app/wiki/html/history.html'}).
when('/wiki' + path + '/commit/*page/:objectId', {templateUrl: 'app/wiki/html/commit.html'}).
when('/wiki' + path + '/diff/*page/:objectId/:baseObjectId', {templateUrl: 'app/wiki/html/viewPage.html', reloadOnSearch: false}).
when('/wiki' + path + '/formTable/*page', {templateUrl: 'app/wiki/html/formTable.html'}).
when('/wiki' + path + '/dozer/mappings/*page', {templateUrl: 'app/wiki/html/dozerMappings.html'}).
when('/wiki' + path + '/configurations/*page', { templateUrl: 'app/wiki/html/configurations.html' }).
when('/wiki' + path + '/configuration/:pid/*page', { templateUrl: 'app/wiki/html/configuration.html' }).
when('/wiki' + path + '/newConfiguration/:factoryPid/*page', { templateUrl: 'app/wiki/html/configuration.html' }).
when('/wiki' + path + '/camel/diagram/*page', {templateUrl: 'app/wiki/html/camelDiagram.html'}).
when('/wiki' + path + '/camel/canvas/*page', {templateUrl: 'app/wiki/html/camelCanvas.html'}).
when('/wiki' + path + '/camel/properties/*page', {templateUrl: 'app/wiki/html/camelProperties.html'});
});
}]);
_module.factory('wikiRepository', ["workspace", "jolokia", "localStorage", (workspace:Workspace, jolokia, localStorage) => {
return new GitWikiRepository(() => Git.createGitRepository(workspace, jolokia, localStorage));
}]);
/**
* Branch Menu service
*/
export interface BranchMenu {
addExtension: (item:UI.MenuItem) => void;
applyMenuExtensions: (menu:UI.MenuItem[]) => void;
}
_module.factory('wikiBranchMenu', () => {
var self = {
items: [],
addExtension: (item:UI.MenuItem) => {
self.items.push(item);
},
applyMenuExtensions: (menu:UI.MenuItem[]) => {
if (self.items.length === 0) {
return;
}
var extendedMenu:UI.MenuItem[] = [{
heading: "Actions"
}];
self.items.forEach((item:UI.MenuItem) => {
if (item.valid()) {
extendedMenu.push(item);
}
});
if (extendedMenu.length > 1) |
}
};
return self;
});
_module.factory('fileExtensionTypeRegistry', () => {
return {
"image": ["svg", "png", "ico", "bmp", "jpg", "gif"],
"markdown": ["md", "markdown", "mdown", "mkdn", "mkd"],
"htmlmixed": ["html", "xhtml", "htm"],
"text/x-java": ["java"],
"text/x-scala": ["scala"],
"javascript": ["js", "json", "javascript", "jscript", "ecmascript", "form"],
"xml": ["xml", "xsd", "wsdl", "atom"],
"properties": ["properties"]
};
});
_module.filter('fileIconClass', () => iconClass);
_module.run(["$location", "workspace", "viewRegistry", "jolokia", "localStorage", "layoutFull", "helpRegistry", "preferencesRegistry", "wikiRepository", "postLoginTasks", "$rootScope", ($location:ng.ILocationService,
workspace:Workspace,
viewRegistry,
jolokia,
localStorage,
layoutFull,
helpRegistry,
preferencesRegistry,
wikiRepository,
postLoginTasks,
$rootScope) => {
viewRegistry['wiki'] = templatePath + 'layoutWiki.html';
helpRegistry.addUserDoc('wiki', 'app/wiki/doc/help.md', () => {
return Wiki.isWikiEnabled(workspace, jolokia, localStorage);
});
preferencesRegistry.addTab("Git", 'app/wiki/html/gitPreferences.html');
tab = {
id: "wiki",
content: "Wiki",
title: "View and edit wiki pages",
isValid: (workspace:Workspace) => Wiki.isWikiEnabled(workspace, jolokia, localStorage),
href: () => "#/wiki/view",
isActive: (workspace:Workspace) => workspace.isLinkActive("/wiki") && !workspace.linkContains("fabric", "profiles") && !workspace.linkContains("editFeatures")
};
workspace.topLevelTabs.push(tab);
postLoginTasks.addTask('wikiGetRepositoryLabel', () => {
wikiRepository.getRepositoryLabel((label) => {
tab.content = label;
Core.$apply($rootScope)
}, (response) => {
// silently ignore
});
});
// add empty regexs to templates that don't define
// them so ng-pattern doesn't barf
Wiki.documentTemplates.forEach((template: any) => {
if (!template['regex']) {
template.regex = /(?:)/;
}
});
}]);
hawtioPluginLoader.addModule(pluginName);
}
| {
menu.add(extendedMenu);
} | conditional_block |
wikiPlugin.ts | /**
* @module Wiki
* @main Wiki
*/
/// <reference path="wikiHelpers.ts"/> | /// <reference path="../../core/js/workspace.ts"/>
/// <reference path="../../git/js/git.ts"/>
/// <reference path="../../git/js/gitHelpers.ts"/>
/// <reference path="../../helpers/js/pluginHelpers.ts"/>
/// <reference path="../../helpers/js/urlHelpers.ts"/>
/// <reference path="./wikiRepository.ts"/>
module Wiki {
export var pluginName = 'wiki';
export var templatePath = 'app/wiki/html/';
export var tab:any = null;
export var _module = angular.module(pluginName, ['bootstrap', 'ui.bootstrap.dialog', 'ui.bootstrap.tabs', 'ngResource', 'hawtioCore', 'hawtio-ui', 'tree', 'camel']);
export var controller = PluginHelpers.createControllerFunction(_module, 'Wiki');
export var route = PluginHelpers.createRoutingFunction(templatePath);
_module.config(["$routeProvider", ($routeProvider) => {
// allow optional branch paths...
angular.forEach(["", "/branch/:branch"], (path) => {
$routeProvider.
when(UrlHelpers.join('/wiki', path, 'view'), route('viewPage.html', false)).
when(UrlHelpers.join('/wiki', path, 'create/*page'), route('create.html', false)).
when('/wiki' + path + '/view/*page', {templateUrl: 'app/wiki/html/viewPage.html', reloadOnSearch: false}).
when('/wiki' + path + '/book/*page', {templateUrl: 'app/wiki/html/viewBook.html', reloadOnSearch: false}).
when('/wiki' + path + '/edit/*page', {templateUrl: 'app/wiki/html/editPage.html'}).
when('/wiki' + path + '/version/*page/:objectId', {templateUrl: 'app/wiki/html/viewPage.html'}).
when('/wiki' + path + '/history/*page', {templateUrl: 'app/wiki/html/history.html'}).
when('/wiki' + path + '/commit/*page/:objectId', {templateUrl: 'app/wiki/html/commit.html'}).
when('/wiki' + path + '/diff/*page/:objectId/:baseObjectId', {templateUrl: 'app/wiki/html/viewPage.html', reloadOnSearch: false}).
when('/wiki' + path + '/formTable/*page', {templateUrl: 'app/wiki/html/formTable.html'}).
when('/wiki' + path + '/dozer/mappings/*page', {templateUrl: 'app/wiki/html/dozerMappings.html'}).
when('/wiki' + path + '/configurations/*page', { templateUrl: 'app/wiki/html/configurations.html' }).
when('/wiki' + path + '/configuration/:pid/*page', { templateUrl: 'app/wiki/html/configuration.html' }).
when('/wiki' + path + '/newConfiguration/:factoryPid/*page', { templateUrl: 'app/wiki/html/configuration.html' }).
when('/wiki' + path + '/camel/diagram/*page', {templateUrl: 'app/wiki/html/camelDiagram.html'}).
when('/wiki' + path + '/camel/canvas/*page', {templateUrl: 'app/wiki/html/camelCanvas.html'}).
when('/wiki' + path + '/camel/properties/*page', {templateUrl: 'app/wiki/html/camelProperties.html'});
});
}]);
_module.factory('wikiRepository', ["workspace", "jolokia", "localStorage", (workspace:Workspace, jolokia, localStorage) => {
return new GitWikiRepository(() => Git.createGitRepository(workspace, jolokia, localStorage));
}]);
/**
* Branch Menu service
*/
export interface BranchMenu {
addExtension: (item:UI.MenuItem) => void;
applyMenuExtensions: (menu:UI.MenuItem[]) => void;
}
_module.factory('wikiBranchMenu', () => {
var self = {
items: [],
addExtension: (item:UI.MenuItem) => {
self.items.push(item);
},
applyMenuExtensions: (menu:UI.MenuItem[]) => {
if (self.items.length === 0) {
return;
}
var extendedMenu:UI.MenuItem[] = [{
heading: "Actions"
}];
self.items.forEach((item:UI.MenuItem) => {
if (item.valid()) {
extendedMenu.push(item);
}
});
if (extendedMenu.length > 1) {
menu.add(extendedMenu);
}
}
};
return self;
});
_module.factory('fileExtensionTypeRegistry', () => {
return {
"image": ["svg", "png", "ico", "bmp", "jpg", "gif"],
"markdown": ["md", "markdown", "mdown", "mkdn", "mkd"],
"htmlmixed": ["html", "xhtml", "htm"],
"text/x-java": ["java"],
"text/x-scala": ["scala"],
"javascript": ["js", "json", "javascript", "jscript", "ecmascript", "form"],
"xml": ["xml", "xsd", "wsdl", "atom"],
"properties": ["properties"]
};
});
_module.filter('fileIconClass', () => iconClass);
_module.run(["$location", "workspace", "viewRegistry", "jolokia", "localStorage", "layoutFull", "helpRegistry", "preferencesRegistry", "wikiRepository", "postLoginTasks", "$rootScope", ($location:ng.ILocationService,
workspace:Workspace,
viewRegistry,
jolokia,
localStorage,
layoutFull,
helpRegistry,
preferencesRegistry,
wikiRepository,
postLoginTasks,
$rootScope) => {
viewRegistry['wiki'] = templatePath + 'layoutWiki.html';
helpRegistry.addUserDoc('wiki', 'app/wiki/doc/help.md', () => {
return Wiki.isWikiEnabled(workspace, jolokia, localStorage);
});
preferencesRegistry.addTab("Git", 'app/wiki/html/gitPreferences.html');
tab = {
id: "wiki",
content: "Wiki",
title: "View and edit wiki pages",
isValid: (workspace:Workspace) => Wiki.isWikiEnabled(workspace, jolokia, localStorage),
href: () => "#/wiki/view",
isActive: (workspace:Workspace) => workspace.isLinkActive("/wiki") && !workspace.linkContains("fabric", "profiles") && !workspace.linkContains("editFeatures")
};
workspace.topLevelTabs.push(tab);
postLoginTasks.addTask('wikiGetRepositoryLabel', () => {
wikiRepository.getRepositoryLabel((label) => {
tab.content = label;
Core.$apply($rootScope)
}, (response) => {
// silently ignore
});
});
// add empty regexs to templates that don't define
// them so ng-pattern doesn't barf
Wiki.documentTemplates.forEach((template: any) => {
if (!template['regex']) {
template.regex = /(?:)/;
}
});
}]);
hawtioPluginLoader.addModule(pluginName);
} | /// <reference path="../../ui/js/dropDown.ts"/> | random_line_split |
login.rs | use command_prelude::*;
use std::io::{self, BufRead};
use cargo::core::{Source, SourceId};
use cargo::sources::RegistrySource;
use cargo::util::{CargoError, CargoResultExt};
use cargo::ops;
pub fn cli() -> App {
subcommand("login")
.about(
"Save an api token from the registry locally. \
If token is not specified, it will be read from stdin.",
)
.arg(Arg::with_name("token"))
.arg(opt("host", "Host to set the token for").value_name("HOST"))
.arg(opt("registry", "Registry to use").value_name("REGISTRY"))
}
pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult | {
let registry = args.registry(config)?;
let token = match args.value_of("token") {
Some(token) => token.to_string(),
None => {
let host = match registry {
Some(ref _registry) => {
return Err(format_err!(
"token must be provided when \
--registry is provided."
).into());
}
None => {
let src = SourceId::crates_io(config)?;
let mut src = RegistrySource::remote(&src, config);
src.update()?;
let config = src.config()?.unwrap();
args.value_of("host")
.map(|s| s.to_string())
.unwrap_or(config.api.unwrap())
}
};
println!("please visit {}me and paste the API Token below", host);
let mut line = String::new();
let input = io::stdin();
input
.lock()
.read_line(&mut line)
.chain_err(|| "failed to read stdin")
.map_err(CargoError::from)?;
line.trim().to_string()
}
};
ops::registry_login(config, token, registry)?;
Ok(())
} | identifier_body | |
login.rs | use command_prelude::*;
use std::io::{self, BufRead};
use cargo::core::{Source, SourceId};
use cargo::sources::RegistrySource;
use cargo::util::{CargoError, CargoResultExt};
use cargo::ops;
pub fn cli() -> App {
subcommand("login")
.about(
"Save an api token from the registry locally. \
If token is not specified, it will be read from stdin.",
)
.arg(Arg::with_name("token"))
.arg(opt("host", "Host to set the token for").value_name("HOST"))
.arg(opt("registry", "Registry to use").value_name("REGISTRY"))
}
pub fn | (config: &mut Config, args: &ArgMatches) -> CliResult {
let registry = args.registry(config)?;
let token = match args.value_of("token") {
Some(token) => token.to_string(),
None => {
let host = match registry {
Some(ref _registry) => {
return Err(format_err!(
"token must be provided when \
--registry is provided."
).into());
}
None => {
let src = SourceId::crates_io(config)?;
let mut src = RegistrySource::remote(&src, config);
src.update()?;
let config = src.config()?.unwrap();
args.value_of("host")
.map(|s| s.to_string())
.unwrap_or(config.api.unwrap())
}
};
println!("please visit {}me and paste the API Token below", host);
let mut line = String::new();
let input = io::stdin();
input
.lock()
.read_line(&mut line)
.chain_err(|| "failed to read stdin")
.map_err(CargoError::from)?;
line.trim().to_string()
}
};
ops::registry_login(config, token, registry)?;
Ok(())
}
| exec | identifier_name |
login.rs | use command_prelude::*;
use std::io::{self, BufRead};
use cargo::core::{Source, SourceId}; | use cargo::ops;
pub fn cli() -> App {
subcommand("login")
.about(
"Save an api token from the registry locally. \
If token is not specified, it will be read from stdin.",
)
.arg(Arg::with_name("token"))
.arg(opt("host", "Host to set the token for").value_name("HOST"))
.arg(opt("registry", "Registry to use").value_name("REGISTRY"))
}
pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
let registry = args.registry(config)?;
let token = match args.value_of("token") {
Some(token) => token.to_string(),
None => {
let host = match registry {
Some(ref _registry) => {
return Err(format_err!(
"token must be provided when \
--registry is provided."
).into());
}
None => {
let src = SourceId::crates_io(config)?;
let mut src = RegistrySource::remote(&src, config);
src.update()?;
let config = src.config()?.unwrap();
args.value_of("host")
.map(|s| s.to_string())
.unwrap_or(config.api.unwrap())
}
};
println!("please visit {}me and paste the API Token below", host);
let mut line = String::new();
let input = io::stdin();
input
.lock()
.read_line(&mut line)
.chain_err(|| "failed to read stdin")
.map_err(CargoError::from)?;
line.trim().to_string()
}
};
ops::registry_login(config, token, registry)?;
Ok(())
} | use cargo::sources::RegistrySource;
use cargo::util::{CargoError, CargoResultExt}; | random_line_split |
dialog-container.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
Component,
ComponentRef,
ViewChild,
ViewEncapsulation,
NgZone,
ElementRef,
EventEmitter,
Inject,
Optional,
ChangeDetectorRef,
} from '@angular/core';
import {
animate,
trigger,
state,
style,
transition,
AnimationEvent,
} from '@angular/animations';
import {DOCUMENT} from '@angular/platform-browser';
import {BasePortalHost, ComponentPortal, PortalHostDirective, TemplatePortal} from '../core';
import {MdDialogConfig} from './dialog-config';
import {FocusTrapFactory, FocusTrap} from '../core/a11y/focus-trap';
/**
* Throws an exception for the case when a ComponentPortal is
* attached to a DomPortalHost without an origin.
* @docs-private
*/
export function throwMdDialogContentAlreadyAttachedError() {
throw Error('Attempting to attach dialog content after content is already attached');
}
/**
* Internal component that wraps user-provided dialog content.
* Animation is based on https://material.io/guidelines/motion/choreography.html.
* @docs-private
*/
@Component({
moduleId: module.id,
selector: 'md-dialog-container, mat-dialog-container',
templateUrl: 'dialog-container.html',
styleUrls: ['dialog.css'],
encapsulation: ViewEncapsulation.None,
animations: [
trigger('slideDialog', [
// Note: The `enter` animation doesn't transition to something like `translate3d(0, 0, 0)
// scale(1)`, because for some reason specifying the transform explicitly, causes IE both
// to blur the dialog content and decimate the animation performance. Leaving it as `none`
// solves both issues.
state('enter', style({ transform: 'none', opacity: 1 })),
state('void', style({ transform: 'translate3d(0, 25%, 0) scale(0.9)', opacity: 0 })),
state('exit', style({ transform: 'translate3d(0, 25%, 0)', opacity: 0 })),
transition('* => *', animate('400ms cubic-bezier(0.25, 0.8, 0.25, 1)')),
])
],
host: {
'class': 'mat-dialog-container',
'[attr.role]': '_config?.role',
'[attr.aria-labelledby]': '_ariaLabelledBy',
'[attr.aria-describedby]': '_config?.ariaDescribedBy || null',
'[@slideDialog]': '_state',
'(@slideDialog.start)': '_onAnimationStart($event)',
'(@slideDialog.done)': '_onAnimationDone($event)',
},
})
export class MdDialogContainer extends BasePortalHost {
/** The portal host inside of this container into which the dialog content will be loaded. */
@ViewChild(PortalHostDirective) _portalHost: PortalHostDirective;
/** The class that traps and manages focus within the dialog. */
private _focusTrap: FocusTrap;
/** Element that was focused before the dialog was opened. Save this to restore upon close. */
private _elementFocusedBeforeDialogWasOpened: HTMLElement | null = null;
/** The dialog configuration. */
_config: MdDialogConfig;
/** State of the dialog animation. */
_state: 'void' | 'enter' | 'exit' = 'enter';
/** Emits when an animation state changes. */
_animationStateChanged = new EventEmitter<AnimationEvent>();
/** ID of the element that should be considered as the dialog's label. */
_ariaLabelledBy: string | null = null;
/** Whether the container is currently mid-animation. */
_isAnimating = false;
constructor(
private _ngZone: NgZone,
private _elementRef: ElementRef,
private _focusTrapFactory: FocusTrapFactory,
private _changeDetectorRef: ChangeDetectorRef,
@Optional() @Inject(DOCUMENT) private _document: any) {
super();
}
/**
* Attach a ComponentPortal as content to this dialog container.
* @param portal Portal to be attached as the dialog content.
*/
attachComponentPortal<T>(portal: ComponentPortal<T>): ComponentRef<T> {
if (this._portalHost.hasAttached()) {
throwMdDialogContentAlreadyAttachedError();
}
this._savePreviouslyFocusedElement();
return this._portalHost.attachComponentPortal(portal);
}
/**
* Attach a TemplatePortal as content to this dialog container.
* @param portal Portal to be attached as the dialog content.
*/
attachTemplatePortal(portal: TemplatePortal): Map<string, any> {
if (this._portalHost.hasAttached()) {
throwMdDialogContentAlreadyAttachedError();
}
this._savePreviouslyFocusedElement();
return this._portalHost.attachTemplatePortal(portal);
}
/** Moves the focus inside the focus trap. */
private _trapFocus() {
if (!this._focusTrap) {
this._focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement);
}
// If were to attempt to focus immediately, then the content of the dialog would not yet be
// ready in instances where change detection has to run first. To deal with this, we simply
// wait for the microtask queue to be empty.
this._focusTrap.focusInitialElementWhenReady();
}
/** Restores focus to the element that was focused before the dialog opened. */
private _restoreFocus() {
const toFocus = this._elementFocusedBeforeDialogWasOpened;
// We need the extra check, because IE can set the `activeElement` to null in some cases.
if (toFocus && 'focus' in toFocus) {
toFocus.focus();
}
if (this._focusTrap) {
this._focusTrap.destroy();
}
}
/** Saves a reference to the element that was focused before the dialog was opened. */
private _savePreviouslyFocusedElement() {
if (this._document) {
this._elementFocusedBeforeDialogWasOpened = this._document.activeElement as HTMLElement;
}
}
/** Callback, invoked whenever an animation on the host completes. */
_onAnimationDone(event: AnimationEvent) {
if (event.toState === 'enter') {
this._trapFocus();
} else if (event.toState === 'exit') {
this._restoreFocus();
}
this._animationStateChanged.emit(event);
this._isAnimating = false;
}
/** Callback, invoked when an animation on the host starts. */
_onAnimationStart(event: AnimationEvent) {
this._isAnimating = true;
this._animationStateChanged.emit(event);
}
/** Starts the dialog exit animation. */
_startExitAnimation(): void |
}
| {
this._state = 'exit';
// Mark the container for check so it can react if the
// view container is using OnPush change detection.
this._changeDetectorRef.markForCheck();
} | identifier_body |
dialog-container.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
Component,
ComponentRef,
ViewChild,
ViewEncapsulation,
NgZone,
ElementRef,
EventEmitter,
Inject, | ChangeDetectorRef,
} from '@angular/core';
import {
animate,
trigger,
state,
style,
transition,
AnimationEvent,
} from '@angular/animations';
import {DOCUMENT} from '@angular/platform-browser';
import {BasePortalHost, ComponentPortal, PortalHostDirective, TemplatePortal} from '../core';
import {MdDialogConfig} from './dialog-config';
import {FocusTrapFactory, FocusTrap} from '../core/a11y/focus-trap';
/**
* Throws an exception for the case when a ComponentPortal is
* attached to a DomPortalHost without an origin.
* @docs-private
*/
export function throwMdDialogContentAlreadyAttachedError() {
throw Error('Attempting to attach dialog content after content is already attached');
}
/**
* Internal component that wraps user-provided dialog content.
* Animation is based on https://material.io/guidelines/motion/choreography.html.
* @docs-private
*/
@Component({
moduleId: module.id,
selector: 'md-dialog-container, mat-dialog-container',
templateUrl: 'dialog-container.html',
styleUrls: ['dialog.css'],
encapsulation: ViewEncapsulation.None,
animations: [
trigger('slideDialog', [
// Note: The `enter` animation doesn't transition to something like `translate3d(0, 0, 0)
// scale(1)`, because for some reason specifying the transform explicitly, causes IE both
// to blur the dialog content and decimate the animation performance. Leaving it as `none`
// solves both issues.
state('enter', style({ transform: 'none', opacity: 1 })),
state('void', style({ transform: 'translate3d(0, 25%, 0) scale(0.9)', opacity: 0 })),
state('exit', style({ transform: 'translate3d(0, 25%, 0)', opacity: 0 })),
transition('* => *', animate('400ms cubic-bezier(0.25, 0.8, 0.25, 1)')),
])
],
host: {
'class': 'mat-dialog-container',
'[attr.role]': '_config?.role',
'[attr.aria-labelledby]': '_ariaLabelledBy',
'[attr.aria-describedby]': '_config?.ariaDescribedBy || null',
'[@slideDialog]': '_state',
'(@slideDialog.start)': '_onAnimationStart($event)',
'(@slideDialog.done)': '_onAnimationDone($event)',
},
})
export class MdDialogContainer extends BasePortalHost {
/** The portal host inside of this container into which the dialog content will be loaded. */
@ViewChild(PortalHostDirective) _portalHost: PortalHostDirective;
/** The class that traps and manages focus within the dialog. */
private _focusTrap: FocusTrap;
/** Element that was focused before the dialog was opened. Save this to restore upon close. */
private _elementFocusedBeforeDialogWasOpened: HTMLElement | null = null;
/** The dialog configuration. */
_config: MdDialogConfig;
/** State of the dialog animation. */
_state: 'void' | 'enter' | 'exit' = 'enter';
/** Emits when an animation state changes. */
_animationStateChanged = new EventEmitter<AnimationEvent>();
/** ID of the element that should be considered as the dialog's label. */
_ariaLabelledBy: string | null = null;
/** Whether the container is currently mid-animation. */
_isAnimating = false;
constructor(
private _ngZone: NgZone,
private _elementRef: ElementRef,
private _focusTrapFactory: FocusTrapFactory,
private _changeDetectorRef: ChangeDetectorRef,
@Optional() @Inject(DOCUMENT) private _document: any) {
super();
}
/**
* Attach a ComponentPortal as content to this dialog container.
* @param portal Portal to be attached as the dialog content.
*/
attachComponentPortal<T>(portal: ComponentPortal<T>): ComponentRef<T> {
if (this._portalHost.hasAttached()) {
throwMdDialogContentAlreadyAttachedError();
}
this._savePreviouslyFocusedElement();
return this._portalHost.attachComponentPortal(portal);
}
/**
* Attach a TemplatePortal as content to this dialog container.
* @param portal Portal to be attached as the dialog content.
*/
attachTemplatePortal(portal: TemplatePortal): Map<string, any> {
if (this._portalHost.hasAttached()) {
throwMdDialogContentAlreadyAttachedError();
}
this._savePreviouslyFocusedElement();
return this._portalHost.attachTemplatePortal(portal);
}
/** Moves the focus inside the focus trap. */
private _trapFocus() {
if (!this._focusTrap) {
this._focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement);
}
// If were to attempt to focus immediately, then the content of the dialog would not yet be
// ready in instances where change detection has to run first. To deal with this, we simply
// wait for the microtask queue to be empty.
this._focusTrap.focusInitialElementWhenReady();
}
/** Restores focus to the element that was focused before the dialog opened. */
private _restoreFocus() {
const toFocus = this._elementFocusedBeforeDialogWasOpened;
// We need the extra check, because IE can set the `activeElement` to null in some cases.
if (toFocus && 'focus' in toFocus) {
toFocus.focus();
}
if (this._focusTrap) {
this._focusTrap.destroy();
}
}
/** Saves a reference to the element that was focused before the dialog was opened. */
private _savePreviouslyFocusedElement() {
if (this._document) {
this._elementFocusedBeforeDialogWasOpened = this._document.activeElement as HTMLElement;
}
}
/** Callback, invoked whenever an animation on the host completes. */
_onAnimationDone(event: AnimationEvent) {
if (event.toState === 'enter') {
this._trapFocus();
} else if (event.toState === 'exit') {
this._restoreFocus();
}
this._animationStateChanged.emit(event);
this._isAnimating = false;
}
/** Callback, invoked when an animation on the host starts. */
_onAnimationStart(event: AnimationEvent) {
this._isAnimating = true;
this._animationStateChanged.emit(event);
}
/** Starts the dialog exit animation. */
_startExitAnimation(): void {
this._state = 'exit';
// Mark the container for check so it can react if the
// view container is using OnPush change detection.
this._changeDetectorRef.markForCheck();
}
} | Optional, | random_line_split |
dialog-container.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
Component,
ComponentRef,
ViewChild,
ViewEncapsulation,
NgZone,
ElementRef,
EventEmitter,
Inject,
Optional,
ChangeDetectorRef,
} from '@angular/core';
import {
animate,
trigger,
state,
style,
transition,
AnimationEvent,
} from '@angular/animations';
import {DOCUMENT} from '@angular/platform-browser';
import {BasePortalHost, ComponentPortal, PortalHostDirective, TemplatePortal} from '../core';
import {MdDialogConfig} from './dialog-config';
import {FocusTrapFactory, FocusTrap} from '../core/a11y/focus-trap';
/**
* Throws an exception for the case when a ComponentPortal is
* attached to a DomPortalHost without an origin.
* @docs-private
*/
export function throwMdDialogContentAlreadyAttachedError() {
throw Error('Attempting to attach dialog content after content is already attached');
}
/**
* Internal component that wraps user-provided dialog content.
* Animation is based on https://material.io/guidelines/motion/choreography.html.
* @docs-private
*/
@Component({
moduleId: module.id,
selector: 'md-dialog-container, mat-dialog-container',
templateUrl: 'dialog-container.html',
styleUrls: ['dialog.css'],
encapsulation: ViewEncapsulation.None,
animations: [
trigger('slideDialog', [
// Note: The `enter` animation doesn't transition to something like `translate3d(0, 0, 0)
// scale(1)`, because for some reason specifying the transform explicitly, causes IE both
// to blur the dialog content and decimate the animation performance. Leaving it as `none`
// solves both issues.
state('enter', style({ transform: 'none', opacity: 1 })),
state('void', style({ transform: 'translate3d(0, 25%, 0) scale(0.9)', opacity: 0 })),
state('exit', style({ transform: 'translate3d(0, 25%, 0)', opacity: 0 })),
transition('* => *', animate('400ms cubic-bezier(0.25, 0.8, 0.25, 1)')),
])
],
host: {
'class': 'mat-dialog-container',
'[attr.role]': '_config?.role',
'[attr.aria-labelledby]': '_ariaLabelledBy',
'[attr.aria-describedby]': '_config?.ariaDescribedBy || null',
'[@slideDialog]': '_state',
'(@slideDialog.start)': '_onAnimationStart($event)',
'(@slideDialog.done)': '_onAnimationDone($event)',
},
})
export class MdDialogContainer extends BasePortalHost {
/** The portal host inside of this container into which the dialog content will be loaded. */
@ViewChild(PortalHostDirective) _portalHost: PortalHostDirective;
/** The class that traps and manages focus within the dialog. */
private _focusTrap: FocusTrap;
/** Element that was focused before the dialog was opened. Save this to restore upon close. */
private _elementFocusedBeforeDialogWasOpened: HTMLElement | null = null;
/** The dialog configuration. */
_config: MdDialogConfig;
/** State of the dialog animation. */
_state: 'void' | 'enter' | 'exit' = 'enter';
/** Emits when an animation state changes. */
_animationStateChanged = new EventEmitter<AnimationEvent>();
/** ID of the element that should be considered as the dialog's label. */
_ariaLabelledBy: string | null = null;
/** Whether the container is currently mid-animation. */
_isAnimating = false;
constructor(
private _ngZone: NgZone,
private _elementRef: ElementRef,
private _focusTrapFactory: FocusTrapFactory,
private _changeDetectorRef: ChangeDetectorRef,
@Optional() @Inject(DOCUMENT) private _document: any) {
super();
}
/**
* Attach a ComponentPortal as content to this dialog container.
* @param portal Portal to be attached as the dialog content.
*/
| <T>(portal: ComponentPortal<T>): ComponentRef<T> {
if (this._portalHost.hasAttached()) {
throwMdDialogContentAlreadyAttachedError();
}
this._savePreviouslyFocusedElement();
return this._portalHost.attachComponentPortal(portal);
}
/**
* Attach a TemplatePortal as content to this dialog container.
* @param portal Portal to be attached as the dialog content.
*/
attachTemplatePortal(portal: TemplatePortal): Map<string, any> {
if (this._portalHost.hasAttached()) {
throwMdDialogContentAlreadyAttachedError();
}
this._savePreviouslyFocusedElement();
return this._portalHost.attachTemplatePortal(portal);
}
/** Moves the focus inside the focus trap. */
private _trapFocus() {
if (!this._focusTrap) {
this._focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement);
}
// If were to attempt to focus immediately, then the content of the dialog would not yet be
// ready in instances where change detection has to run first. To deal with this, we simply
// wait for the microtask queue to be empty.
this._focusTrap.focusInitialElementWhenReady();
}
/** Restores focus to the element that was focused before the dialog opened. */
private _restoreFocus() {
const toFocus = this._elementFocusedBeforeDialogWasOpened;
// We need the extra check, because IE can set the `activeElement` to null in some cases.
if (toFocus && 'focus' in toFocus) {
toFocus.focus();
}
if (this._focusTrap) {
this._focusTrap.destroy();
}
}
/** Saves a reference to the element that was focused before the dialog was opened. */
private _savePreviouslyFocusedElement() {
if (this._document) {
this._elementFocusedBeforeDialogWasOpened = this._document.activeElement as HTMLElement;
}
}
/** Callback, invoked whenever an animation on the host completes. */
_onAnimationDone(event: AnimationEvent) {
if (event.toState === 'enter') {
this._trapFocus();
} else if (event.toState === 'exit') {
this._restoreFocus();
}
this._animationStateChanged.emit(event);
this._isAnimating = false;
}
/** Callback, invoked when an animation on the host starts. */
_onAnimationStart(event: AnimationEvent) {
this._isAnimating = true;
this._animationStateChanged.emit(event);
}
/** Starts the dialog exit animation. */
_startExitAnimation(): void {
this._state = 'exit';
// Mark the container for check so it can react if the
// view container is using OnPush change detection.
this._changeDetectorRef.markForCheck();
}
}
| attachComponentPortal | identifier_name |
dialog-container.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
Component,
ComponentRef,
ViewChild,
ViewEncapsulation,
NgZone,
ElementRef,
EventEmitter,
Inject,
Optional,
ChangeDetectorRef,
} from '@angular/core';
import {
animate,
trigger,
state,
style,
transition,
AnimationEvent,
} from '@angular/animations';
import {DOCUMENT} from '@angular/platform-browser';
import {BasePortalHost, ComponentPortal, PortalHostDirective, TemplatePortal} from '../core';
import {MdDialogConfig} from './dialog-config';
import {FocusTrapFactory, FocusTrap} from '../core/a11y/focus-trap';
/**
* Throws an exception for the case when a ComponentPortal is
* attached to a DomPortalHost without an origin.
* @docs-private
*/
export function throwMdDialogContentAlreadyAttachedError() {
throw Error('Attempting to attach dialog content after content is already attached');
}
/**
* Internal component that wraps user-provided dialog content.
* Animation is based on https://material.io/guidelines/motion/choreography.html.
* @docs-private
*/
@Component({
moduleId: module.id,
selector: 'md-dialog-container, mat-dialog-container',
templateUrl: 'dialog-container.html',
styleUrls: ['dialog.css'],
encapsulation: ViewEncapsulation.None,
animations: [
trigger('slideDialog', [
// Note: The `enter` animation doesn't transition to something like `translate3d(0, 0, 0)
// scale(1)`, because for some reason specifying the transform explicitly, causes IE both
// to blur the dialog content and decimate the animation performance. Leaving it as `none`
// solves both issues.
state('enter', style({ transform: 'none', opacity: 1 })),
state('void', style({ transform: 'translate3d(0, 25%, 0) scale(0.9)', opacity: 0 })),
state('exit', style({ transform: 'translate3d(0, 25%, 0)', opacity: 0 })),
transition('* => *', animate('400ms cubic-bezier(0.25, 0.8, 0.25, 1)')),
])
],
host: {
'class': 'mat-dialog-container',
'[attr.role]': '_config?.role',
'[attr.aria-labelledby]': '_ariaLabelledBy',
'[attr.aria-describedby]': '_config?.ariaDescribedBy || null',
'[@slideDialog]': '_state',
'(@slideDialog.start)': '_onAnimationStart($event)',
'(@slideDialog.done)': '_onAnimationDone($event)',
},
})
export class MdDialogContainer extends BasePortalHost {
/** The portal host inside of this container into which the dialog content will be loaded. */
@ViewChild(PortalHostDirective) _portalHost: PortalHostDirective;
/** The class that traps and manages focus within the dialog. */
private _focusTrap: FocusTrap;
/** Element that was focused before the dialog was opened. Save this to restore upon close. */
private _elementFocusedBeforeDialogWasOpened: HTMLElement | null = null;
/** The dialog configuration. */
_config: MdDialogConfig;
/** State of the dialog animation. */
_state: 'void' | 'enter' | 'exit' = 'enter';
/** Emits when an animation state changes. */
_animationStateChanged = new EventEmitter<AnimationEvent>();
/** ID of the element that should be considered as the dialog's label. */
_ariaLabelledBy: string | null = null;
/** Whether the container is currently mid-animation. */
_isAnimating = false;
constructor(
private _ngZone: NgZone,
private _elementRef: ElementRef,
private _focusTrapFactory: FocusTrapFactory,
private _changeDetectorRef: ChangeDetectorRef,
@Optional() @Inject(DOCUMENT) private _document: any) {
super();
}
/**
* Attach a ComponentPortal as content to this dialog container.
* @param portal Portal to be attached as the dialog content.
*/
attachComponentPortal<T>(portal: ComponentPortal<T>): ComponentRef<T> {
if (this._portalHost.hasAttached()) {
throwMdDialogContentAlreadyAttachedError();
}
this._savePreviouslyFocusedElement();
return this._portalHost.attachComponentPortal(portal);
}
/**
* Attach a TemplatePortal as content to this dialog container.
* @param portal Portal to be attached as the dialog content.
*/
attachTemplatePortal(portal: TemplatePortal): Map<string, any> {
if (this._portalHost.hasAttached()) {
throwMdDialogContentAlreadyAttachedError();
}
this._savePreviouslyFocusedElement();
return this._portalHost.attachTemplatePortal(portal);
}
/** Moves the focus inside the focus trap. */
private _trapFocus() {
if (!this._focusTrap) {
this._focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement);
}
// If were to attempt to focus immediately, then the content of the dialog would not yet be
// ready in instances where change detection has to run first. To deal with this, we simply
// wait for the microtask queue to be empty.
this._focusTrap.focusInitialElementWhenReady();
}
/** Restores focus to the element that was focused before the dialog opened. */
private _restoreFocus() {
const toFocus = this._elementFocusedBeforeDialogWasOpened;
// We need the extra check, because IE can set the `activeElement` to null in some cases.
if (toFocus && 'focus' in toFocus) {
toFocus.focus();
}
if (this._focusTrap) |
}
/** Saves a reference to the element that was focused before the dialog was opened. */
private _savePreviouslyFocusedElement() {
if (this._document) {
this._elementFocusedBeforeDialogWasOpened = this._document.activeElement as HTMLElement;
}
}
/** Callback, invoked whenever an animation on the host completes. */
_onAnimationDone(event: AnimationEvent) {
if (event.toState === 'enter') {
this._trapFocus();
} else if (event.toState === 'exit') {
this._restoreFocus();
}
this._animationStateChanged.emit(event);
this._isAnimating = false;
}
/** Callback, invoked when an animation on the host starts. */
_onAnimationStart(event: AnimationEvent) {
this._isAnimating = true;
this._animationStateChanged.emit(event);
}
/** Starts the dialog exit animation. */
_startExitAnimation(): void {
this._state = 'exit';
// Mark the container for check so it can react if the
// view container is using OnPush change detection.
this._changeDetectorRef.markForCheck();
}
}
| {
this._focusTrap.destroy();
} | conditional_block |
wanderer.py | '''
Created on Jan 19, 2013
@author: dsnowdon
'''
import os
import tempfile
import datetime
import json
import logging
from naoutil.jsonobj import to_json_string, from_json_string
from naoutil.general import find_class
import robotstate
from event import *
from action import *
from naoutil.naoenv import make_environment
'''
Here we define the memory locations used to store state
'''
MEM_SECURITY_DISTANCE = "WandererSecurityDistance"
MEM_HEADING = "WandererWalkHeading"
MEM_WALK_PATH = "WandererWalkPath"
MEM_DETECTED_FACE_DIRECTION = "WandererFaceDirection"
MEM_PLANNED_ACTIONS = "WandererActionsPlanned"
MEM_CURRENT_ACTIONS = "WandererActionsInProgress"
MEM_COMPLETED_ACTIONS = "WandererActionsCompleted"
MEM_CURRENT_EVENT = "WandererEvent"
MEM_MAP = "WandererMap"
MEM_LOCATION = "WandererLocation"
EVENT_LOOK_FOR_PEOPLE = "WandererEventLookForPeople"
DEFAULT_CONFIG_FILE = "wanderer"
PROPERTY_PLANNER_CLASS = "plannerClass"
DEFAULT_PLANNER_CLASS = "wanderer.randomwalk.RandomWalk"
PROPERTY_EXECUTOR_CLASS = "executorClass"
DEFAULT_EXECUTOR_CLASS = "wanderer.wanderer.PlanExecutor"
PROPERTY_MAPPER_CLASS = "mapperClass"
DEFAULT_MAPPER_CLASS = "wanderer.wanderer.NullMapper"
PROPERTY_UPDATER_CLASSES = "updaterClasses"
PROPERTY_HTTP_PORT = "httpPort"
DEFAULT_HTTP_PORT = 8080
PROPERTY_DATA_COLLECTOR_HOST = "dataCollectorHost"
PROPERTY_DATA_COLLECTOR_PORT = "dataCollectorPort"
PROPERTY_LOOK_FOR_PEOPLE = "lookForPeople"
STATIC_WEB_DIR = "web"
CENTRE_BIAS = False
HEAD_HORIZONTAL_OFFSET = 0
WANDERER_NAME = "wanderer"
# START GLOBALS
# We put instances of planners, executors and mappers here so we don't need to continually create
# new instances
planner_instance = None
executor_instance = None
mapper_instance = None
updater_instances = None
# END GLOBALS
wanderer_logger = logging.getLogger("wanderer.wanderer")
def init_state(env, startPos):
# declare events
env.memory.declareEvent(EVENT_LOOK_FOR_PEOPLE);
# getData & removeData throw errors if the value is not set,
# so ensure all the memory locations we want to use are initialised
env.memory.insertData(MEM_CURRENT_EVENT, None)
# set "security distance"
env.memory.insertData(MEM_SECURITY_DISTANCE, "0.25")
# should we look for people as we go?
lookForPeople = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_LOOK_FOR_PEOPLE)
if lookForPeople:
env.memory.raiseEvent(EVENT_LOOK_FOR_PEOPLE, True)
env.log("Looking for people")
else:
env.memory.raiseEvent(EVENT_LOOK_FOR_PEOPLE, False)
env.log("Not looking for people")
# set initial position (in list of positions)
env.memory.insertData(MEM_WALK_PATH, [startPos])
# current actions and completed actions
env.memory.insertData(MEM_PLANNED_ACTIONS, "")
env.memory.insertData(MEM_CURRENT_ACTIONS, "")
env.memory.insertData(MEM_COMPLETED_ACTIONS, "")
def shutdown(env):
planner = get_planner_instance(env)
planner.shutdown()
executor = get_executor_instance(env, None)
executor.shutdown()
mapper = get_mapper_instance(env)
mapper.shutdown()
updater_instances = get_updaters(env)
for updater in updater_instances:
updater.shutdown()
'''
Base class for wanderer planning.
Handles generating plans and reacting to events
'''
class Planner(object):
def __init__(self, env_):
super(Planner, self).__init__()
self.env = env_
def handleEvent(self, event, state):
plan = self.dispatch(event, state)
save_plan(self.env, plan)
log_plan(self.env, "New plan", plan)
return plan
# return true if this event should cause the current plan to be executed and
# a new plan created to react to it
def does_event_interrupt_plan(self, event, state):
return True
def dispatch(self, event, state):
methodName = 'handle'+ event.name()
try:
method = getattr(self, methodName)
return method(event, state)
except AttributeError:
self.env.log("Unimplemented event handler for: {}".format(event.name()))
def shutdown(self):
pass
'''
Base class for executing plans. Since we may need to trigger choreographe
boxes we delegate actually performing a single action to an actionExecutor
which in most cases will be the choreographe box that called us.
The actionExecutor must implement do_action(action) and all_done()
'''
class PlanExecutor(object):
def __init__(self, env, actionExecutor):
super(PlanExecutor, self).__init__()
self.env = env
self.actionExecutor = actionExecutor
def perform_next_action(self):
self.env.log("perform next action")
# save completed action to history if there is one
completedAction = get_current_action(self.env)
self.env.log("Completed action = {}".format(repr(completedAction)))
if not completedAction is None:
if not isinstance(completedAction, NullAction):
push_completed_action(self.env, completedAction)
# if we have moved, then save current location
if isinstance(completedAction, Move):
self._have_moved_wrapper()
self.env.log("set current action to NullAction")
# ensure that current action is cleared until we have another one
set_current_action(self.env, NullAction())
self.env.log("pop from plan")
# pop first action from plan
action = pop_planned_action(self.env)
if action is None:
self.env.log("No next action")
self.actionExecutor.all_done()
else:
self.env.log("Next action = {}".format(repr(action)))
set_current_action(self.env, action)
self.actionExecutor.do_action(action)
self.env.log("perform_next_action done")
# get current and previous positions and call have_moved
# it's not intended that this method be overridden
def _have_moved_wrapper(self):
self.env.log("Have moved")
pos = get_position(self.env)
lastPos = get_last_position(self.env)
self.have_moved(lastPos, pos)
save_waypoint(self.env, pos)
# hook for base classes to implement additional functionality
# after robot has moved
def have_moved(self, previousPos, currentPos):
pass
def save_position(self):
pos = get_position(self.env)
save_waypoint(self.env, pos)
def shutdown(self):
pass
'''
Abstract mapping class
'''
class AbstractMapper(object):
def __init__(self, env):
super(AbstractMapper, self).__init__()
self.env = env
# update map based on new sensor data
def update(self, position, sensors):
pass
# return the current map
def get_map(self):
return None
def shutdown(self):
pass
'''
Null mapper - does nothing, just a place holder for when no mapping is actually required
'''
class NullMapper(AbstractMapper):
def __init__(self, env):
super(NullMapper, self).__init__(env)
'''
Mapper that does no actual mapping, but logs all data to file for future analysis
'''
class FileLoggingMapper(AbstractMapper):
def __init__(self, env, save_data=True):
super(FileLoggingMapper, self).__init__(env)
self.save_data = save_data
if self.save_data:
self.open_data_file()
# save the data to file
def update(self, position, sensors):
if self.save_data:
self.save_update_data(position, sensors)
def open_data_file(self):
self.logFilename = tempfile.mktemp()
self.env.log("Saving sensor data to {}".format(self.logFilename))
self.first_write = True
try:
self.logFile = open(self.logFilename, 'r+')
except IOError:
self.env.log("Failed to open file: {}".format(self.logFilename))
self.logFile = None
def save_update_data(self, position, sensors):
if self.logFile:
data = { 'timestamp' : self.timestamp(),
'position' : position,
'leftSonar' : sensors.get_sensor('LeftSonar'),
'rightSonar' : sensors.get_sensor('RightSonar') }
jstr = json.dumps(data)
#self.env.log("Mapper.update: "+jstr)
if not self.first_write:
self.logFile.write(",\n")
self.logFile.write(jstr)
self.first_write = False
self.logFile.flush()
def timestamp(self):
return datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
# TODO should really block write access while doing this
def write_sensor_data_to_file(self, fp, buffer_size=1024):
if self.logFile:
self.logFile.seek(0)
fp.write('[\n')
while 1:
copy_buffer = self.logFile.read(buffer_size)
if copy_buffer:
fp.write(copy_buffer)
else:
break
fp.write(' ]\n')
self.logFile.seek(0, 2)
def shutdown(self):
if self.logFile:
self.logFile.close()
'''
Get the instance of the planner, creating an instance of the configured class if we don't already
have a planner instance
'''
def get_planner_instance(env):
global planner_instance
if not planner_instance:
fqcn = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_PLANNER_CLASS, DEFAULT_PLANNER_CLASS)
env.log("Creating a new planner instance of {}".format(fqcn))
klass = find_class(fqcn)
planner_instance = klass(env)
return planner_instance
'''
Get the instance of the plan executor, creating an instance of the class specified in the configuration
file if necessary.
'''
def get_executor_instance(env, actionExecutor):
global executor_instance
if not executor_instance:
fqcn = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_EXECUTOR_CLASS, DEFAULT_EXECUTOR_CLASS)
env.log("Creating a new executor instance of {}".format(fqcn))
klass = find_class(fqcn)
executor_instance = klass(env, actionExecutor)
# NOT THREAD SAFE
# even if we already had an instance of an executor the choreographe object might have become
# stale so we refresh it. We only have one executor instance at once so this should be OK
executor_instance.actionExecutor = actionExecutor
return executor_instance
'''
Get the instance of the mapper to use
'''
def get_mapper_instance(env):
global mapper_instance
if not mapper_instance:
fqcn = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_MAPPER_CLASS, DEFAULT_MAPPER_CLASS)
env.log("Creating a new mapper instance of {}".format(fqcn))
klass = find_class(fqcn)
mapper_instance = klass(env)
return mapper_instance
def run_updaters(env, position, sensors):
global wanderer_logger
# do the map update
mapper = get_mapper_instance(env)
if mapper:
try:
mapper.update(position, sensors)
except TypeError as e:
wanderer_logger.error("Error running mapper {0} update: {1}".format(repr(mapper), e))
# run any other updaters
updater_instances = get_updaters(env)
for updater in updater_instances:
try:
updater. update(position, sensors)
except TypeError as e:
wanderer_logger.error("Error running updater {0} update: {1}".format(repr(updater), e))
def get_updaters(env):
global updater_instances
if not updater_instances:
updater_instances = []
fqcns = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_UPDATER_CLASSES)
if fqcns:
for fqcn in fqcns:
env.log("Creating a new updater instance of {}".format(fqcn))
klass = find_class(fqcn)
updater = klass(env)
if updater:
updater_instances.append(updater)
return updater_instances
def make_wanderer_environment(box_):
env = make_environment(box_)
env.set_application_name(WANDERER_NAME)
return env
def load_event(env):
return from_json_string(env.memory.getData(MEM_CURRENT_EVENT))
def save_event(env, event):
env.memory.insertData(MEM_CURRENT_EVENT, to_json_string(event))
def load_plan(env):
return from_json_string(env.memory.getData(MEM_PLANNED_ACTIONS))
def save_plan(env, plan):
env.memory.insertData(MEM_PLANNED_ACTIONS, to_json_string(plan))
def load_completed_actions(env):
return from_json_string(env.memory.getData(MEM_COMPLETED_ACTIONS))
def save_completed_actions(env, actions):
env.memory.insertData(MEM_COMPLETED_ACTIONS, to_json_string(actions))
def pop_planned_action(env):
plan = load_plan(env)
action = None
if not plan is None:
if len(plan) > 0:
action = plan[0]
plan = plan[1:]
else:
plan = []
save_plan(env, plan)
return action
def get_current_action(env):
return from_json_string(env.memory.getData(MEM_CURRENT_ACTIONS))
def set_current_action(env, action):
env.memory.insertData(MEM_CURRENT_ACTIONS, to_json_string(action))
def push_completed_action(env, action):
actions = load_completed_actions(env)
if actions is None:
actions = []
actions.append(action)
save_completed_actions(env, actions)
def log_plan(env, msg, plan):
|
def save_direction(env, hRad):
env.memory.insertData(MEM_HEADING, hRad)
'''
Get the entire path
'''
def get_path(env):
return env.memory.getData(MEM_WALK_PATH)
def set_path(env, path):
env.memory.insertData(MEM_WALK_PATH, path)
'''
Get the last position the robot was at by looking at the path
'''
def get_last_position(env):
path = get_path(env)
pos = None
if not path is None:
try:
pos = path[-1]
except IndexError:
pass
return pos
'''
Get the current position of the robot
'''
def get_position(env):
# 1 = FRAME_WORLD
return env.motion.getPosition("Torso", 1, True)
def save_waypoint(env, waypoint):
path = get_path(env)
if path is None:
path = []
path.append(waypoint)
env.log("Path = "+str(path))
set_path(env, path)
| env.log(msg)
for p in plan:
env.log(str(p)) | identifier_body |
wanderer.py | '''
Created on Jan 19, 2013
@author: dsnowdon
'''
import os
import tempfile
import datetime
import json
import logging
from naoutil.jsonobj import to_json_string, from_json_string
from naoutil.general import find_class
import robotstate
from event import *
from action import *
from naoutil.naoenv import make_environment
'''
Here we define the memory locations used to store state
'''
MEM_SECURITY_DISTANCE = "WandererSecurityDistance"
MEM_HEADING = "WandererWalkHeading"
MEM_WALK_PATH = "WandererWalkPath"
MEM_DETECTED_FACE_DIRECTION = "WandererFaceDirection"
MEM_PLANNED_ACTIONS = "WandererActionsPlanned"
MEM_CURRENT_ACTIONS = "WandererActionsInProgress"
MEM_COMPLETED_ACTIONS = "WandererActionsCompleted"
MEM_CURRENT_EVENT = "WandererEvent"
MEM_MAP = "WandererMap"
MEM_LOCATION = "WandererLocation"
EVENT_LOOK_FOR_PEOPLE = "WandererEventLookForPeople"
DEFAULT_CONFIG_FILE = "wanderer"
PROPERTY_PLANNER_CLASS = "plannerClass"
DEFAULT_PLANNER_CLASS = "wanderer.randomwalk.RandomWalk"
PROPERTY_EXECUTOR_CLASS = "executorClass"
DEFAULT_EXECUTOR_CLASS = "wanderer.wanderer.PlanExecutor"
PROPERTY_MAPPER_CLASS = "mapperClass"
DEFAULT_MAPPER_CLASS = "wanderer.wanderer.NullMapper"
PROPERTY_UPDATER_CLASSES = "updaterClasses"
PROPERTY_HTTP_PORT = "httpPort"
DEFAULT_HTTP_PORT = 8080
PROPERTY_DATA_COLLECTOR_HOST = "dataCollectorHost"
PROPERTY_DATA_COLLECTOR_PORT = "dataCollectorPort"
PROPERTY_LOOK_FOR_PEOPLE = "lookForPeople"
STATIC_WEB_DIR = "web"
CENTRE_BIAS = False
HEAD_HORIZONTAL_OFFSET = 0
WANDERER_NAME = "wanderer"
# START GLOBALS
# We put instances of planners, executors and mappers here so we don't need to continually create
# new instances
planner_instance = None
executor_instance = None
mapper_instance = None
updater_instances = None
# END GLOBALS
wanderer_logger = logging.getLogger("wanderer.wanderer")
def init_state(env, startPos):
# declare events
env.memory.declareEvent(EVENT_LOOK_FOR_PEOPLE);
# getData & removeData throw errors if the value is not set,
# so ensure all the memory locations we want to use are initialised
env.memory.insertData(MEM_CURRENT_EVENT, None)
# set "security distance"
env.memory.insertData(MEM_SECURITY_DISTANCE, "0.25")
# should we look for people as we go?
lookForPeople = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_LOOK_FOR_PEOPLE)
if lookForPeople:
env.memory.raiseEvent(EVENT_LOOK_FOR_PEOPLE, True)
env.log("Looking for people")
else:
env.memory.raiseEvent(EVENT_LOOK_FOR_PEOPLE, False)
env.log("Not looking for people")
# set initial position (in list of positions)
env.memory.insertData(MEM_WALK_PATH, [startPos])
# current actions and completed actions
env.memory.insertData(MEM_PLANNED_ACTIONS, "")
env.memory.insertData(MEM_CURRENT_ACTIONS, "")
env.memory.insertData(MEM_COMPLETED_ACTIONS, "")
def shutdown(env):
planner = get_planner_instance(env)
planner.shutdown()
executor = get_executor_instance(env, None)
executor.shutdown()
mapper = get_mapper_instance(env)
mapper.shutdown()
updater_instances = get_updaters(env)
for updater in updater_instances:
updater.shutdown()
'''
Base class for wanderer planning.
Handles generating plans and reacting to events
'''
class Planner(object):
def __init__(self, env_):
super(Planner, self).__init__()
self.env = env_
def handleEvent(self, event, state):
plan = self.dispatch(event, state)
save_plan(self.env, plan)
log_plan(self.env, "New plan", plan)
return plan
# return true if this event should cause the current plan to be executed and
# a new plan created to react to it
def does_event_interrupt_plan(self, event, state):
return True
def dispatch(self, event, state):
methodName = 'handle'+ event.name()
try:
method = getattr(self, methodName)
return method(event, state)
except AttributeError:
self.env.log("Unimplemented event handler for: {}".format(event.name()))
def shutdown(self):
pass
'''
Base class for executing plans. Since we may need to trigger choreographe
boxes we delegate actually performing a single action to an actionExecutor
which in most cases will be the choreographe box that called us.
The actionExecutor must implement do_action(action) and all_done()
'''
class PlanExecutor(object):
def __init__(self, env, actionExecutor):
super(PlanExecutor, self).__init__()
self.env = env
self.actionExecutor = actionExecutor
def perform_next_action(self):
self.env.log("perform next action")
# save completed action to history if there is one
completedAction = get_current_action(self.env)
self.env.log("Completed action = {}".format(repr(completedAction)))
if not completedAction is None:
if not isinstance(completedAction, NullAction):
push_completed_action(self.env, completedAction)
# if we have moved, then save current location
if isinstance(completedAction, Move):
self._have_moved_wrapper()
self.env.log("set current action to NullAction")
# ensure that current action is cleared until we have another one
set_current_action(self.env, NullAction())
self.env.log("pop from plan")
# pop first action from plan
action = pop_planned_action(self.env)
if action is None:
self.env.log("No next action")
self.actionExecutor.all_done()
else:
self.env.log("Next action = {}".format(repr(action)))
set_current_action(self.env, action)
self.actionExecutor.do_action(action)
self.env.log("perform_next_action done")
# get current and previous positions and call have_moved
# it's not intended that this method be overridden
def _have_moved_wrapper(self):
self.env.log("Have moved")
pos = get_position(self.env)
lastPos = get_last_position(self.env)
self.have_moved(lastPos, pos)
save_waypoint(self.env, pos)
# hook for base classes to implement additional functionality
# after robot has moved
def have_moved(self, previousPos, currentPos):
pass
def save_position(self):
pos = get_position(self.env)
save_waypoint(self.env, pos)
def shutdown(self):
pass
'''
Abstract mapping class
'''
class AbstractMapper(object):
def __init__(self, env):
super(AbstractMapper, self).__init__()
self.env = env
# update map based on new sensor data
def update(self, position, sensors):
pass
# return the current map
def get_map(self):
return None
def shutdown(self):
pass
'''
Null mapper - does nothing, just a place holder for when no mapping is actually required
'''
class NullMapper(AbstractMapper):
def __init__(self, env):
super(NullMapper, self).__init__(env)
'''
Mapper that does no actual mapping, but logs all data to file for future analysis
'''
class FileLoggingMapper(AbstractMapper):
def __init__(self, env, save_data=True):
super(FileLoggingMapper, self).__init__(env)
self.save_data = save_data
if self.save_data:
self.open_data_file()
# save the data to file
def update(self, position, sensors):
if self.save_data:
self.save_update_data(position, sensors)
def open_data_file(self):
self.logFilename = tempfile.mktemp()
self.env.log("Saving sensor data to {}".format(self.logFilename))
self.first_write = True
try:
self.logFile = open(self.logFilename, 'r+')
except IOError:
self.env.log("Failed to open file: {}".format(self.logFilename))
self.logFile = None
def save_update_data(self, position, sensors):
if self.logFile:
data = { 'timestamp' : self.timestamp(),
'position' : position,
'leftSonar' : sensors.get_sensor('LeftSonar'),
'rightSonar' : sensors.get_sensor('RightSonar') }
jstr = json.dumps(data)
#self.env.log("Mapper.update: "+jstr)
if not self.first_write:
self.logFile.write(",\n")
self.logFile.write(jstr)
self.first_write = False
self.logFile.flush()
def timestamp(self):
return datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
# TODO should really block write access while doing this
def write_sensor_data_to_file(self, fp, buffer_size=1024):
if self.logFile:
self.logFile.seek(0)
fp.write('[\n')
while 1:
copy_buffer = self.logFile.read(buffer_size)
if copy_buffer:
fp.write(copy_buffer)
else:
break
fp.write(' ]\n')
self.logFile.seek(0, 2)
def shutdown(self):
if self.logFile:
|
'''
Get the instance of the planner, creating an instance of the configured class if we don't already
have a planner instance
'''
def get_planner_instance(env):
global planner_instance
if not planner_instance:
fqcn = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_PLANNER_CLASS, DEFAULT_PLANNER_CLASS)
env.log("Creating a new planner instance of {}".format(fqcn))
klass = find_class(fqcn)
planner_instance = klass(env)
return planner_instance
'''
Get the instance of the plan executor, creating an instance of the class specified in the configuration
file if necessary.
'''
def get_executor_instance(env, actionExecutor):
global executor_instance
if not executor_instance:
fqcn = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_EXECUTOR_CLASS, DEFAULT_EXECUTOR_CLASS)
env.log("Creating a new executor instance of {}".format(fqcn))
klass = find_class(fqcn)
executor_instance = klass(env, actionExecutor)
# NOT THREAD SAFE
# even if we already had an instance of an executor the choreographe object might have become
# stale so we refresh it. We only have one executor instance at once so this should be OK
executor_instance.actionExecutor = actionExecutor
return executor_instance
'''
Get the instance of the mapper to use
'''
def get_mapper_instance(env):
global mapper_instance
if not mapper_instance:
fqcn = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_MAPPER_CLASS, DEFAULT_MAPPER_CLASS)
env.log("Creating a new mapper instance of {}".format(fqcn))
klass = find_class(fqcn)
mapper_instance = klass(env)
return mapper_instance
def run_updaters(env, position, sensors):
global wanderer_logger
# do the map update
mapper = get_mapper_instance(env)
if mapper:
try:
mapper.update(position, sensors)
except TypeError as e:
wanderer_logger.error("Error running mapper {0} update: {1}".format(repr(mapper), e))
# run any other updaters
updater_instances = get_updaters(env)
for updater in updater_instances:
try:
updater. update(position, sensors)
except TypeError as e:
wanderer_logger.error("Error running updater {0} update: {1}".format(repr(updater), e))
def get_updaters(env):
global updater_instances
if not updater_instances:
updater_instances = []
fqcns = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_UPDATER_CLASSES)
if fqcns:
for fqcn in fqcns:
env.log("Creating a new updater instance of {}".format(fqcn))
klass = find_class(fqcn)
updater = klass(env)
if updater:
updater_instances.append(updater)
return updater_instances
def make_wanderer_environment(box_):
env = make_environment(box_)
env.set_application_name(WANDERER_NAME)
return env
def load_event(env):
return from_json_string(env.memory.getData(MEM_CURRENT_EVENT))
def save_event(env, event):
env.memory.insertData(MEM_CURRENT_EVENT, to_json_string(event))
def load_plan(env):
return from_json_string(env.memory.getData(MEM_PLANNED_ACTIONS))
def save_plan(env, plan):
env.memory.insertData(MEM_PLANNED_ACTIONS, to_json_string(plan))
def load_completed_actions(env):
return from_json_string(env.memory.getData(MEM_COMPLETED_ACTIONS))
def save_completed_actions(env, actions):
env.memory.insertData(MEM_COMPLETED_ACTIONS, to_json_string(actions))
def pop_planned_action(env):
plan = load_plan(env)
action = None
if not plan is None:
if len(plan) > 0:
action = plan[0]
plan = plan[1:]
else:
plan = []
save_plan(env, plan)
return action
def get_current_action(env):
return from_json_string(env.memory.getData(MEM_CURRENT_ACTIONS))
def set_current_action(env, action):
env.memory.insertData(MEM_CURRENT_ACTIONS, to_json_string(action))
def push_completed_action(env, action):
actions = load_completed_actions(env)
if actions is None:
actions = []
actions.append(action)
save_completed_actions(env, actions)
def log_plan(env, msg, plan):
env.log(msg)
for p in plan:
env.log(str(p))
def save_direction(env, hRad):
env.memory.insertData(MEM_HEADING, hRad)
'''
Get the entire path
'''
def get_path(env):
return env.memory.getData(MEM_WALK_PATH)
def set_path(env, path):
env.memory.insertData(MEM_WALK_PATH, path)
'''
Get the last position the robot was at by looking at the path
'''
def get_last_position(env):
path = get_path(env)
pos = None
if not path is None:
try:
pos = path[-1]
except IndexError:
pass
return pos
'''
Get the current position of the robot
'''
def get_position(env):
# 1 = FRAME_WORLD
return env.motion.getPosition("Torso", 1, True)
def save_waypoint(env, waypoint):
path = get_path(env)
if path is None:
path = []
path.append(waypoint)
env.log("Path = "+str(path))
set_path(env, path)
| self.logFile.close() | conditional_block |
wanderer.py | '''
Created on Jan 19, 2013
@author: dsnowdon
'''
import os
import tempfile
import datetime
import json
import logging
from naoutil.jsonobj import to_json_string, from_json_string
from naoutil.general import find_class
import robotstate
from event import *
from action import *
from naoutil.naoenv import make_environment
'''
Here we define the memory locations used to store state
'''
MEM_SECURITY_DISTANCE = "WandererSecurityDistance"
MEM_HEADING = "WandererWalkHeading"
MEM_WALK_PATH = "WandererWalkPath"
MEM_DETECTED_FACE_DIRECTION = "WandererFaceDirection"
MEM_PLANNED_ACTIONS = "WandererActionsPlanned"
MEM_CURRENT_ACTIONS = "WandererActionsInProgress"
MEM_COMPLETED_ACTIONS = "WandererActionsCompleted"
MEM_CURRENT_EVENT = "WandererEvent"
MEM_MAP = "WandererMap"
MEM_LOCATION = "WandererLocation"
EVENT_LOOK_FOR_PEOPLE = "WandererEventLookForPeople"
DEFAULT_CONFIG_FILE = "wanderer"
PROPERTY_PLANNER_CLASS = "plannerClass"
DEFAULT_PLANNER_CLASS = "wanderer.randomwalk.RandomWalk"
PROPERTY_EXECUTOR_CLASS = "executorClass"
DEFAULT_EXECUTOR_CLASS = "wanderer.wanderer.PlanExecutor"
PROPERTY_MAPPER_CLASS = "mapperClass"
DEFAULT_MAPPER_CLASS = "wanderer.wanderer.NullMapper"
PROPERTY_UPDATER_CLASSES = "updaterClasses"
PROPERTY_HTTP_PORT = "httpPort"
DEFAULT_HTTP_PORT = 8080
PROPERTY_DATA_COLLECTOR_HOST = "dataCollectorHost"
PROPERTY_DATA_COLLECTOR_PORT = "dataCollectorPort"
PROPERTY_LOOK_FOR_PEOPLE = "lookForPeople"
STATIC_WEB_DIR = "web"
CENTRE_BIAS = False
HEAD_HORIZONTAL_OFFSET = 0
WANDERER_NAME = "wanderer"
# START GLOBALS
# We put instances of planners, executors and mappers here so we don't need to continually create
# new instances
planner_instance = None
executor_instance = None
mapper_instance = None
updater_instances = None
# END GLOBALS
wanderer_logger = logging.getLogger("wanderer.wanderer")
def init_state(env, startPos):
# declare events
env.memory.declareEvent(EVENT_LOOK_FOR_PEOPLE);
# getData & removeData throw errors if the value is not set,
# so ensure all the memory locations we want to use are initialised
env.memory.insertData(MEM_CURRENT_EVENT, None)
# set "security distance"
env.memory.insertData(MEM_SECURITY_DISTANCE, "0.25")
# should we look for people as we go?
lookForPeople = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_LOOK_FOR_PEOPLE)
if lookForPeople:
env.memory.raiseEvent(EVENT_LOOK_FOR_PEOPLE, True)
env.log("Looking for people")
else:
env.memory.raiseEvent(EVENT_LOOK_FOR_PEOPLE, False)
env.log("Not looking for people")
# set initial position (in list of positions)
env.memory.insertData(MEM_WALK_PATH, [startPos])
# current actions and completed actions
env.memory.insertData(MEM_PLANNED_ACTIONS, "")
env.memory.insertData(MEM_CURRENT_ACTIONS, "")
env.memory.insertData(MEM_COMPLETED_ACTIONS, "")
def shutdown(env):
planner = get_planner_instance(env)
planner.shutdown()
executor = get_executor_instance(env, None)
executor.shutdown()
mapper = get_mapper_instance(env)
mapper.shutdown()
updater_instances = get_updaters(env)
for updater in updater_instances:
updater.shutdown()
'''
Base class for wanderer planning.
Handles generating plans and reacting to events
'''
class Planner(object):
def __init__(self, env_):
super(Planner, self).__init__()
self.env = env_
def handleEvent(self, event, state):
plan = self.dispatch(event, state)
save_plan(self.env, plan)
log_plan(self.env, "New plan", plan)
return plan
# return true if this event should cause the current plan to be executed and
# a new plan created to react to it
def does_event_interrupt_plan(self, event, state):
return True
def dispatch(self, event, state):
methodName = 'handle'+ event.name()
try:
method = getattr(self, methodName)
return method(event, state)
except AttributeError:
self.env.log("Unimplemented event handler for: {}".format(event.name()))
def shutdown(self):
pass
'''
Base class for executing plans. Since we may need to trigger choreographe
boxes we delegate actually performing a single action to an actionExecutor
which in most cases will be the choreographe box that called us.
The actionExecutor must implement do_action(action) and all_done()
'''
class PlanExecutor(object):
def __init__(self, env, actionExecutor):
super(PlanExecutor, self).__init__()
self.env = env
self.actionExecutor = actionExecutor
def perform_next_action(self):
self.env.log("perform next action")
# save completed action to history if there is one
completedAction = get_current_action(self.env)
self.env.log("Completed action = {}".format(repr(completedAction)))
if not completedAction is None:
if not isinstance(completedAction, NullAction):
push_completed_action(self.env, completedAction)
# if we have moved, then save current location
if isinstance(completedAction, Move):
self._have_moved_wrapper()
self.env.log("set current action to NullAction")
# ensure that current action is cleared until we have another one
set_current_action(self.env, NullAction())
self.env.log("pop from plan")
# pop first action from plan
action = pop_planned_action(self.env)
if action is None:
self.env.log("No next action")
self.actionExecutor.all_done()
else:
self.env.log("Next action = {}".format(repr(action)))
set_current_action(self.env, action)
self.actionExecutor.do_action(action)
self.env.log("perform_next_action done")
# get current and previous positions and call have_moved
# it's not intended that this method be overridden
def _have_moved_wrapper(self):
self.env.log("Have moved")
pos = get_position(self.env)
lastPos = get_last_position(self.env)
self.have_moved(lastPos, pos)
save_waypoint(self.env, pos)
# hook for base classes to implement additional functionality
# after robot has moved
def have_moved(self, previousPos, currentPos):
pass
def save_position(self):
pos = get_position(self.env)
save_waypoint(self.env, pos)
def shutdown(self):
pass
'''
Abstract mapping class
'''
class AbstractMapper(object):
def __init__(self, env):
super(AbstractMapper, self).__init__()
self.env = env
# update map based on new sensor data
def update(self, position, sensors):
pass
# return the current map
def get_map(self):
return None
def shutdown(self):
pass
'''
Null mapper - does nothing, just a place holder for when no mapping is actually required
'''
class NullMapper(AbstractMapper):
def __init__(self, env):
super(NullMapper, self).__init__(env)
'''
Mapper that does no actual mapping, but logs all data to file for future analysis
'''
class FileLoggingMapper(AbstractMapper):
def __init__(self, env, save_data=True):
super(FileLoggingMapper, self).__init__(env)
self.save_data = save_data
if self.save_data:
self.open_data_file()
# save the data to file
def update(self, position, sensors):
if self.save_data:
self.save_update_data(position, sensors)
def open_data_file(self):
self.logFilename = tempfile.mktemp()
self.env.log("Saving sensor data to {}".format(self.logFilename))
self.first_write = True
try:
self.logFile = open(self.logFilename, 'r+')
except IOError:
self.env.log("Failed to open file: {}".format(self.logFilename))
self.logFile = None
def save_update_data(self, position, sensors):
if self.logFile:
data = { 'timestamp' : self.timestamp(),
'position' : position,
'leftSonar' : sensors.get_sensor('LeftSonar'),
'rightSonar' : sensors.get_sensor('RightSonar') }
jstr = json.dumps(data)
#self.env.log("Mapper.update: "+jstr)
if not self.first_write:
self.logFile.write(",\n")
self.logFile.write(jstr)
self.first_write = False
self.logFile.flush()
def timestamp(self):
return datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
# TODO should really block write access while doing this
def | (self, fp, buffer_size=1024):
if self.logFile:
self.logFile.seek(0)
fp.write('[\n')
while 1:
copy_buffer = self.logFile.read(buffer_size)
if copy_buffer:
fp.write(copy_buffer)
else:
break
fp.write(' ]\n')
self.logFile.seek(0, 2)
def shutdown(self):
if self.logFile:
self.logFile.close()
'''
Get the instance of the planner, creating an instance of the configured class if we don't already
have a planner instance
'''
def get_planner_instance(env):
global planner_instance
if not planner_instance:
fqcn = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_PLANNER_CLASS, DEFAULT_PLANNER_CLASS)
env.log("Creating a new planner instance of {}".format(fqcn))
klass = find_class(fqcn)
planner_instance = klass(env)
return planner_instance
'''
Get the instance of the plan executor, creating an instance of the class specified in the configuration
file if necessary.
'''
def get_executor_instance(env, actionExecutor):
global executor_instance
if not executor_instance:
fqcn = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_EXECUTOR_CLASS, DEFAULT_EXECUTOR_CLASS)
env.log("Creating a new executor instance of {}".format(fqcn))
klass = find_class(fqcn)
executor_instance = klass(env, actionExecutor)
# NOT THREAD SAFE
# even if we already had an instance of an executor the choreographe object might have become
# stale so we refresh it. We only have one executor instance at once so this should be OK
executor_instance.actionExecutor = actionExecutor
return executor_instance
'''
Get the instance of the mapper to use
'''
def get_mapper_instance(env):
global mapper_instance
if not mapper_instance:
fqcn = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_MAPPER_CLASS, DEFAULT_MAPPER_CLASS)
env.log("Creating a new mapper instance of {}".format(fqcn))
klass = find_class(fqcn)
mapper_instance = klass(env)
return mapper_instance
def run_updaters(env, position, sensors):
global wanderer_logger
# do the map update
mapper = get_mapper_instance(env)
if mapper:
try:
mapper.update(position, sensors)
except TypeError as e:
wanderer_logger.error("Error running mapper {0} update: {1}".format(repr(mapper), e))
# run any other updaters
updater_instances = get_updaters(env)
for updater in updater_instances:
try:
updater. update(position, sensors)
except TypeError as e:
wanderer_logger.error("Error running updater {0} update: {1}".format(repr(updater), e))
def get_updaters(env):
global updater_instances
if not updater_instances:
updater_instances = []
fqcns = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_UPDATER_CLASSES)
if fqcns:
for fqcn in fqcns:
env.log("Creating a new updater instance of {}".format(fqcn))
klass = find_class(fqcn)
updater = klass(env)
if updater:
updater_instances.append(updater)
return updater_instances
def make_wanderer_environment(box_):
env = make_environment(box_)
env.set_application_name(WANDERER_NAME)
return env
def load_event(env):
return from_json_string(env.memory.getData(MEM_CURRENT_EVENT))
def save_event(env, event):
env.memory.insertData(MEM_CURRENT_EVENT, to_json_string(event))
def load_plan(env):
return from_json_string(env.memory.getData(MEM_PLANNED_ACTIONS))
def save_plan(env, plan):
env.memory.insertData(MEM_PLANNED_ACTIONS, to_json_string(plan))
def load_completed_actions(env):
return from_json_string(env.memory.getData(MEM_COMPLETED_ACTIONS))
def save_completed_actions(env, actions):
env.memory.insertData(MEM_COMPLETED_ACTIONS, to_json_string(actions))
def pop_planned_action(env):
plan = load_plan(env)
action = None
if not plan is None:
if len(plan) > 0:
action = plan[0]
plan = plan[1:]
else:
plan = []
save_plan(env, plan)
return action
def get_current_action(env):
return from_json_string(env.memory.getData(MEM_CURRENT_ACTIONS))
def set_current_action(env, action):
env.memory.insertData(MEM_CURRENT_ACTIONS, to_json_string(action))
def push_completed_action(env, action):
actions = load_completed_actions(env)
if actions is None:
actions = []
actions.append(action)
save_completed_actions(env, actions)
def log_plan(env, msg, plan):
env.log(msg)
for p in plan:
env.log(str(p))
def save_direction(env, hRad):
env.memory.insertData(MEM_HEADING, hRad)
'''
Get the entire path
'''
def get_path(env):
return env.memory.getData(MEM_WALK_PATH)
def set_path(env, path):
env.memory.insertData(MEM_WALK_PATH, path)
'''
Get the last position the robot was at by looking at the path
'''
def get_last_position(env):
path = get_path(env)
pos = None
if not path is None:
try:
pos = path[-1]
except IndexError:
pass
return pos
'''
Get the current position of the robot
'''
def get_position(env):
# 1 = FRAME_WORLD
return env.motion.getPosition("Torso", 1, True)
def save_waypoint(env, waypoint):
path = get_path(env)
if path is None:
path = []
path.append(waypoint)
env.log("Path = "+str(path))
set_path(env, path)
| write_sensor_data_to_file | identifier_name |
wanderer.py | '''
Created on Jan 19, 2013
@author: dsnowdon
'''
import os
import tempfile
import datetime
import json
import logging
from naoutil.jsonobj import to_json_string, from_json_string
from naoutil.general import find_class
import robotstate
from event import *
from action import *
from naoutil.naoenv import make_environment
'''
Here we define the memory locations used to store state
'''
MEM_SECURITY_DISTANCE = "WandererSecurityDistance"
MEM_HEADING = "WandererWalkHeading"
MEM_WALK_PATH = "WandererWalkPath"
MEM_DETECTED_FACE_DIRECTION = "WandererFaceDirection"
MEM_PLANNED_ACTIONS = "WandererActionsPlanned"
MEM_CURRENT_ACTIONS = "WandererActionsInProgress"
MEM_COMPLETED_ACTIONS = "WandererActionsCompleted"
MEM_CURRENT_EVENT = "WandererEvent"
MEM_MAP = "WandererMap"
MEM_LOCATION = "WandererLocation"
EVENT_LOOK_FOR_PEOPLE = "WandererEventLookForPeople"
DEFAULT_CONFIG_FILE = "wanderer"
PROPERTY_PLANNER_CLASS = "plannerClass"
DEFAULT_PLANNER_CLASS = "wanderer.randomwalk.RandomWalk"
PROPERTY_EXECUTOR_CLASS = "executorClass"
DEFAULT_EXECUTOR_CLASS = "wanderer.wanderer.PlanExecutor"
PROPERTY_MAPPER_CLASS = "mapperClass"
DEFAULT_MAPPER_CLASS = "wanderer.wanderer.NullMapper"
PROPERTY_UPDATER_CLASSES = "updaterClasses"
PROPERTY_HTTP_PORT = "httpPort"
DEFAULT_HTTP_PORT = 8080
PROPERTY_DATA_COLLECTOR_HOST = "dataCollectorHost"
PROPERTY_DATA_COLLECTOR_PORT = "dataCollectorPort"
PROPERTY_LOOK_FOR_PEOPLE = "lookForPeople"
STATIC_WEB_DIR = "web"
CENTRE_BIAS = False | WANDERER_NAME = "wanderer"
# START GLOBALS
# We put instances of planners, executors and mappers here so we don't need to continually create
# new instances
planner_instance = None
executor_instance = None
mapper_instance = None
updater_instances = None
# END GLOBALS
wanderer_logger = logging.getLogger("wanderer.wanderer")
def init_state(env, startPos):
# declare events
env.memory.declareEvent(EVENT_LOOK_FOR_PEOPLE);
# getData & removeData throw errors if the value is not set,
# so ensure all the memory locations we want to use are initialised
env.memory.insertData(MEM_CURRENT_EVENT, None)
# set "security distance"
env.memory.insertData(MEM_SECURITY_DISTANCE, "0.25")
# should we look for people as we go?
lookForPeople = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_LOOK_FOR_PEOPLE)
if lookForPeople:
env.memory.raiseEvent(EVENT_LOOK_FOR_PEOPLE, True)
env.log("Looking for people")
else:
env.memory.raiseEvent(EVENT_LOOK_FOR_PEOPLE, False)
env.log("Not looking for people")
# set initial position (in list of positions)
env.memory.insertData(MEM_WALK_PATH, [startPos])
# current actions and completed actions
env.memory.insertData(MEM_PLANNED_ACTIONS, "")
env.memory.insertData(MEM_CURRENT_ACTIONS, "")
env.memory.insertData(MEM_COMPLETED_ACTIONS, "")
def shutdown(env):
planner = get_planner_instance(env)
planner.shutdown()
executor = get_executor_instance(env, None)
executor.shutdown()
mapper = get_mapper_instance(env)
mapper.shutdown()
updater_instances = get_updaters(env)
for updater in updater_instances:
updater.shutdown()
'''
Base class for wanderer planning.
Handles generating plans and reacting to events
'''
class Planner(object):
def __init__(self, env_):
super(Planner, self).__init__()
self.env = env_
def handleEvent(self, event, state):
plan = self.dispatch(event, state)
save_plan(self.env, plan)
log_plan(self.env, "New plan", plan)
return plan
# return true if this event should cause the current plan to be executed and
# a new plan created to react to it
def does_event_interrupt_plan(self, event, state):
return True
def dispatch(self, event, state):
methodName = 'handle'+ event.name()
try:
method = getattr(self, methodName)
return method(event, state)
except AttributeError:
self.env.log("Unimplemented event handler for: {}".format(event.name()))
def shutdown(self):
pass
'''
Base class for executing plans. Since we may need to trigger choreographe
boxes we delegate actually performing a single action to an actionExecutor
which in most cases will be the choreographe box that called us.
The actionExecutor must implement do_action(action) and all_done()
'''
class PlanExecutor(object):
def __init__(self, env, actionExecutor):
super(PlanExecutor, self).__init__()
self.env = env
self.actionExecutor = actionExecutor
def perform_next_action(self):
self.env.log("perform next action")
# save completed action to history if there is one
completedAction = get_current_action(self.env)
self.env.log("Completed action = {}".format(repr(completedAction)))
if not completedAction is None:
if not isinstance(completedAction, NullAction):
push_completed_action(self.env, completedAction)
# if we have moved, then save current location
if isinstance(completedAction, Move):
self._have_moved_wrapper()
self.env.log("set current action to NullAction")
# ensure that current action is cleared until we have another one
set_current_action(self.env, NullAction())
self.env.log("pop from plan")
# pop first action from plan
action = pop_planned_action(self.env)
if action is None:
self.env.log("No next action")
self.actionExecutor.all_done()
else:
self.env.log("Next action = {}".format(repr(action)))
set_current_action(self.env, action)
self.actionExecutor.do_action(action)
self.env.log("perform_next_action done")
# get current and previous positions and call have_moved
# it's not intended that this method be overridden
def _have_moved_wrapper(self):
self.env.log("Have moved")
pos = get_position(self.env)
lastPos = get_last_position(self.env)
self.have_moved(lastPos, pos)
save_waypoint(self.env, pos)
# hook for base classes to implement additional functionality
# after robot has moved
def have_moved(self, previousPos, currentPos):
pass
def save_position(self):
pos = get_position(self.env)
save_waypoint(self.env, pos)
def shutdown(self):
pass
'''
Abstract mapping class
'''
class AbstractMapper(object):
def __init__(self, env):
super(AbstractMapper, self).__init__()
self.env = env
# update map based on new sensor data
def update(self, position, sensors):
pass
# return the current map
def get_map(self):
return None
def shutdown(self):
pass
'''
Null mapper - does nothing, just a place holder for when no mapping is actually required
'''
class NullMapper(AbstractMapper):
def __init__(self, env):
super(NullMapper, self).__init__(env)
'''
Mapper that does no actual mapping, but logs all data to file for future analysis
'''
class FileLoggingMapper(AbstractMapper):
def __init__(self, env, save_data=True):
super(FileLoggingMapper, self).__init__(env)
self.save_data = save_data
if self.save_data:
self.open_data_file()
# save the data to file
def update(self, position, sensors):
if self.save_data:
self.save_update_data(position, sensors)
def open_data_file(self):
self.logFilename = tempfile.mktemp()
self.env.log("Saving sensor data to {}".format(self.logFilename))
self.first_write = True
try:
self.logFile = open(self.logFilename, 'r+')
except IOError:
self.env.log("Failed to open file: {}".format(self.logFilename))
self.logFile = None
def save_update_data(self, position, sensors):
if self.logFile:
data = { 'timestamp' : self.timestamp(),
'position' : position,
'leftSonar' : sensors.get_sensor('LeftSonar'),
'rightSonar' : sensors.get_sensor('RightSonar') }
jstr = json.dumps(data)
#self.env.log("Mapper.update: "+jstr)
if not self.first_write:
self.logFile.write(",\n")
self.logFile.write(jstr)
self.first_write = False
self.logFile.flush()
def timestamp(self):
return datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
# TODO should really block write access while doing this
def write_sensor_data_to_file(self, fp, buffer_size=1024):
if self.logFile:
self.logFile.seek(0)
fp.write('[\n')
while 1:
copy_buffer = self.logFile.read(buffer_size)
if copy_buffer:
fp.write(copy_buffer)
else:
break
fp.write(' ]\n')
self.logFile.seek(0, 2)
def shutdown(self):
if self.logFile:
self.logFile.close()
'''
Get the instance of the planner, creating an instance of the configured class if we don't already
have a planner instance
'''
def get_planner_instance(env):
global planner_instance
if not planner_instance:
fqcn = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_PLANNER_CLASS, DEFAULT_PLANNER_CLASS)
env.log("Creating a new planner instance of {}".format(fqcn))
klass = find_class(fqcn)
planner_instance = klass(env)
return planner_instance
'''
Get the instance of the plan executor, creating an instance of the class specified in the configuration
file if necessary.
'''
def get_executor_instance(env, actionExecutor):
global executor_instance
if not executor_instance:
fqcn = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_EXECUTOR_CLASS, DEFAULT_EXECUTOR_CLASS)
env.log("Creating a new executor instance of {}".format(fqcn))
klass = find_class(fqcn)
executor_instance = klass(env, actionExecutor)
# NOT THREAD SAFE
# even if we already had an instance of an executor the choreographe object might have become
# stale so we refresh it. We only have one executor instance at once so this should be OK
executor_instance.actionExecutor = actionExecutor
return executor_instance
'''
Get the instance of the mapper to use
'''
def get_mapper_instance(env):
global mapper_instance
if not mapper_instance:
fqcn = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_MAPPER_CLASS, DEFAULT_MAPPER_CLASS)
env.log("Creating a new mapper instance of {}".format(fqcn))
klass = find_class(fqcn)
mapper_instance = klass(env)
return mapper_instance
def run_updaters(env, position, sensors):
global wanderer_logger
# do the map update
mapper = get_mapper_instance(env)
if mapper:
try:
mapper.update(position, sensors)
except TypeError as e:
wanderer_logger.error("Error running mapper {0} update: {1}".format(repr(mapper), e))
# run any other updaters
updater_instances = get_updaters(env)
for updater in updater_instances:
try:
updater. update(position, sensors)
except TypeError as e:
wanderer_logger.error("Error running updater {0} update: {1}".format(repr(updater), e))
def get_updaters(env):
global updater_instances
if not updater_instances:
updater_instances = []
fqcns = env.get_property(DEFAULT_CONFIG_FILE, PROPERTY_UPDATER_CLASSES)
if fqcns:
for fqcn in fqcns:
env.log("Creating a new updater instance of {}".format(fqcn))
klass = find_class(fqcn)
updater = klass(env)
if updater:
updater_instances.append(updater)
return updater_instances
def make_wanderer_environment(box_):
env = make_environment(box_)
env.set_application_name(WANDERER_NAME)
return env
def load_event(env):
return from_json_string(env.memory.getData(MEM_CURRENT_EVENT))
def save_event(env, event):
env.memory.insertData(MEM_CURRENT_EVENT, to_json_string(event))
def load_plan(env):
return from_json_string(env.memory.getData(MEM_PLANNED_ACTIONS))
def save_plan(env, plan):
env.memory.insertData(MEM_PLANNED_ACTIONS, to_json_string(plan))
def load_completed_actions(env):
return from_json_string(env.memory.getData(MEM_COMPLETED_ACTIONS))
def save_completed_actions(env, actions):
env.memory.insertData(MEM_COMPLETED_ACTIONS, to_json_string(actions))
def pop_planned_action(env):
plan = load_plan(env)
action = None
if not plan is None:
if len(plan) > 0:
action = plan[0]
plan = plan[1:]
else:
plan = []
save_plan(env, plan)
return action
def get_current_action(env):
return from_json_string(env.memory.getData(MEM_CURRENT_ACTIONS))
def set_current_action(env, action):
env.memory.insertData(MEM_CURRENT_ACTIONS, to_json_string(action))
def push_completed_action(env, action):
actions = load_completed_actions(env)
if actions is None:
actions = []
actions.append(action)
save_completed_actions(env, actions)
def log_plan(env, msg, plan):
env.log(msg)
for p in plan:
env.log(str(p))
def save_direction(env, hRad):
env.memory.insertData(MEM_HEADING, hRad)
'''
Get the entire path
'''
def get_path(env):
return env.memory.getData(MEM_WALK_PATH)
def set_path(env, path):
env.memory.insertData(MEM_WALK_PATH, path)
'''
Get the last position the robot was at by looking at the path
'''
def get_last_position(env):
path = get_path(env)
pos = None
if not path is None:
try:
pos = path[-1]
except IndexError:
pass
return pos
'''
Get the current position of the robot
'''
def get_position(env):
# 1 = FRAME_WORLD
return env.motion.getPosition("Torso", 1, True)
def save_waypoint(env, waypoint):
path = get_path(env)
if path is None:
path = []
path.append(waypoint)
env.log("Path = "+str(path))
set_path(env, path) | HEAD_HORIZONTAL_OFFSET = 0 | random_line_split |
server.ts | import * as ws from "ws";
import { SERVER_HOST, SERVER_PATH, SERVER_PORT } from "../shared/config";
import { HEARTBEAT_INTERVAL_MS } from "../shared/const";
import { ServerRooms } from "./room/serverRooms";
import { ServerPlayer } from "./room/serverPlayer";
export interface Socket extends ws {
pingSent: number;
pongReceived: number;
latency: number;
}
export class | {
private roomManager = new ServerRooms();
private ws: ws.Server;
private pingInterval: NodeJS.Timeout;
constructor() {
this.ws = new ws.Server({
host: "0.0.0.0",
port: SERVER_PORT,
path: SERVER_PATH,
maxPayload: 256,
clientTracking: true,
});
this.ws.on("connection", (socket: Socket) => {
const player = new ServerPlayer(socket, this.roomManager.emitter);
socket.pingSent = socket.pongReceived = new Date().getTime();
socket.latency = 0;
socket.on("pong", () => {
socket.pongReceived = new Date().getTime();
socket.latency = new Date().getTime() - socket.pingSent;
});
socket.on("close", async () => {
player.connected = false;
await this.roomManager.removePlayer(player);
});
});
this.pingInterval = setInterval(() => {
((this.ws.clients as unknown) as Socket[]).forEach((client: Socket) => {
if (client.pongReceived - client.pingSent > HEARTBEAT_INTERVAL_MS * 2) {
return client.terminate();
}
client.pingSent = new Date().getTime();
client.ping();
});
}, HEARTBEAT_INTERVAL_MS);
console.debug(`Running WebSocket server at ${SERVER_HOST}:${SERVER_PATH}${SERVER_PORT}`);
}
}
| Server | identifier_name |
server.ts | import * as ws from "ws";
import { SERVER_HOST, SERVER_PATH, SERVER_PORT } from "../shared/config";
import { HEARTBEAT_INTERVAL_MS } from "../shared/const";
import { ServerRooms } from "./room/serverRooms";
import { ServerPlayer } from "./room/serverPlayer";
export interface Socket extends ws {
pingSent: number;
pongReceived: number;
latency: number;
}
export class Server {
private roomManager = new ServerRooms();
private ws: ws.Server;
private pingInterval: NodeJS.Timeout;
constructor() |
}
| {
this.ws = new ws.Server({
host: "0.0.0.0",
port: SERVER_PORT,
path: SERVER_PATH,
maxPayload: 256,
clientTracking: true,
});
this.ws.on("connection", (socket: Socket) => {
const player = new ServerPlayer(socket, this.roomManager.emitter);
socket.pingSent = socket.pongReceived = new Date().getTime();
socket.latency = 0;
socket.on("pong", () => {
socket.pongReceived = new Date().getTime();
socket.latency = new Date().getTime() - socket.pingSent;
});
socket.on("close", async () => {
player.connected = false;
await this.roomManager.removePlayer(player);
});
});
this.pingInterval = setInterval(() => {
((this.ws.clients as unknown) as Socket[]).forEach((client: Socket) => {
if (client.pongReceived - client.pingSent > HEARTBEAT_INTERVAL_MS * 2) {
return client.terminate();
}
client.pingSent = new Date().getTime();
client.ping();
});
}, HEARTBEAT_INTERVAL_MS);
console.debug(`Running WebSocket server at ${SERVER_HOST}:${SERVER_PATH}${SERVER_PORT}`);
} | identifier_body |
server.ts | import * as ws from "ws";
import { SERVER_HOST, SERVER_PATH, SERVER_PORT } from "../shared/config";
import { HEARTBEAT_INTERVAL_MS } from "../shared/const";
import { ServerRooms } from "./room/serverRooms";
import { ServerPlayer } from "./room/serverPlayer";
export interface Socket extends ws {
pingSent: number;
pongReceived: number;
latency: number;
}
export class Server {
private roomManager = new ServerRooms();
private ws: ws.Server;
private pingInterval: NodeJS.Timeout;
constructor() {
this.ws = new ws.Server({
host: "0.0.0.0",
port: SERVER_PORT,
path: SERVER_PATH,
maxPayload: 256,
clientTracking: true,
});
this.ws.on("connection", (socket: Socket) => {
const player = new ServerPlayer(socket, this.roomManager.emitter);
socket.pingSent = socket.pongReceived = new Date().getTime();
socket.latency = 0;
socket.on("pong", () => {
socket.pongReceived = new Date().getTime();
socket.latency = new Date().getTime() - socket.pingSent;
});
socket.on("close", async () => {
player.connected = false;
await this.roomManager.removePlayer(player);
});
});
this.pingInterval = setInterval(() => {
((this.ws.clients as unknown) as Socket[]).forEach((client: Socket) => {
if (client.pongReceived - client.pingSent > HEARTBEAT_INTERVAL_MS * 2) |
client.pingSent = new Date().getTime();
client.ping();
});
}, HEARTBEAT_INTERVAL_MS);
console.debug(`Running WebSocket server at ${SERVER_HOST}:${SERVER_PATH}${SERVER_PORT}`);
}
}
| {
return client.terminate();
} | conditional_block |
server.ts | import * as ws from "ws";
import { SERVER_HOST, SERVER_PATH, SERVER_PORT } from "../shared/config";
import { HEARTBEAT_INTERVAL_MS } from "../shared/const";
import { ServerRooms } from "./room/serverRooms";
import { ServerPlayer } from "./room/serverPlayer";
export interface Socket extends ws {
pingSent: number;
pongReceived: number;
latency: number;
}
export class Server {
private roomManager = new ServerRooms();
private ws: ws.Server;
private pingInterval: NodeJS.Timeout;
constructor() {
this.ws = new ws.Server({
host: "0.0.0.0",
port: SERVER_PORT,
path: SERVER_PATH,
maxPayload: 256,
clientTracking: true,
});
this.ws.on("connection", (socket: Socket) => {
const player = new ServerPlayer(socket, this.roomManager.emitter);
socket.pingSent = socket.pongReceived = new Date().getTime();
socket.latency = 0;
socket.on("pong", () => {
socket.pongReceived = new Date().getTime();
socket.latency = new Date().getTime() - socket.pingSent;
});
socket.on("close", async () => {
player.connected = false;
await this.roomManager.removePlayer(player);
});
});
this.pingInterval = setInterval(() => {
((this.ws.clients as unknown) as Socket[]).forEach((client: Socket) => {
if (client.pongReceived - client.pingSent > HEARTBEAT_INTERVAL_MS * 2) {
return client.terminate();
}
client.pingSent = new Date().getTime();
client.ping();
}); | }, HEARTBEAT_INTERVAL_MS);
console.debug(`Running WebSocket server at ${SERVER_HOST}:${SERVER_PATH}${SERVER_PORT}`);
}
} | random_line_split | |
parametric_system.py | import floq.core.fixed_system as fs
import floq.evolution as ev
import floq.errors as er
import floq.helpers.index as h
class ParametricSystemBase(object):
"""
Base class to specify a physical system that still has open parameters,
such as the control amplitudes, the control duration, or other arbitrary
parameters in the Hamiltonian.
This needs to be sub-classed, and a subclass should provide:
- get_system(controls)
"""
def get_system(self, controls, t):
raise NotImplementedError("get_system not implemented.")
def is_nz_ok(self, controls, t):
system = self.get_system(controls, t)
try:
u = ev.evolve_system(system)
except er.EigenvalueNumberError:
return False
return h.is_unitary(u)
def set_nz(self, controls, t):
if self.is_nz_ok(controls, t):
self.decrease_nz_until_not_ok(controls, t, step=max(10, self.nz/5))
self.decrease_nz_until_not_ok(controls, t, step=max(10, self.nz/10))
self.decrease_nz_until_not_ok(controls, t, step=2)
self.increase_nz_until_ok(controls, t, step=2)
else:
self.increase_nz_until_ok(controls, t, step=max(10, self.nz/5))
self.decrease_nz_until_not_ok(controls, t, step=2)
self.increase_nz_until_ok(controls, t, step=2)
def increase_nz_until_ok(self, controls, t, step=2):
while self.is_nz_ok(controls, t) is False:
self.nz += h.make_even(step)
def decrease_nz_until_not_ok(self, controls, t, step=2):
while self.is_nz_ok(controls, t) and self.nz-step > 3:
self.nz -= h.make_even(step)
class ParametricSystemWithFunctions(ParametricSystemBase):
"""
A system with parametric hf and dhf, which are passed as callables to the constructor.
hf has to have the form hf(a,parameters)
"""
def __init__(self, hf, dhf, nz, omega, parameters):
"""
hf: callable hf(controls,parameters,omega)
dhf: callable dhf(controls,parameters,omega)
omega: 2 pi/T, the period of the Hamiltonian
nz: number of Fourier modes to be considered during evolution
parameters: a data structure that holds parameters for hf and dhf
(dictionary is probably the best idea)
"""
self.hf = hf
self.dhf = dhf
self.omega = omega
self.nz = nz
self.parameters = parameters
def calculate_hf(self, controls):
|
def calculate_dhf(self, controls):
return self.dhf(controls, self.parameters, self.omega)
def get_system(self, controls, t):
hf = self.calculate_hf(controls)
dhf = self.calculate_dhf(controls)
return fs.FixedSystem(hf, dhf, self.nz, self.omega, t)
| return self.hf(controls, self.parameters, self.omega) | identifier_body |
parametric_system.py | import floq.core.fixed_system as fs
import floq.evolution as ev
import floq.errors as er
import floq.helpers.index as h
class ParametricSystemBase(object):
"""
Base class to specify a physical system that still has open parameters,
such as the control amplitudes, the control duration, or other arbitrary
parameters in the Hamiltonian.
This needs to be sub-classed, and a subclass should provide:
- get_system(controls)
|
def is_nz_ok(self, controls, t):
system = self.get_system(controls, t)
try:
u = ev.evolve_system(system)
except er.EigenvalueNumberError:
return False
return h.is_unitary(u)
def set_nz(self, controls, t):
if self.is_nz_ok(controls, t):
self.decrease_nz_until_not_ok(controls, t, step=max(10, self.nz/5))
self.decrease_nz_until_not_ok(controls, t, step=max(10, self.nz/10))
self.decrease_nz_until_not_ok(controls, t, step=2)
self.increase_nz_until_ok(controls, t, step=2)
else:
self.increase_nz_until_ok(controls, t, step=max(10, self.nz/5))
self.decrease_nz_until_not_ok(controls, t, step=2)
self.increase_nz_until_ok(controls, t, step=2)
def increase_nz_until_ok(self, controls, t, step=2):
while self.is_nz_ok(controls, t) is False:
self.nz += h.make_even(step)
def decrease_nz_until_not_ok(self, controls, t, step=2):
while self.is_nz_ok(controls, t) and self.nz-step > 3:
self.nz -= h.make_even(step)
class ParametricSystemWithFunctions(ParametricSystemBase):
"""
A system with parametric hf and dhf, which are passed as callables to the constructor.
hf has to have the form hf(a,parameters)
"""
def __init__(self, hf, dhf, nz, omega, parameters):
"""
hf: callable hf(controls,parameters,omega)
dhf: callable dhf(controls,parameters,omega)
omega: 2 pi/T, the period of the Hamiltonian
nz: number of Fourier modes to be considered during evolution
parameters: a data structure that holds parameters for hf and dhf
(dictionary is probably the best idea)
"""
self.hf = hf
self.dhf = dhf
self.omega = omega
self.nz = nz
self.parameters = parameters
def calculate_hf(self, controls):
return self.hf(controls, self.parameters, self.omega)
def calculate_dhf(self, controls):
return self.dhf(controls, self.parameters, self.omega)
def get_system(self, controls, t):
hf = self.calculate_hf(controls)
dhf = self.calculate_dhf(controls)
return fs.FixedSystem(hf, dhf, self.nz, self.omega, t) | """
def get_system(self, controls, t):
raise NotImplementedError("get_system not implemented.") | random_line_split |
parametric_system.py | import floq.core.fixed_system as fs
import floq.evolution as ev
import floq.errors as er
import floq.helpers.index as h
class ParametricSystemBase(object):
"""
Base class to specify a physical system that still has open parameters,
such as the control amplitudes, the control duration, or other arbitrary
parameters in the Hamiltonian.
This needs to be sub-classed, and a subclass should provide:
- get_system(controls)
"""
def get_system(self, controls, t):
raise NotImplementedError("get_system not implemented.")
def is_nz_ok(self, controls, t):
system = self.get_system(controls, t)
try:
u = ev.evolve_system(system)
except er.EigenvalueNumberError:
return False
return h.is_unitary(u)
def set_nz(self, controls, t):
if self.is_nz_ok(controls, t):
self.decrease_nz_until_not_ok(controls, t, step=max(10, self.nz/5))
self.decrease_nz_until_not_ok(controls, t, step=max(10, self.nz/10))
self.decrease_nz_until_not_ok(controls, t, step=2)
self.increase_nz_until_ok(controls, t, step=2)
else:
|
def increase_nz_until_ok(self, controls, t, step=2):
while self.is_nz_ok(controls, t) is False:
self.nz += h.make_even(step)
def decrease_nz_until_not_ok(self, controls, t, step=2):
while self.is_nz_ok(controls, t) and self.nz-step > 3:
self.nz -= h.make_even(step)
class ParametricSystemWithFunctions(ParametricSystemBase):
"""
A system with parametric hf and dhf, which are passed as callables to the constructor.
hf has to have the form hf(a,parameters)
"""
def __init__(self, hf, dhf, nz, omega, parameters):
"""
hf: callable hf(controls,parameters,omega)
dhf: callable dhf(controls,parameters,omega)
omega: 2 pi/T, the period of the Hamiltonian
nz: number of Fourier modes to be considered during evolution
parameters: a data structure that holds parameters for hf and dhf
(dictionary is probably the best idea)
"""
self.hf = hf
self.dhf = dhf
self.omega = omega
self.nz = nz
self.parameters = parameters
def calculate_hf(self, controls):
return self.hf(controls, self.parameters, self.omega)
def calculate_dhf(self, controls):
return self.dhf(controls, self.parameters, self.omega)
def get_system(self, controls, t):
hf = self.calculate_hf(controls)
dhf = self.calculate_dhf(controls)
return fs.FixedSystem(hf, dhf, self.nz, self.omega, t)
| self.increase_nz_until_ok(controls, t, step=max(10, self.nz/5))
self.decrease_nz_until_not_ok(controls, t, step=2)
self.increase_nz_until_ok(controls, t, step=2) | conditional_block |
parametric_system.py | import floq.core.fixed_system as fs
import floq.evolution as ev
import floq.errors as er
import floq.helpers.index as h
class ParametricSystemBase(object):
"""
Base class to specify a physical system that still has open parameters,
such as the control amplitudes, the control duration, or other arbitrary
parameters in the Hamiltonian.
This needs to be sub-classed, and a subclass should provide:
- get_system(controls)
"""
def get_system(self, controls, t):
raise NotImplementedError("get_system not implemented.")
def | (self, controls, t):
system = self.get_system(controls, t)
try:
u = ev.evolve_system(system)
except er.EigenvalueNumberError:
return False
return h.is_unitary(u)
def set_nz(self, controls, t):
if self.is_nz_ok(controls, t):
self.decrease_nz_until_not_ok(controls, t, step=max(10, self.nz/5))
self.decrease_nz_until_not_ok(controls, t, step=max(10, self.nz/10))
self.decrease_nz_until_not_ok(controls, t, step=2)
self.increase_nz_until_ok(controls, t, step=2)
else:
self.increase_nz_until_ok(controls, t, step=max(10, self.nz/5))
self.decrease_nz_until_not_ok(controls, t, step=2)
self.increase_nz_until_ok(controls, t, step=2)
def increase_nz_until_ok(self, controls, t, step=2):
while self.is_nz_ok(controls, t) is False:
self.nz += h.make_even(step)
def decrease_nz_until_not_ok(self, controls, t, step=2):
while self.is_nz_ok(controls, t) and self.nz-step > 3:
self.nz -= h.make_even(step)
class ParametricSystemWithFunctions(ParametricSystemBase):
"""
A system with parametric hf and dhf, which are passed as callables to the constructor.
hf has to have the form hf(a,parameters)
"""
def __init__(self, hf, dhf, nz, omega, parameters):
"""
hf: callable hf(controls,parameters,omega)
dhf: callable dhf(controls,parameters,omega)
omega: 2 pi/T, the period of the Hamiltonian
nz: number of Fourier modes to be considered during evolution
parameters: a data structure that holds parameters for hf and dhf
(dictionary is probably the best idea)
"""
self.hf = hf
self.dhf = dhf
self.omega = omega
self.nz = nz
self.parameters = parameters
def calculate_hf(self, controls):
return self.hf(controls, self.parameters, self.omega)
def calculate_dhf(self, controls):
return self.dhf(controls, self.parameters, self.omega)
def get_system(self, controls, t):
hf = self.calculate_hf(controls)
dhf = self.calculate_dhf(controls)
return fs.FixedSystem(hf, dhf, self.nz, self.omega, t)
| is_nz_ok | identifier_name |
_Dialign.py | # Copyright 2009 by Cymon J. Cox. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Command line wrapper for the multiple alignment program DIALIGN2-2.
"""
from __future__ import print_function
__docformat__ = "restructuredtext en" # Don't just use plain text in epydoc API pages!
from Bio.Application import _Option, _Argument, _Switch, AbstractCommandline
class DialignCommandline(AbstractCommandline):
"""Command line wrapper for the multiple alignment program DIALIGN2-2.
http://bibiserv.techfak.uni-bielefeld.de/dialign/welcome.html
Example:
--------
To align a FASTA file (unaligned.fasta) with the output files names
aligned.* including a FASTA output file (aligned.fa), use:
>>> from Bio.Align.Applications import DialignCommandline
>>> dialign_cline = DialignCommandline(input="unaligned.fasta",
... fn="aligned", fa=True)
>>> print(dialign_cline)
dialign2-2 -fa -fn aligned unaligned.fasta
You would typically run the command line with dialign_cline() or via
the Python subprocess module, as described in the Biopython tutorial.
Citation:
---------
B. Morgenstern (2004). DIALIGN: Multiple DNA and Protein Sequence
Alignment at BiBiServ. Nucleic Acids Research 32, W33-W36.
Last checked against version: 2.2
"""
def __init__(self, cmd="dialign2-2", **kwargs):
self.program_name = cmd
self.parameters = \
[
_Switch(["-afc", "afc"],
"Creates additional output file '*.afc' "
"containing data of all fragments considered "
"for alignment WARNING: this file can be HUGE !"),
_Switch(["-afc_v", "afc_v"],
"Like '-afc' but verbose: fragments are explicitly "
"printed. WARNING: this file can be EVEN BIGGER !"),
_Switch(["-anc", "anc"],
"Anchored alignment. Requires a file <seq_file>.anc "
"containing anchor points."),
_Switch(["-cs", "cs"],
"If segments are translated, not only the `Watson "
"strand' but also the `Crick strand' is looked at."),
_Switch(["-cw", "cw"],
"Additional output file in CLUSTAL W format."),
_Switch(["-ds", "ds"],
"`dna alignment speed up' - non-translated nucleic acid "
"fragments are taken into account only if they start "
"with at least two matches. Speeds up DNA alignment at "
"the expense of sensitivity."),
_Switch(["-fa", "fa"],
"Additional output file in FASTA format."),
_Switch(["-ff", "ff"],
"Creates file *.frg containing information about all "
"fragments that are part of the respective optimal "
"pairwise alignmnets plus information about "
"consistency in the multiple alignment"),
_Option(["-fn", "fn"],
"Output files are named <out_file>.<extension>.",
equate=False),
_Switch(["-fop", "fop"],
"Creates file *.fop containing coordinates of all "
"fragments that are part of the respective pairwise alignments."),
_Switch(["-fsm", "fsm"],
"Creates file *.fsm containing coordinates of all "
"fragments that are part of the final alignment"),
_Switch(["-iw", "iw"],
"Overlap weights switched off (by default, overlap "
"weights are used if up to 35 sequences are aligned). "
"This option speeds up the alignment but may lead "
"to reduced alignment quality."),
_Switch(["-lgs", "lgs"],
"`long genomic sequences' - combines the following "
"options: -ma, -thr 2, -lmax 30, -smin 8, -nta, -ff, "
"-fop, -ff, -cs, -ds, -pst "),
_Switch(["-lgs_t", "lgs_t"],
"Like '-lgs' but with all segment pairs assessed "
"at the peptide level (rather than 'mixed alignments' "
"as with the '-lgs' option). Therefore faster than "
"-lgs but not very sensitive for non-coding regions."),
_Option(["-lmax", "lmax"],
"Maximum fragment length = x (default: x = 40 or "
"x = 120 for `translated' fragments). Shorter x "
"speeds up the program but may affect alignment quality.",
checker_function=lambda x: isinstance(x, int),
equate=False),
_Switch(["-lo", "lo"],
"(Long Output) Additional file *.log with information "
"about fragments selected for pairwise alignment and "
"about consistency in multi-alignment proceedure."),
_Switch(["-ma", "ma"],
"`mixed alignments' consisting of P-fragments and "
"N-fragments if nucleic acid sequences are aligned."),
_Switch(["-mask", "mask"],
"Residues not belonging to selected fragments are "
"replaced by `*' characters in output alignment "
"(rather than being printed in lower-case characters)"),
_Switch(["-mat", "mat"],
"Creates file *mat with substitution counts derived "
"from the fragments that have been selected for alignment."),
_Switch(["-mat_thr", "mat_thr"],
"Like '-mat' but only fragments with weight score "
"> t are considered"),
_Switch(["-max_link", "max_link"],
"'maximum linkage' clustering used to construct "
"sequence tree (instead of UPGMA)."),
_Switch(["-min_link", "min_link"],
"'minimum linkage' clustering used."),
_Option(["-mot", "mot"],
"'motif' option.",
equate=False),
_Switch(["-msf", "msf"],
"Separate output file in MSF format."),
_Switch(["-n", "n"],
"Input sequences are nucleic acid sequences. "
"No translation of fragments."),
_Switch(["-nt", "nt"],
"Input sequences are nucleic acid sequences and "
"`nucleic acid segments' are translated to `peptide "
"segments'."),
_Switch(["-nta", "nta"],
"`no textual alignment' - textual alignment suppressed. "
"This option makes sense if other output files are of "
"intrest -- e.g. the fragment files created with -ff, "
"-fop, -fsm or -lo."),
_Switch(["-o", "o"],
"Fast version, resulting alignments may be slightly "
"different."),
_Switch(["-ow", "ow"],
"Overlap weights enforced (By default, overlap weights "
"are used only if up to 35 sequences are aligned since "
"calculating overlap weights is time consuming)."),
_Switch(["-pst", "pst"],
"'print status'. Creates and updates a file *.sta with "
"information about the current status of the program "
"run. This option is recommended if large data sets "
"are aligned since it allows the user to estimate the "
"remaining running time."),
_Switch(["-smin", "smin"],
"Minimum similarity value for first residue pair "
"(or codon pair) in fragments. Speeds up protein "
"alignment or alignment of translated DNA fragments "
"at the expense of sensitivity."),
_Option(["-stars", "stars"],
"Maximum number of `*' characters indicating degree "
"of local similarity among sequences. By default, no "
"stars are used but numbers between 0 and 9, instead.",
checker_function = lambda x: x in range(0, 10),
equate=False),
_Switch(["-stdo", "stdo"],
"Results written to standard output."),
_Switch(["-ta", "ta"],
"Standard textual alignment printed (overrides "
"suppression of textual alignments in special "
"options, e.g. -lgs)"),
_Option(["-thr", "thr"],
"Threshold T = x.",
checker_function = lambda x: isinstance(x, int),
equate=False),
_Switch(["-xfr", "xfr"],
"'exclude fragments' - list of fragments can be "
"specified that are NOT considered for pairwise alignment"),
_Argument(["input"],
"Input file name. Must be FASTA format",
filename=True,
is_required=True),
]
AbstractCommandline.__init__(self, cmd, **kwargs)
def _test():
|
if __name__ == "__main__":
_test()
| """Run the module's doctests (PRIVATE)."""
print("Running modules doctests...")
import doctest
doctest.testmod()
print("Done") | identifier_body |
_Dialign.py | # Copyright 2009 by Cymon J. Cox. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Command line wrapper for the multiple alignment program DIALIGN2-2.
"""
from __future__ import print_function
__docformat__ = "restructuredtext en" # Don't just use plain text in epydoc API pages!
from Bio.Application import _Option, _Argument, _Switch, AbstractCommandline
class DialignCommandline(AbstractCommandline):
"""Command line wrapper for the multiple alignment program DIALIGN2-2.
http://bibiserv.techfak.uni-bielefeld.de/dialign/welcome.html
Example:
--------
To align a FASTA file (unaligned.fasta) with the output files names
aligned.* including a FASTA output file (aligned.fa), use:
>>> from Bio.Align.Applications import DialignCommandline
>>> dialign_cline = DialignCommandline(input="unaligned.fasta",
... fn="aligned", fa=True)
>>> print(dialign_cline)
dialign2-2 -fa -fn aligned unaligned.fasta
You would typically run the command line with dialign_cline() or via
the Python subprocess module, as described in the Biopython tutorial.
Citation:
---------
B. Morgenstern (2004). DIALIGN: Multiple DNA and Protein Sequence
Alignment at BiBiServ. Nucleic Acids Research 32, W33-W36.
Last checked against version: 2.2
"""
def __init__(self, cmd="dialign2-2", **kwargs):
self.program_name = cmd
self.parameters = \
[
_Switch(["-afc", "afc"],
"Creates additional output file '*.afc' "
"containing data of all fragments considered "
"for alignment WARNING: this file can be HUGE !"),
_Switch(["-afc_v", "afc_v"],
"Like '-afc' but verbose: fragments are explicitly "
"printed. WARNING: this file can be EVEN BIGGER !"),
_Switch(["-anc", "anc"],
"Anchored alignment. Requires a file <seq_file>.anc "
"containing anchor points."),
_Switch(["-cs", "cs"],
"If segments are translated, not only the `Watson "
"strand' but also the `Crick strand' is looked at."),
_Switch(["-cw", "cw"],
"Additional output file in CLUSTAL W format."),
_Switch(["-ds", "ds"],
"`dna alignment speed up' - non-translated nucleic acid "
"fragments are taken into account only if they start "
"with at least two matches. Speeds up DNA alignment at "
"the expense of sensitivity."),
_Switch(["-fa", "fa"],
"Additional output file in FASTA format."),
_Switch(["-ff", "ff"],
"Creates file *.frg containing information about all "
"fragments that are part of the respective optimal "
"pairwise alignmnets plus information about "
"consistency in the multiple alignment"),
_Option(["-fn", "fn"],
"Output files are named <out_file>.<extension>.",
equate=False),
_Switch(["-fop", "fop"],
"Creates file *.fop containing coordinates of all "
"fragments that are part of the respective pairwise alignments."),
_Switch(["-fsm", "fsm"],
"Creates file *.fsm containing coordinates of all "
"fragments that are part of the final alignment"),
_Switch(["-iw", "iw"],
"Overlap weights switched off (by default, overlap "
"weights are used if up to 35 sequences are aligned). "
"This option speeds up the alignment but may lead "
"to reduced alignment quality."),
_Switch(["-lgs", "lgs"],
"`long genomic sequences' - combines the following "
"options: -ma, -thr 2, -lmax 30, -smin 8, -nta, -ff, "
"-fop, -ff, -cs, -ds, -pst "),
_Switch(["-lgs_t", "lgs_t"],
"Like '-lgs' but with all segment pairs assessed "
"at the peptide level (rather than 'mixed alignments' "
"as with the '-lgs' option). Therefore faster than "
"-lgs but not very sensitive for non-coding regions."),
_Option(["-lmax", "lmax"],
"Maximum fragment length = x (default: x = 40 or "
"x = 120 for `translated' fragments). Shorter x "
"speeds up the program but may affect alignment quality.",
checker_function=lambda x: isinstance(x, int),
equate=False),
_Switch(["-lo", "lo"],
"(Long Output) Additional file *.log with information "
"about fragments selected for pairwise alignment and "
"about consistency in multi-alignment proceedure."),
_Switch(["-ma", "ma"],
"`mixed alignments' consisting of P-fragments and "
"N-fragments if nucleic acid sequences are aligned."),
_Switch(["-mask", "mask"],
"Residues not belonging to selected fragments are "
"replaced by `*' characters in output alignment "
"(rather than being printed in lower-case characters)"),
_Switch(["-mat", "mat"],
"Creates file *mat with substitution counts derived "
"from the fragments that have been selected for alignment."),
_Switch(["-mat_thr", "mat_thr"],
"Like '-mat' but only fragments with weight score "
"> t are considered"),
_Switch(["-max_link", "max_link"],
"'maximum linkage' clustering used to construct "
"sequence tree (instead of UPGMA)."),
_Switch(["-min_link", "min_link"],
"'minimum linkage' clustering used."),
_Option(["-mot", "mot"],
"'motif' option.",
equate=False),
_Switch(["-msf", "msf"],
"Separate output file in MSF format."),
_Switch(["-n", "n"],
"Input sequences are nucleic acid sequences. "
"No translation of fragments."),
_Switch(["-nt", "nt"],
"Input sequences are nucleic acid sequences and "
"`nucleic acid segments' are translated to `peptide "
"segments'."),
_Switch(["-nta", "nta"],
"`no textual alignment' - textual alignment suppressed. "
"This option makes sense if other output files are of "
"intrest -- e.g. the fragment files created with -ff, "
"-fop, -fsm or -lo."),
_Switch(["-o", "o"],
"Fast version, resulting alignments may be slightly "
"different."),
_Switch(["-ow", "ow"],
"Overlap weights enforced (By default, overlap weights "
"are used only if up to 35 sequences are aligned since "
"calculating overlap weights is time consuming)."),
_Switch(["-pst", "pst"],
"'print status'. Creates and updates a file *.sta with "
"information about the current status of the program "
"run. This option is recommended if large data sets "
"are aligned since it allows the user to estimate the "
"remaining running time."),
_Switch(["-smin", "smin"],
"Minimum similarity value for first residue pair "
"(or codon pair) in fragments. Speeds up protein "
"alignment or alignment of translated DNA fragments "
"at the expense of sensitivity."),
_Option(["-stars", "stars"],
"Maximum number of `*' characters indicating degree "
"of local similarity among sequences. By default, no "
"stars are used but numbers between 0 and 9, instead.",
checker_function = lambda x: x in range(0, 10),
equate=False),
_Switch(["-stdo", "stdo"],
"Results written to standard output."),
_Switch(["-ta", "ta"],
"Standard textual alignment printed (overrides "
"suppression of textual alignments in special "
"options, e.g. -lgs)"),
_Option(["-thr", "thr"],
"Threshold T = x.",
checker_function = lambda x: isinstance(x, int),
equate=False),
_Switch(["-xfr", "xfr"],
"'exclude fragments' - list of fragments can be "
"specified that are NOT considered for pairwise alignment"),
_Argument(["input"],
"Input file name. Must be FASTA format",
filename=True,
is_required=True),
]
AbstractCommandline.__init__(self, cmd, **kwargs)
def _test():
"""Run the module's doctests (PRIVATE)."""
print("Running modules doctests...")
import doctest
doctest.testmod()
print("Done")
if __name__ == "__main__":
| _test() | conditional_block | |
_Dialign.py | # Copyright 2009 by Cymon J. Cox. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Command line wrapper for the multiple alignment program DIALIGN2-2.
"""
from __future__ import print_function
__docformat__ = "restructuredtext en" # Don't just use plain text in epydoc API pages!
from Bio.Application import _Option, _Argument, _Switch, AbstractCommandline
class | (AbstractCommandline):
"""Command line wrapper for the multiple alignment program DIALIGN2-2.
http://bibiserv.techfak.uni-bielefeld.de/dialign/welcome.html
Example:
--------
To align a FASTA file (unaligned.fasta) with the output files names
aligned.* including a FASTA output file (aligned.fa), use:
>>> from Bio.Align.Applications import DialignCommandline
>>> dialign_cline = DialignCommandline(input="unaligned.fasta",
... fn="aligned", fa=True)
>>> print(dialign_cline)
dialign2-2 -fa -fn aligned unaligned.fasta
You would typically run the command line with dialign_cline() or via
the Python subprocess module, as described in the Biopython tutorial.
Citation:
---------
B. Morgenstern (2004). DIALIGN: Multiple DNA and Protein Sequence
Alignment at BiBiServ. Nucleic Acids Research 32, W33-W36.
Last checked against version: 2.2
"""
def __init__(self, cmd="dialign2-2", **kwargs):
self.program_name = cmd
self.parameters = \
[
_Switch(["-afc", "afc"],
"Creates additional output file '*.afc' "
"containing data of all fragments considered "
"for alignment WARNING: this file can be HUGE !"),
_Switch(["-afc_v", "afc_v"],
"Like '-afc' but verbose: fragments are explicitly "
"printed. WARNING: this file can be EVEN BIGGER !"),
_Switch(["-anc", "anc"],
"Anchored alignment. Requires a file <seq_file>.anc "
"containing anchor points."),
_Switch(["-cs", "cs"],
"If segments are translated, not only the `Watson "
"strand' but also the `Crick strand' is looked at."),
_Switch(["-cw", "cw"],
"Additional output file in CLUSTAL W format."),
_Switch(["-ds", "ds"],
"`dna alignment speed up' - non-translated nucleic acid "
"fragments are taken into account only if they start "
"with at least two matches. Speeds up DNA alignment at "
"the expense of sensitivity."),
_Switch(["-fa", "fa"],
"Additional output file in FASTA format."),
_Switch(["-ff", "ff"],
"Creates file *.frg containing information about all "
"fragments that are part of the respective optimal "
"pairwise alignmnets plus information about "
"consistency in the multiple alignment"),
_Option(["-fn", "fn"],
"Output files are named <out_file>.<extension>.",
equate=False),
_Switch(["-fop", "fop"],
"Creates file *.fop containing coordinates of all "
"fragments that are part of the respective pairwise alignments."),
_Switch(["-fsm", "fsm"],
"Creates file *.fsm containing coordinates of all "
"fragments that are part of the final alignment"),
_Switch(["-iw", "iw"],
"Overlap weights switched off (by default, overlap "
"weights are used if up to 35 sequences are aligned). "
"This option speeds up the alignment but may lead "
"to reduced alignment quality."),
_Switch(["-lgs", "lgs"],
"`long genomic sequences' - combines the following "
"options: -ma, -thr 2, -lmax 30, -smin 8, -nta, -ff, "
"-fop, -ff, -cs, -ds, -pst "),
_Switch(["-lgs_t", "lgs_t"],
"Like '-lgs' but with all segment pairs assessed "
"at the peptide level (rather than 'mixed alignments' "
"as with the '-lgs' option). Therefore faster than "
"-lgs but not very sensitive for non-coding regions."),
_Option(["-lmax", "lmax"],
"Maximum fragment length = x (default: x = 40 or "
"x = 120 for `translated' fragments). Shorter x "
"speeds up the program but may affect alignment quality.",
checker_function=lambda x: isinstance(x, int),
equate=False),
_Switch(["-lo", "lo"],
"(Long Output) Additional file *.log with information "
"about fragments selected for pairwise alignment and "
"about consistency in multi-alignment proceedure."),
_Switch(["-ma", "ma"],
"`mixed alignments' consisting of P-fragments and "
"N-fragments if nucleic acid sequences are aligned."),
_Switch(["-mask", "mask"],
"Residues not belonging to selected fragments are "
"replaced by `*' characters in output alignment "
"(rather than being printed in lower-case characters)"),
_Switch(["-mat", "mat"],
"Creates file *mat with substitution counts derived "
"from the fragments that have been selected for alignment."),
_Switch(["-mat_thr", "mat_thr"],
"Like '-mat' but only fragments with weight score "
"> t are considered"),
_Switch(["-max_link", "max_link"],
"'maximum linkage' clustering used to construct "
"sequence tree (instead of UPGMA)."),
_Switch(["-min_link", "min_link"],
"'minimum linkage' clustering used."),
_Option(["-mot", "mot"],
"'motif' option.",
equate=False),
_Switch(["-msf", "msf"],
"Separate output file in MSF format."),
_Switch(["-n", "n"],
"Input sequences are nucleic acid sequences. "
"No translation of fragments."),
_Switch(["-nt", "nt"],
"Input sequences are nucleic acid sequences and "
"`nucleic acid segments' are translated to `peptide "
"segments'."),
_Switch(["-nta", "nta"],
"`no textual alignment' - textual alignment suppressed. "
"This option makes sense if other output files are of "
"intrest -- e.g. the fragment files created with -ff, "
"-fop, -fsm or -lo."),
_Switch(["-o", "o"],
"Fast version, resulting alignments may be slightly "
"different."),
_Switch(["-ow", "ow"],
"Overlap weights enforced (By default, overlap weights "
"are used only if up to 35 sequences are aligned since "
"calculating overlap weights is time consuming)."),
_Switch(["-pst", "pst"],
"'print status'. Creates and updates a file *.sta with "
"information about the current status of the program "
"run. This option is recommended if large data sets "
"are aligned since it allows the user to estimate the "
"remaining running time."),
_Switch(["-smin", "smin"],
"Minimum similarity value for first residue pair "
"(or codon pair) in fragments. Speeds up protein "
"alignment or alignment of translated DNA fragments "
"at the expense of sensitivity."),
_Option(["-stars", "stars"],
"Maximum number of `*' characters indicating degree "
"of local similarity among sequences. By default, no "
"stars are used but numbers between 0 and 9, instead.",
checker_function = lambda x: x in range(0, 10),
equate=False),
_Switch(["-stdo", "stdo"],
"Results written to standard output."),
_Switch(["-ta", "ta"],
"Standard textual alignment printed (overrides "
"suppression of textual alignments in special "
"options, e.g. -lgs)"),
_Option(["-thr", "thr"],
"Threshold T = x.",
checker_function = lambda x: isinstance(x, int),
equate=False),
_Switch(["-xfr", "xfr"],
"'exclude fragments' - list of fragments can be "
"specified that are NOT considered for pairwise alignment"),
_Argument(["input"],
"Input file name. Must be FASTA format",
filename=True,
is_required=True),
]
AbstractCommandline.__init__(self, cmd, **kwargs)
def _test():
"""Run the module's doctests (PRIVATE)."""
print("Running modules doctests...")
import doctest
doctest.testmod()
print("Done")
if __name__ == "__main__":
_test()
| DialignCommandline | identifier_name |
_Dialign.py | # Copyright 2009 by Cymon J. Cox. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Command line wrapper for the multiple alignment program DIALIGN2-2.
"""
from __future__ import print_function
__docformat__ = "restructuredtext en" # Don't just use plain text in epydoc API pages!
from Bio.Application import _Option, _Argument, _Switch, AbstractCommandline
class DialignCommandline(AbstractCommandline):
"""Command line wrapper for the multiple alignment program DIALIGN2-2.
http://bibiserv.techfak.uni-bielefeld.de/dialign/welcome.html
Example:
--------
To align a FASTA file (unaligned.fasta) with the output files names
aligned.* including a FASTA output file (aligned.fa), use:
>>> from Bio.Align.Applications import DialignCommandline
>>> dialign_cline = DialignCommandline(input="unaligned.fasta",
... fn="aligned", fa=True)
>>> print(dialign_cline)
dialign2-2 -fa -fn aligned unaligned.fasta
You would typically run the command line with dialign_cline() or via | the Python subprocess module, as described in the Biopython tutorial.
Citation:
---------
B. Morgenstern (2004). DIALIGN: Multiple DNA and Protein Sequence
Alignment at BiBiServ. Nucleic Acids Research 32, W33-W36.
Last checked against version: 2.2
"""
def __init__(self, cmd="dialign2-2", **kwargs):
self.program_name = cmd
self.parameters = \
[
_Switch(["-afc", "afc"],
"Creates additional output file '*.afc' "
"containing data of all fragments considered "
"for alignment WARNING: this file can be HUGE !"),
_Switch(["-afc_v", "afc_v"],
"Like '-afc' but verbose: fragments are explicitly "
"printed. WARNING: this file can be EVEN BIGGER !"),
_Switch(["-anc", "anc"],
"Anchored alignment. Requires a file <seq_file>.anc "
"containing anchor points."),
_Switch(["-cs", "cs"],
"If segments are translated, not only the `Watson "
"strand' but also the `Crick strand' is looked at."),
_Switch(["-cw", "cw"],
"Additional output file in CLUSTAL W format."),
_Switch(["-ds", "ds"],
"`dna alignment speed up' - non-translated nucleic acid "
"fragments are taken into account only if they start "
"with at least two matches. Speeds up DNA alignment at "
"the expense of sensitivity."),
_Switch(["-fa", "fa"],
"Additional output file in FASTA format."),
_Switch(["-ff", "ff"],
"Creates file *.frg containing information about all "
"fragments that are part of the respective optimal "
"pairwise alignmnets plus information about "
"consistency in the multiple alignment"),
_Option(["-fn", "fn"],
"Output files are named <out_file>.<extension>.",
equate=False),
_Switch(["-fop", "fop"],
"Creates file *.fop containing coordinates of all "
"fragments that are part of the respective pairwise alignments."),
_Switch(["-fsm", "fsm"],
"Creates file *.fsm containing coordinates of all "
"fragments that are part of the final alignment"),
_Switch(["-iw", "iw"],
"Overlap weights switched off (by default, overlap "
"weights are used if up to 35 sequences are aligned). "
"This option speeds up the alignment but may lead "
"to reduced alignment quality."),
_Switch(["-lgs", "lgs"],
"`long genomic sequences' - combines the following "
"options: -ma, -thr 2, -lmax 30, -smin 8, -nta, -ff, "
"-fop, -ff, -cs, -ds, -pst "),
_Switch(["-lgs_t", "lgs_t"],
"Like '-lgs' but with all segment pairs assessed "
"at the peptide level (rather than 'mixed alignments' "
"as with the '-lgs' option). Therefore faster than "
"-lgs but not very sensitive for non-coding regions."),
_Option(["-lmax", "lmax"],
"Maximum fragment length = x (default: x = 40 or "
"x = 120 for `translated' fragments). Shorter x "
"speeds up the program but may affect alignment quality.",
checker_function=lambda x: isinstance(x, int),
equate=False),
_Switch(["-lo", "lo"],
"(Long Output) Additional file *.log with information "
"about fragments selected for pairwise alignment and "
"about consistency in multi-alignment proceedure."),
_Switch(["-ma", "ma"],
"`mixed alignments' consisting of P-fragments and "
"N-fragments if nucleic acid sequences are aligned."),
_Switch(["-mask", "mask"],
"Residues not belonging to selected fragments are "
"replaced by `*' characters in output alignment "
"(rather than being printed in lower-case characters)"),
_Switch(["-mat", "mat"],
"Creates file *mat with substitution counts derived "
"from the fragments that have been selected for alignment."),
_Switch(["-mat_thr", "mat_thr"],
"Like '-mat' but only fragments with weight score "
"> t are considered"),
_Switch(["-max_link", "max_link"],
"'maximum linkage' clustering used to construct "
"sequence tree (instead of UPGMA)."),
_Switch(["-min_link", "min_link"],
"'minimum linkage' clustering used."),
_Option(["-mot", "mot"],
"'motif' option.",
equate=False),
_Switch(["-msf", "msf"],
"Separate output file in MSF format."),
_Switch(["-n", "n"],
"Input sequences are nucleic acid sequences. "
"No translation of fragments."),
_Switch(["-nt", "nt"],
"Input sequences are nucleic acid sequences and "
"`nucleic acid segments' are translated to `peptide "
"segments'."),
_Switch(["-nta", "nta"],
"`no textual alignment' - textual alignment suppressed. "
"This option makes sense if other output files are of "
"intrest -- e.g. the fragment files created with -ff, "
"-fop, -fsm or -lo."),
_Switch(["-o", "o"],
"Fast version, resulting alignments may be slightly "
"different."),
_Switch(["-ow", "ow"],
"Overlap weights enforced (By default, overlap weights "
"are used only if up to 35 sequences are aligned since "
"calculating overlap weights is time consuming)."),
_Switch(["-pst", "pst"],
"'print status'. Creates and updates a file *.sta with "
"information about the current status of the program "
"run. This option is recommended if large data sets "
"are aligned since it allows the user to estimate the "
"remaining running time."),
_Switch(["-smin", "smin"],
"Minimum similarity value for first residue pair "
"(or codon pair) in fragments. Speeds up protein "
"alignment or alignment of translated DNA fragments "
"at the expense of sensitivity."),
_Option(["-stars", "stars"],
"Maximum number of `*' characters indicating degree "
"of local similarity among sequences. By default, no "
"stars are used but numbers between 0 and 9, instead.",
checker_function = lambda x: x in range(0, 10),
equate=False),
_Switch(["-stdo", "stdo"],
"Results written to standard output."),
_Switch(["-ta", "ta"],
"Standard textual alignment printed (overrides "
"suppression of textual alignments in special "
"options, e.g. -lgs)"),
_Option(["-thr", "thr"],
"Threshold T = x.",
checker_function = lambda x: isinstance(x, int),
equate=False),
_Switch(["-xfr", "xfr"],
"'exclude fragments' - list of fragments can be "
"specified that are NOT considered for pairwise alignment"),
_Argument(["input"],
"Input file name. Must be FASTA format",
filename=True,
is_required=True),
]
AbstractCommandline.__init__(self, cmd, **kwargs)
def _test():
"""Run the module's doctests (PRIVATE)."""
print("Running modules doctests...")
import doctest
doctest.testmod()
print("Done")
if __name__ == "__main__":
_test() | random_line_split | |
abi.rs | use std::{fmt::Debug, result::Result};
use wasm_bindgen::{
convert::FromWasmAbi,
describe::{inform, WasmDescribe},
JsValue,
};
pub type JsResult<T> = Result<T, JsValue>;
pub trait Context<T> {
fn context(self, msg: &dyn Debug) -> JsResult<T>;
}
impl<T, TError> Context<T> for Result<T, TError>
where
TError: Debug,
{
fn context(self, msg: &dyn Debug) -> JsResult<T> {
match self {
Ok(v) => Ok(v),
Err(err) => Err(format!("{:?} {:?}", msg, err).into()),
}
}
}
pub struct LogLevel(pub log::Level);
impl WasmDescribe for LogLevel {
fn describe() {
inform(wasm_bindgen::describe::I8);
}
}
impl FromWasmAbi for LogLevel {
type Abi = u32;
unsafe fn from_abi(js: Self::Abi) -> Self {
match js { | 2 => LogLevel(log::Level::Info),
3 => LogLevel(log::Level::Warn),
_ => LogLevel(log::Level::Error),
}
}
} | 0 => LogLevel(log::Level::Trace),
1 => LogLevel(log::Level::Debug), | random_line_split |
abi.rs | use std::{fmt::Debug, result::Result};
use wasm_bindgen::{
convert::FromWasmAbi,
describe::{inform, WasmDescribe},
JsValue,
};
pub type JsResult<T> = Result<T, JsValue>;
pub trait Context<T> {
fn context(self, msg: &dyn Debug) -> JsResult<T>;
}
impl<T, TError> Context<T> for Result<T, TError>
where
TError: Debug,
{
fn context(self, msg: &dyn Debug) -> JsResult<T> |
}
pub struct LogLevel(pub log::Level);
impl WasmDescribe for LogLevel {
fn describe() {
inform(wasm_bindgen::describe::I8);
}
}
impl FromWasmAbi for LogLevel {
type Abi = u32;
unsafe fn from_abi(js: Self::Abi) -> Self {
match js {
0 => LogLevel(log::Level::Trace),
1 => LogLevel(log::Level::Debug),
2 => LogLevel(log::Level::Info),
3 => LogLevel(log::Level::Warn),
_ => LogLevel(log::Level::Error),
}
}
}
| {
match self {
Ok(v) => Ok(v),
Err(err) => Err(format!("{:?} {:?}", msg, err).into()),
}
} | identifier_body |
abi.rs | use std::{fmt::Debug, result::Result};
use wasm_bindgen::{
convert::FromWasmAbi,
describe::{inform, WasmDescribe},
JsValue,
};
pub type JsResult<T> = Result<T, JsValue>;
pub trait Context<T> {
fn context(self, msg: &dyn Debug) -> JsResult<T>;
}
impl<T, TError> Context<T> for Result<T, TError>
where
TError: Debug,
{
fn | (self, msg: &dyn Debug) -> JsResult<T> {
match self {
Ok(v) => Ok(v),
Err(err) => Err(format!("{:?} {:?}", msg, err).into()),
}
}
}
pub struct LogLevel(pub log::Level);
impl WasmDescribe for LogLevel {
fn describe() {
inform(wasm_bindgen::describe::I8);
}
}
impl FromWasmAbi for LogLevel {
type Abi = u32;
unsafe fn from_abi(js: Self::Abi) -> Self {
match js {
0 => LogLevel(log::Level::Trace),
1 => LogLevel(log::Level::Debug),
2 => LogLevel(log::Level::Info),
3 => LogLevel(log::Level::Warn),
_ => LogLevel(log::Level::Error),
}
}
}
| context | identifier_name |
will-members.ts | // Source file from duniter: Crypto-currency software to manage libre currency such as Ğ1
// Copyright (C) 2018 Cedric Moreau <cem.moreau@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
import {assertEqual, assertTrue, writeBasicTestWithConfAnd2Users} from "duniter/test/integration/tools/test-framework"
import {CommonConstants} from "duniter/app/lib/common-libs/constants";
import {DataFinder, initMonitDB} from "../lib/DataFinder";
import {MonitDBBlock} from "../lib/SqliteBlockchain";
import {willMembers} from "../modules/will-members";
describe('willMembers', () => writeBasicTestWithConfAnd2Users({
sigQty: 1,
medianTimeBlocks: 1,
}, (test) => {
const now = 1500000000
before(() => {
CommonConstants.BLOCKS_IN_MEMORY_MAX = 3 // Must be > forkWindowSize
})
test('Duniter blockchain init', async (s1, cat, tac) => {
await cat.createIdentity()
await tac.createIdentity()
await cat.cert(tac) | await tac.cert(cat)
await cat.join()
await tac.join()
const head = await s1.commit({ time: now })
assertEqual(head.number, 0);
assertEqual(head.membersCount, 2);
await initMonitDB(s1._server)
})
test('toc tries to join', async (s1, cat, tac, toc) => {
await toc.createIdentity()
await toc.join()
await cat.cert(toc)
await tac.cert(toc)
const will = await willMembers(s1._server)
assertEqual(will.idtysListOrdered.length, 1)
assertEqual(will.idtysListOrdered[0].pendingCertifications.length, 2) // cat & tac
})
})) | random_line_split | |
vis_utils_test.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for Keras Vis utils."""
from tensorflow.python import keras
from tensorflow.python.keras.utils import vis_utils
from tensorflow.python.lib.io import file_io
from tensorflow.python.ops import math_ops |
def test_plot_model_cnn(self):
model = keras.Sequential()
model.add(
keras.layers.Conv2D(
filters=2, kernel_size=(2, 3), input_shape=(3, 5, 5), name='conv'))
model.add(keras.layers.Flatten(name='flat'))
model.add(keras.layers.Dense(5, name='dense'))
dot_img_file = 'model_1.png'
try:
vis_utils.plot_model(
model, to_file=dot_img_file, show_shapes=True, show_dtype=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
def test_plot_model_with_wrapped_layers_and_models(self):
inputs = keras.Input(shape=(None, 3))
lstm = keras.layers.LSTM(6, return_sequences=True, name='lstm')
x = lstm(inputs)
# Add layer inside a Wrapper
bilstm = keras.layers.Bidirectional(
keras.layers.LSTM(16, return_sequences=True, name='bilstm'))
x = bilstm(x)
# Add model inside a Wrapper
submodel = keras.Sequential(
[keras.layers.Dense(32, name='dense', input_shape=(None, 32))]
)
wrapped_dense = keras.layers.TimeDistributed(submodel)
x = wrapped_dense(x)
# Add shared submodel
outputs = submodel(x)
model = keras.Model(inputs, outputs)
dot_img_file = 'model_2.png'
try:
vis_utils.plot_model(
model,
to_file=dot_img_file,
show_shapes=True,
show_dtype=True,
expand_nested=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
def test_plot_model_with_add_loss(self):
inputs = keras.Input(shape=(None, 3))
outputs = keras.layers.Dense(1)(inputs)
model = keras.Model(inputs, outputs)
model.add_loss(math_ops.reduce_mean(outputs))
dot_img_file = 'model_3.png'
try:
vis_utils.plot_model(
model,
to_file=dot_img_file,
show_shapes=True,
show_dtype=True,
expand_nested=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
model = keras.Sequential([
keras.Input(shape=(None, 3)), keras.layers.Dense(1)])
model.add_loss(math_ops.reduce_mean(model.output))
dot_img_file = 'model_4.png'
try:
vis_utils.plot_model(
model,
to_file=dot_img_file,
show_shapes=True,
show_dtype=True,
expand_nested=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
if __name__ == '__main__':
test.main() | from tensorflow.python.platform import test
class ModelToDotFormatTest(test.TestCase): | random_line_split |
vis_utils_test.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for Keras Vis utils."""
from tensorflow.python import keras
from tensorflow.python.keras.utils import vis_utils
from tensorflow.python.lib.io import file_io
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test
class ModelToDotFormatTest(test.TestCase):
def test_plot_model_cnn(self):
model = keras.Sequential()
model.add(
keras.layers.Conv2D(
filters=2, kernel_size=(2, 3), input_shape=(3, 5, 5), name='conv'))
model.add(keras.layers.Flatten(name='flat'))
model.add(keras.layers.Dense(5, name='dense'))
dot_img_file = 'model_1.png'
try:
vis_utils.plot_model(
model, to_file=dot_img_file, show_shapes=True, show_dtype=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
def test_plot_model_with_wrapped_layers_and_models(self):
inputs = keras.Input(shape=(None, 3))
lstm = keras.layers.LSTM(6, return_sequences=True, name='lstm')
x = lstm(inputs)
# Add layer inside a Wrapper
bilstm = keras.layers.Bidirectional(
keras.layers.LSTM(16, return_sequences=True, name='bilstm'))
x = bilstm(x)
# Add model inside a Wrapper
submodel = keras.Sequential(
[keras.layers.Dense(32, name='dense', input_shape=(None, 32))]
)
wrapped_dense = keras.layers.TimeDistributed(submodel)
x = wrapped_dense(x)
# Add shared submodel
outputs = submodel(x)
model = keras.Model(inputs, outputs)
dot_img_file = 'model_2.png'
try:
vis_utils.plot_model(
model,
to_file=dot_img_file,
show_shapes=True,
show_dtype=True,
expand_nested=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
def test_plot_model_with_add_loss(self):
inputs = keras.Input(shape=(None, 3))
outputs = keras.layers.Dense(1)(inputs)
model = keras.Model(inputs, outputs)
model.add_loss(math_ops.reduce_mean(outputs))
dot_img_file = 'model_3.png'
try:
vis_utils.plot_model(
model,
to_file=dot_img_file,
show_shapes=True,
show_dtype=True,
expand_nested=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
model = keras.Sequential([
keras.Input(shape=(None, 3)), keras.layers.Dense(1)])
model.add_loss(math_ops.reduce_mean(model.output))
dot_img_file = 'model_4.png'
try:
vis_utils.plot_model(
model,
to_file=dot_img_file,
show_shapes=True,
show_dtype=True,
expand_nested=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
if __name__ == '__main__':
| test.main() | conditional_block | |
vis_utils_test.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for Keras Vis utils."""
from tensorflow.python import keras
from tensorflow.python.keras.utils import vis_utils
from tensorflow.python.lib.io import file_io
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test
class ModelToDotFormatTest(test.TestCase):
def test_plot_model_cnn(self):
|
def test_plot_model_with_wrapped_layers_and_models(self):
inputs = keras.Input(shape=(None, 3))
lstm = keras.layers.LSTM(6, return_sequences=True, name='lstm')
x = lstm(inputs)
# Add layer inside a Wrapper
bilstm = keras.layers.Bidirectional(
keras.layers.LSTM(16, return_sequences=True, name='bilstm'))
x = bilstm(x)
# Add model inside a Wrapper
submodel = keras.Sequential(
[keras.layers.Dense(32, name='dense', input_shape=(None, 32))]
)
wrapped_dense = keras.layers.TimeDistributed(submodel)
x = wrapped_dense(x)
# Add shared submodel
outputs = submodel(x)
model = keras.Model(inputs, outputs)
dot_img_file = 'model_2.png'
try:
vis_utils.plot_model(
model,
to_file=dot_img_file,
show_shapes=True,
show_dtype=True,
expand_nested=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
def test_plot_model_with_add_loss(self):
inputs = keras.Input(shape=(None, 3))
outputs = keras.layers.Dense(1)(inputs)
model = keras.Model(inputs, outputs)
model.add_loss(math_ops.reduce_mean(outputs))
dot_img_file = 'model_3.png'
try:
vis_utils.plot_model(
model,
to_file=dot_img_file,
show_shapes=True,
show_dtype=True,
expand_nested=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
model = keras.Sequential([
keras.Input(shape=(None, 3)), keras.layers.Dense(1)])
model.add_loss(math_ops.reduce_mean(model.output))
dot_img_file = 'model_4.png'
try:
vis_utils.plot_model(
model,
to_file=dot_img_file,
show_shapes=True,
show_dtype=True,
expand_nested=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
if __name__ == '__main__':
test.main()
| model = keras.Sequential()
model.add(
keras.layers.Conv2D(
filters=2, kernel_size=(2, 3), input_shape=(3, 5, 5), name='conv'))
model.add(keras.layers.Flatten(name='flat'))
model.add(keras.layers.Dense(5, name='dense'))
dot_img_file = 'model_1.png'
try:
vis_utils.plot_model(
model, to_file=dot_img_file, show_shapes=True, show_dtype=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass | identifier_body |
vis_utils_test.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for Keras Vis utils."""
from tensorflow.python import keras
from tensorflow.python.keras.utils import vis_utils
from tensorflow.python.lib.io import file_io
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test
class ModelToDotFormatTest(test.TestCase):
def test_plot_model_cnn(self):
model = keras.Sequential()
model.add(
keras.layers.Conv2D(
filters=2, kernel_size=(2, 3), input_shape=(3, 5, 5), name='conv'))
model.add(keras.layers.Flatten(name='flat'))
model.add(keras.layers.Dense(5, name='dense'))
dot_img_file = 'model_1.png'
try:
vis_utils.plot_model(
model, to_file=dot_img_file, show_shapes=True, show_dtype=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
def test_plot_model_with_wrapped_layers_and_models(self):
inputs = keras.Input(shape=(None, 3))
lstm = keras.layers.LSTM(6, return_sequences=True, name='lstm')
x = lstm(inputs)
# Add layer inside a Wrapper
bilstm = keras.layers.Bidirectional(
keras.layers.LSTM(16, return_sequences=True, name='bilstm'))
x = bilstm(x)
# Add model inside a Wrapper
submodel = keras.Sequential(
[keras.layers.Dense(32, name='dense', input_shape=(None, 32))]
)
wrapped_dense = keras.layers.TimeDistributed(submodel)
x = wrapped_dense(x)
# Add shared submodel
outputs = submodel(x)
model = keras.Model(inputs, outputs)
dot_img_file = 'model_2.png'
try:
vis_utils.plot_model(
model,
to_file=dot_img_file,
show_shapes=True,
show_dtype=True,
expand_nested=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
def | (self):
inputs = keras.Input(shape=(None, 3))
outputs = keras.layers.Dense(1)(inputs)
model = keras.Model(inputs, outputs)
model.add_loss(math_ops.reduce_mean(outputs))
dot_img_file = 'model_3.png'
try:
vis_utils.plot_model(
model,
to_file=dot_img_file,
show_shapes=True,
show_dtype=True,
expand_nested=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
model = keras.Sequential([
keras.Input(shape=(None, 3)), keras.layers.Dense(1)])
model.add_loss(math_ops.reduce_mean(model.output))
dot_img_file = 'model_4.png'
try:
vis_utils.plot_model(
model,
to_file=dot_img_file,
show_shapes=True,
show_dtype=True,
expand_nested=True)
self.assertTrue(file_io.file_exists_v2(dot_img_file))
file_io.delete_file_v2(dot_img_file)
except ImportError:
pass
if __name__ == '__main__':
test.main()
| test_plot_model_with_add_loss | identifier_name |
flowers_test.py | # Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import paddle.dataset.flowers
import unittest
class TestFlowers(unittest.TestCase): | self.assertEqual(l[0].size, size)
if l[1] > label:
label = l[1]
sum += 1
return sum, label
def test_train(self):
instances, max_label_value = self.check_reader(
paddle.dataset.flowers.train())
self.assertEqual(instances, 6149)
self.assertEqual(max_label_value, 102)
def test_test(self):
instances, max_label_value = self.check_reader(
paddle.dataset.flowers.test())
self.assertEqual(instances, 1020)
self.assertEqual(max_label_value, 102)
def test_valid(self):
instances, max_label_value = self.check_reader(
paddle.dataset.flowers.valid())
self.assertEqual(instances, 1020)
self.assertEqual(max_label_value, 102)
if __name__ == '__main__':
unittest.main() | def check_reader(self, reader):
sum = 0
label = 0
size = 224 * 224 * 3
for l in reader(): | random_line_split |
flowers_test.py | # Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import paddle.dataset.flowers
import unittest
class TestFlowers(unittest.TestCase):
def | (self, reader):
sum = 0
label = 0
size = 224 * 224 * 3
for l in reader():
self.assertEqual(l[0].size, size)
if l[1] > label:
label = l[1]
sum += 1
return sum, label
def test_train(self):
instances, max_label_value = self.check_reader(
paddle.dataset.flowers.train())
self.assertEqual(instances, 6149)
self.assertEqual(max_label_value, 102)
def test_test(self):
instances, max_label_value = self.check_reader(
paddle.dataset.flowers.test())
self.assertEqual(instances, 1020)
self.assertEqual(max_label_value, 102)
def test_valid(self):
instances, max_label_value = self.check_reader(
paddle.dataset.flowers.valid())
self.assertEqual(instances, 1020)
self.assertEqual(max_label_value, 102)
if __name__ == '__main__':
unittest.main()
| check_reader | identifier_name |
flowers_test.py | # Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import paddle.dataset.flowers
import unittest
class TestFlowers(unittest.TestCase):
def check_reader(self, reader):
sum = 0
label = 0
size = 224 * 224 * 3
for l in reader():
self.assertEqual(l[0].size, size)
if l[1] > label:
|
sum += 1
return sum, label
def test_train(self):
instances, max_label_value = self.check_reader(
paddle.dataset.flowers.train())
self.assertEqual(instances, 6149)
self.assertEqual(max_label_value, 102)
def test_test(self):
instances, max_label_value = self.check_reader(
paddle.dataset.flowers.test())
self.assertEqual(instances, 1020)
self.assertEqual(max_label_value, 102)
def test_valid(self):
instances, max_label_value = self.check_reader(
paddle.dataset.flowers.valid())
self.assertEqual(instances, 1020)
self.assertEqual(max_label_value, 102)
if __name__ == '__main__':
unittest.main()
| label = l[1] | conditional_block |
flowers_test.py | # Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import paddle.dataset.flowers
import unittest
class TestFlowers(unittest.TestCase):
def check_reader(self, reader):
sum = 0
label = 0
size = 224 * 224 * 3
for l in reader():
self.assertEqual(l[0].size, size)
if l[1] > label:
label = l[1]
sum += 1
return sum, label
def test_train(self):
instances, max_label_value = self.check_reader(
paddle.dataset.flowers.train())
self.assertEqual(instances, 6149)
self.assertEqual(max_label_value, 102)
def test_test(self):
instances, max_label_value = self.check_reader(
paddle.dataset.flowers.test())
self.assertEqual(instances, 1020)
self.assertEqual(max_label_value, 102)
def test_valid(self):
|
if __name__ == '__main__':
unittest.main()
| instances, max_label_value = self.check_reader(
paddle.dataset.flowers.valid())
self.assertEqual(instances, 1020)
self.assertEqual(max_label_value, 102) | identifier_body |
more.d.ts | import TelegramBotApiEvent from './events';
/**
* @class TelegramBotApi
*/
export default class | extends TelegramBotApiEvent {
/**
* Create a TelegramBotApi
* @param {string} token
* @param {Object} options
*/
constructor(token?: string, options?: {
gzip?: boolean;
autoChatAction?: boolean;
autoChatActionUploadOnly?: boolean;
autoUpdate?: boolean;
updateInterval?: number;
updateLimit?: number;
updatePoolingTimeout?: number;
});
/**
* Array of onMessage listeners
* @private
*/
private _onMsgListenerArray;
/**
* last _onMsgListenerArray item.id
* @private
*/
private _onMsgLastId;
/**
* Make loop on _onMsgListenerArray and if callBackFn return false break the loop
* @private
* @param {Function} callBackFn
*/
private _onMsgListenerLoop(callBackFn);
/**
* Check patterns and call listeners
* called when 'update.message.text' receive
* @private
* @param {any} msg
*/
private _onMsg(msg);
/**
* Make 'update.message.text' event on special regular expersion pattern
* @param {RegExp} pattern
* @param {Function} listener
* @return {number} event id
*/
onMessage(pattern: RegExp, listener: Function): number;
offMessage(id: number): boolean;
}
| TelegramBotApi | identifier_name |
more.d.ts | import TelegramBotApiEvent from './events';
/**
* @class TelegramBotApi
*/
export default class TelegramBotApi extends TelegramBotApiEvent {
/**
* Create a TelegramBotApi
* @param {string} token
* @param {Object} options
*/
constructor(token?: string, options?: {
gzip?: boolean;
autoChatAction?: boolean;
autoChatActionUploadOnly?: boolean;
autoUpdate?: boolean;
updateInterval?: number;
updateLimit?: number;
updatePoolingTimeout?: number; | });
/**
* Array of onMessage listeners
* @private
*/
private _onMsgListenerArray;
/**
* last _onMsgListenerArray item.id
* @private
*/
private _onMsgLastId;
/**
* Make loop on _onMsgListenerArray and if callBackFn return false break the loop
* @private
* @param {Function} callBackFn
*/
private _onMsgListenerLoop(callBackFn);
/**
* Check patterns and call listeners
* called when 'update.message.text' receive
* @private
* @param {any} msg
*/
private _onMsg(msg);
/**
* Make 'update.message.text' event on special regular expersion pattern
* @param {RegExp} pattern
* @param {Function} listener
* @return {number} event id
*/
onMessage(pattern: RegExp, listener: Function): number;
offMessage(id: number): boolean;
} | random_line_split | |
canteen_website_tags.py | # -*- coding: utf-8 -*-
from django import template
from CanteenWebsite.models import Category
from CanteenWebsite.utils.functions import setting_get
register = template.Library()
@register.simple_tag
def | (name, default=None):
return setting_get(name, default)
@register.inclusion_tag('CanteenWebsite/inclusions/sidebar_category_list.html', takes_context=True)
def sidebar_category_list(context):
categories = Category.objects.all()
try:
current_category = context['current_category']
except:
current_category = None
return {
'current': current_category,
'categories': categories,
}
@register.inclusion_tag('CanteenWebsite/inclusions/pagination.html')
def show_pagination(page):
pagination = page.paginator
page_range = list()
if pagination.num_pages <= 10:
page_range = pagination.page_range
else:
ON_EACH_SIDE = 2
ON_ENDS = 2
DOT = '...'
if page.number > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(1, ON_ENDS))
page_range.append(DOT)
page_range.extend(range(page.number - ON_EACH_SIDE, page.number + 1))
else:
page_range.extend(range(1, page.number + 1))
if page.number < (pagination.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page.number + 1, page.number + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(pagination.num_pages - ON_ENDS, pagination.num_pages + 1))
else:
page_range.extend(range(page.number + 1, pagination.num_pages + 1))
return {
'page': page,
'pages': page_range
}
@register.assignment_tag
def define(val=None):
return val
| get_setting | identifier_name |
canteen_website_tags.py | # -*- coding: utf-8 -*-
from django import template
from CanteenWebsite.models import Category
from CanteenWebsite.utils.functions import setting_get
register = template.Library()
@register.simple_tag
def get_setting(name, default=None):
return setting_get(name, default)
@register.inclusion_tag('CanteenWebsite/inclusions/sidebar_category_list.html', takes_context=True)
def sidebar_category_list(context):
categories = Category.objects.all()
try:
current_category = context['current_category']
except:
current_category = None
return {
'current': current_category,
'categories': categories,
}
@register.inclusion_tag('CanteenWebsite/inclusions/pagination.html')
def show_pagination(page):
pagination = page.paginator
page_range = list()
if pagination.num_pages <= 10:
page_range = pagination.page_range
else:
ON_EACH_SIDE = 2 | DOT = '...'
if page.number > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(1, ON_ENDS))
page_range.append(DOT)
page_range.extend(range(page.number - ON_EACH_SIDE, page.number + 1))
else:
page_range.extend(range(1, page.number + 1))
if page.number < (pagination.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page.number + 1, page.number + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(pagination.num_pages - ON_ENDS, pagination.num_pages + 1))
else:
page_range.extend(range(page.number + 1, pagination.num_pages + 1))
return {
'page': page,
'pages': page_range
}
@register.assignment_tag
def define(val=None):
return val | ON_ENDS = 2 | random_line_split |
canteen_website_tags.py | # -*- coding: utf-8 -*-
from django import template
from CanteenWebsite.models import Category
from CanteenWebsite.utils.functions import setting_get
register = template.Library()
@register.simple_tag
def get_setting(name, default=None):
return setting_get(name, default)
@register.inclusion_tag('CanteenWebsite/inclusions/sidebar_category_list.html', takes_context=True)
def sidebar_category_list(context):
|
@register.inclusion_tag('CanteenWebsite/inclusions/pagination.html')
def show_pagination(page):
pagination = page.paginator
page_range = list()
if pagination.num_pages <= 10:
page_range = pagination.page_range
else:
ON_EACH_SIDE = 2
ON_ENDS = 2
DOT = '...'
if page.number > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(1, ON_ENDS))
page_range.append(DOT)
page_range.extend(range(page.number - ON_EACH_SIDE, page.number + 1))
else:
page_range.extend(range(1, page.number + 1))
if page.number < (pagination.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page.number + 1, page.number + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(pagination.num_pages - ON_ENDS, pagination.num_pages + 1))
else:
page_range.extend(range(page.number + 1, pagination.num_pages + 1))
return {
'page': page,
'pages': page_range
}
@register.assignment_tag
def define(val=None):
return val
| categories = Category.objects.all()
try:
current_category = context['current_category']
except:
current_category = None
return {
'current': current_category,
'categories': categories,
} | identifier_body |
canteen_website_tags.py | # -*- coding: utf-8 -*-
from django import template
from CanteenWebsite.models import Category
from CanteenWebsite.utils.functions import setting_get
register = template.Library()
@register.simple_tag
def get_setting(name, default=None):
return setting_get(name, default)
@register.inclusion_tag('CanteenWebsite/inclusions/sidebar_category_list.html', takes_context=True)
def sidebar_category_list(context):
categories = Category.objects.all()
try:
current_category = context['current_category']
except:
current_category = None
return {
'current': current_category,
'categories': categories,
}
@register.inclusion_tag('CanteenWebsite/inclusions/pagination.html')
def show_pagination(page):
pagination = page.paginator
page_range = list()
if pagination.num_pages <= 10:
|
else:
ON_EACH_SIDE = 2
ON_ENDS = 2
DOT = '...'
if page.number > (ON_EACH_SIDE + ON_ENDS):
page_range.extend(range(1, ON_ENDS))
page_range.append(DOT)
page_range.extend(range(page.number - ON_EACH_SIDE, page.number + 1))
else:
page_range.extend(range(1, page.number + 1))
if page.number < (pagination.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page.number + 1, page.number + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(pagination.num_pages - ON_ENDS, pagination.num_pages + 1))
else:
page_range.extend(range(page.number + 1, pagination.num_pages + 1))
return {
'page': page,
'pages': page_range
}
@register.assignment_tag
def define(val=None):
return val
| page_range = pagination.page_range | conditional_block |
map.rs | use std::ops::Range;
use cgmath::{Vector3, InnerSpace, Zero};
use noise::{BasicMulti, Seedable, NoiseModule};
use spherical_voronoi as sv;
use rand::{thread_rng, Rng, Rand};
use color::Color;
use ideal::{IdVec, IdsIter};
use settings;
#[derive(Copy, Clone, PartialEq)]
#[derive(Serialize, Deserialize)]
pub enum CornerKind {
Water,
Land,
Coast,
River,
}
#[derive(Clone)]
#[derive(Serialize, Deserialize)]
pub struct CornerData {
regions: Vec<Region>,
position: Vector3<f64>,
kind: CornerKind,
elevation: f64,
}
create_id!(Corner);
#[derive(Copy, Clone, PartialEq)]
#[derive(Serialize, Deserialize)]
pub enum BorderKind {
River,
Coast,
None,
}
#[derive(Clone)]
#[derive(Serialize, Deserialize)]
pub struct BorderData {
kind: BorderKind,
corners: (Corner, Corner),
regions: (Region, Region),
}
create_id!(Border);
#[derive(Clone, PartialEq, Debug)]
#[derive(Serialize, Deserialize)]
pub struct BiomeData {
name: String,
color: Color,
is_land: bool,
}
create_id!(Biome);
#[derive(Clone)]
#[derive(Serialize, Deserialize)]
pub struct RegionData {
biome: Biome,
corners: Vec<Corner>,
borders: Vec<Border>,
center: Vector3<f64>,
elevation: f64,
}
create_id!(Region);
#[derive(Serialize, Deserialize)]
pub struct Map {
biomes: IdVec<Biome, BiomeData>,
corners: IdVec<Corner, CornerData>,
borders: IdVec<Border, BorderData>,
regions: IdVec<Region, RegionData>,
}
pub struct Neighbors<'a, 'b> {
borders: &'a IdVec<Border, BorderData>,
region: Region,
inner: ::std::slice::Iter<'b, Border>,
}
impl<'a, 'b> ::std::iter::Iterator for Neighbors<'a, 'b> {
type Item = Region;
fn next(&mut self) -> Option<Self::Item> {
if let Some(border) = self.inner.next() {
let (region0, region1) = self.borders[*border].regions;
if region0 == self.region {
Some(region1)
} else {
Some(region0)
}
} else {
None
}
}
}
impl Map {
pub fn regions(&self) -> IdsIter<Region> {
self.regions.ids()
}
pub fn borders(&self) -> IdsIter<Border> {
self.borders.ids()
}
pub fn corners(&self) -> IdsIter<Corner> {
self.corners.ids()
}
pub fn neighbors(&self, region: Region) -> Neighbors {
Neighbors {
borders: &self.borders,
region: region,
inner: self.regions[region].borders.iter(),
}
}
pub fn border_corners(&self, border: Border) -> (Corner, Corner) {
self.borders[border].corners
}
pub fn border_regions(&self, border: Border) -> (Region, Region) {
self.borders[border].regions
}
pub fn border_kind(&self, border: Border) -> BorderKind {
self.borders[border].kind
}
pub fn biome(&self, region: Region) -> Biome {
self.regions[region].biome
}
pub fn is_land(&self, region: Region) -> bool {
self.biomes[self.biome(region)].is_land
}
pub fn biome_color(&self, biome: Biome) -> Color {
self.biomes[biome].color
}
pub fn region_center(&self, region: Region) -> Vector3<f64> {
self.regions[region].center
}
pub fn region_borders(&self, region: Region) -> &[Border] {
&self.regions[region].borders
}
pub fn region_elevation(&self, region: Region) -> f64 {
self.regions[region].elevation
}
pub fn corner_elevation(&self, corner: Corner) -> f64 {
self.corners[corner].elevation
}
pub fn corner_position(&self, corner: Corner) -> Vector3<f64> {
self.corners[corner].position
}
pub fn corner_regions(&self, corner: Corner) -> &[Region] {
&self.corners[corner].regions
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Generator {
size: usize,
relaxations: usize,
sea_level: f64,
elevation_equator_bias: f64,
temperature_equator_bias: f64,
moisture_equator_bias: f64,
noise: settings::NoiseSettings,
biomes: Vec<BiomeData>,
ocean: Biome,
sea: Biome,
land_biomes: Vec<Vec<Biome>>,
}
impl Generator {
pub fn generate(&self) -> Map {
let mut visitor = Visitor::default();
sv::build_relaxed(&generate_points(self.size), &mut visitor, self.relaxations);
let Visitor { mut corners, mut borders, mut regions } = visitor;
for region in regions.ids() {
regions[region].center = regions[region].corners
.iter()
.fold(Vector3::zero(), |acc, &corner| acc + corners[corner].position)
.normalize()
.into();
}
let mut biomes = IdVec::default();
for biome in self.biomes.iter() {
biomes.push(biome.clone());
}
let mut map = Map {
biomes: biomes,
corners: corners,
borders: borders,
regions: regions,
};
self.generate_biomes(&mut map);
//self.generate_rivers(&mut map);
map
}
fn generate_biomes(&self, map: &mut Map) {
let elevations = self.generate_noise(map, self.elevation_equator_bias);
let temperatures = self.generate_noise(map, self.temperature_equator_bias);
let moistures = self.generate_noise(map, self.moisture_equator_bias);
for region in map.regions() {
let elevation = elevations[region];
map.regions[region].elevation = elevation;
if elevation < self.sea_level {
map.regions[region].biome = self.ocean;
} else {
map.regions[region].biome = self.get_biome(temperatures[region], moistures[region]);
}
}
for region in map.regions() {
if map.biome(region) == self.ocean &&
map.neighbors(region).any(|neighbor| map.is_land(neighbor)) |
}
for corner in map.corners() {
let elevation = {
let regions = map.corner_regions(corner);
let len = regions.len() as f64;
regions.iter().map(|®ion| map.region_elevation(region)).sum::<f64>() / len
};
map.corners[corner].elevation = elevation;
}
}
fn get_biome(&self, temperature: f64, moisture: f64) -> Biome {
let biomes = get_element(self.land_biomes.as_slice(), temperature);
*get_element(biomes, moisture)
}
fn generate_noise(&self, map: &Map, equator_bias: f64) -> IdVec<Region, f64> {
let noise = BasicMulti::new().set_seed(thread_rng().gen());
let mut pairs = Vec::new();
for region in map.regions() {
let center = map.region_center(region);
pairs.push((region, noise.get([center.x, center.y, center.z]) + equator_bias * (1.0 - center[2].abs())));
}
pairs.sort_by(|left, right| left.1.partial_cmp(&right.1).unwrap());
let mut values = IdVec::from(vec![0.0; pairs.len()]);
for (index, &(region, _)) in pairs.iter().enumerate() {
values[region] = index as f64 / pairs.len() as f64;
}
values
}
// fn generate_rivers(&self, map: &mut Map) {
// for vertex in map.diagram.vertices() {
// let mut elevation = map.vertex_elevation(vertex);
// if elevation > 0.8 {
// let mut vertex = vertex;
// while map.vertex_kind(vertex) == VertexKind::Land {
// map.vertices[vertex.index()].kind = VertexKind::River;
// let mut edge = None;
// let mut next = vertex;
// // find the lowest adjacent corner
// for &e in map.diagram.vertex_edges(vertex) {
// let v = map.diagram.other_edge_vertex(e, vertex);
// let el = map.vertex_elevation(v);
// if el < elevation {
// elevation = el;
// edge = Some(e);
// next = v;
// }
// }
// if let Some(edge) = edge {
// map.edges[edge.index()].kind = EdgeKind::River;
// vertex = next;
// } else {
// break;
// }
// }
// }
// }
// }
}
#[derive(Default)]
struct Visitor {
corners: IdVec<Corner, CornerData>,
borders: IdVec<Border, BorderData>,
regions: IdVec<Region, RegionData>,
}
impl Visitor {
fn common_regions(&self, corner0: Corner, corner1: Corner) -> (Region, Region) {
let mut regions = (Region::invalid(), Region::invalid());
for ®ion0 in self.corners[corner0].regions.iter() {
for ®ion1 in self.corners[corner1].regions.iter() {
if region0 == region1 {
if regions.0.is_invalid() {
regions.0 = region0;
} else {
regions.1 = region0;
}
}
}
}
regions
}
}
impl sv::Visitor for Visitor {
fn vertex(&mut self, position: Vector3<f64>, cells: [usize; 3]) {
let region0 = Region(cells[0]);
let region1 = Region(cells[1]);
let region2 = Region(cells[2]);
let corner = self.corners.push(CornerData {
regions: vec![region0, region1, region2],
position: position,
elevation: 0.0,
kind: CornerKind::Water,
});
self.regions[region0].corners.push(corner);
self.regions[region1].corners.push(corner);
self.regions[region2].corners.push(corner);
}
fn edge(&mut self, vertices: [usize; 2]) {
let corner0 = Corner(vertices[0]);
let corner1 = Corner(vertices[1]);
let (region0, region1) = self.common_regions(corner0, corner1);
let border = self.borders.push(BorderData {
kind: BorderKind::None,
corners: (corner0, corner1),
regions: (region0, region1),
});
self.regions[region0].borders.push(border);
self.regions[region1].borders.push(border);
}
fn cell(&mut self) {
self.regions.push(RegionData {
corners: Vec::new(),
borders: Vec::new(),
center: Vector3::zero(),
elevation: 0.0,
biome: Biome(0),
});
}
}
fn generate_points(count: usize) -> Vec<Vector3<f64>> {
let mut points = Vec::with_capacity(count);
let mut created = 0;
while created < count {
let x1 = thread_rng().gen_range(-1.0f64, 1.0);
let x2 = thread_rng().gen_range(-1.0f64, 1.0);
let norm2 = x1 * x1 + x2 * x2;
if norm2 < 1.0 {
created += 1;
let x = 2.0 * x1 * (1.0 - norm2).sqrt();
let y = 2.0 * x2 * (1.0 - norm2).sqrt();
let z = 1.0 - 2.0 * norm2;
points.push(Vector3::new(x, y, z));
}
}
points
}
fn get_element<T>(items: &[T], index: f64) -> &T {
&items[((items.len() as f64) * index).floor() as usize]
}
| {
map.regions[region].biome = self.sea;
} | conditional_block |
map.rs | use std::ops::Range;
use cgmath::{Vector3, InnerSpace, Zero};
use noise::{BasicMulti, Seedable, NoiseModule};
use spherical_voronoi as sv;
use rand::{thread_rng, Rng, Rand};
use color::Color;
use ideal::{IdVec, IdsIter};
use settings;
#[derive(Copy, Clone, PartialEq)]
#[derive(Serialize, Deserialize)]
pub enum CornerKind {
Water,
Land,
Coast,
River,
}
#[derive(Clone)]
#[derive(Serialize, Deserialize)]
pub struct | {
regions: Vec<Region>,
position: Vector3<f64>,
kind: CornerKind,
elevation: f64,
}
create_id!(Corner);
#[derive(Copy, Clone, PartialEq)]
#[derive(Serialize, Deserialize)]
pub enum BorderKind {
River,
Coast,
None,
}
#[derive(Clone)]
#[derive(Serialize, Deserialize)]
pub struct BorderData {
kind: BorderKind,
corners: (Corner, Corner),
regions: (Region, Region),
}
create_id!(Border);
#[derive(Clone, PartialEq, Debug)]
#[derive(Serialize, Deserialize)]
pub struct BiomeData {
name: String,
color: Color,
is_land: bool,
}
create_id!(Biome);
#[derive(Clone)]
#[derive(Serialize, Deserialize)]
pub struct RegionData {
biome: Biome,
corners: Vec<Corner>,
borders: Vec<Border>,
center: Vector3<f64>,
elevation: f64,
}
create_id!(Region);
#[derive(Serialize, Deserialize)]
pub struct Map {
biomes: IdVec<Biome, BiomeData>,
corners: IdVec<Corner, CornerData>,
borders: IdVec<Border, BorderData>,
regions: IdVec<Region, RegionData>,
}
pub struct Neighbors<'a, 'b> {
borders: &'a IdVec<Border, BorderData>,
region: Region,
inner: ::std::slice::Iter<'b, Border>,
}
impl<'a, 'b> ::std::iter::Iterator for Neighbors<'a, 'b> {
type Item = Region;
fn next(&mut self) -> Option<Self::Item> {
if let Some(border) = self.inner.next() {
let (region0, region1) = self.borders[*border].regions;
if region0 == self.region {
Some(region1)
} else {
Some(region0)
}
} else {
None
}
}
}
impl Map {
pub fn regions(&self) -> IdsIter<Region> {
self.regions.ids()
}
pub fn borders(&self) -> IdsIter<Border> {
self.borders.ids()
}
pub fn corners(&self) -> IdsIter<Corner> {
self.corners.ids()
}
pub fn neighbors(&self, region: Region) -> Neighbors {
Neighbors {
borders: &self.borders,
region: region,
inner: self.regions[region].borders.iter(),
}
}
pub fn border_corners(&self, border: Border) -> (Corner, Corner) {
self.borders[border].corners
}
pub fn border_regions(&self, border: Border) -> (Region, Region) {
self.borders[border].regions
}
pub fn border_kind(&self, border: Border) -> BorderKind {
self.borders[border].kind
}
pub fn biome(&self, region: Region) -> Biome {
self.regions[region].biome
}
pub fn is_land(&self, region: Region) -> bool {
self.biomes[self.biome(region)].is_land
}
pub fn biome_color(&self, biome: Biome) -> Color {
self.biomes[biome].color
}
pub fn region_center(&self, region: Region) -> Vector3<f64> {
self.regions[region].center
}
pub fn region_borders(&self, region: Region) -> &[Border] {
&self.regions[region].borders
}
pub fn region_elevation(&self, region: Region) -> f64 {
self.regions[region].elevation
}
pub fn corner_elevation(&self, corner: Corner) -> f64 {
self.corners[corner].elevation
}
pub fn corner_position(&self, corner: Corner) -> Vector3<f64> {
self.corners[corner].position
}
pub fn corner_regions(&self, corner: Corner) -> &[Region] {
&self.corners[corner].regions
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Generator {
size: usize,
relaxations: usize,
sea_level: f64,
elevation_equator_bias: f64,
temperature_equator_bias: f64,
moisture_equator_bias: f64,
noise: settings::NoiseSettings,
biomes: Vec<BiomeData>,
ocean: Biome,
sea: Biome,
land_biomes: Vec<Vec<Biome>>,
}
impl Generator {
pub fn generate(&self) -> Map {
let mut visitor = Visitor::default();
sv::build_relaxed(&generate_points(self.size), &mut visitor, self.relaxations);
let Visitor { mut corners, mut borders, mut regions } = visitor;
for region in regions.ids() {
regions[region].center = regions[region].corners
.iter()
.fold(Vector3::zero(), |acc, &corner| acc + corners[corner].position)
.normalize()
.into();
}
let mut biomes = IdVec::default();
for biome in self.biomes.iter() {
biomes.push(biome.clone());
}
let mut map = Map {
biomes: biomes,
corners: corners,
borders: borders,
regions: regions,
};
self.generate_biomes(&mut map);
//self.generate_rivers(&mut map);
map
}
fn generate_biomes(&self, map: &mut Map) {
let elevations = self.generate_noise(map, self.elevation_equator_bias);
let temperatures = self.generate_noise(map, self.temperature_equator_bias);
let moistures = self.generate_noise(map, self.moisture_equator_bias);
for region in map.regions() {
let elevation = elevations[region];
map.regions[region].elevation = elevation;
if elevation < self.sea_level {
map.regions[region].biome = self.ocean;
} else {
map.regions[region].biome = self.get_biome(temperatures[region], moistures[region]);
}
}
for region in map.regions() {
if map.biome(region) == self.ocean &&
map.neighbors(region).any(|neighbor| map.is_land(neighbor)) {
map.regions[region].biome = self.sea;
}
}
for corner in map.corners() {
let elevation = {
let regions = map.corner_regions(corner);
let len = regions.len() as f64;
regions.iter().map(|®ion| map.region_elevation(region)).sum::<f64>() / len
};
map.corners[corner].elevation = elevation;
}
}
fn get_biome(&self, temperature: f64, moisture: f64) -> Biome {
let biomes = get_element(self.land_biomes.as_slice(), temperature);
*get_element(biomes, moisture)
}
fn generate_noise(&self, map: &Map, equator_bias: f64) -> IdVec<Region, f64> {
let noise = BasicMulti::new().set_seed(thread_rng().gen());
let mut pairs = Vec::new();
for region in map.regions() {
let center = map.region_center(region);
pairs.push((region, noise.get([center.x, center.y, center.z]) + equator_bias * (1.0 - center[2].abs())));
}
pairs.sort_by(|left, right| left.1.partial_cmp(&right.1).unwrap());
let mut values = IdVec::from(vec![0.0; pairs.len()]);
for (index, &(region, _)) in pairs.iter().enumerate() {
values[region] = index as f64 / pairs.len() as f64;
}
values
}
// fn generate_rivers(&self, map: &mut Map) {
// for vertex in map.diagram.vertices() {
// let mut elevation = map.vertex_elevation(vertex);
// if elevation > 0.8 {
// let mut vertex = vertex;
// while map.vertex_kind(vertex) == VertexKind::Land {
// map.vertices[vertex.index()].kind = VertexKind::River;
// let mut edge = None;
// let mut next = vertex;
// // find the lowest adjacent corner
// for &e in map.diagram.vertex_edges(vertex) {
// let v = map.diagram.other_edge_vertex(e, vertex);
// let el = map.vertex_elevation(v);
// if el < elevation {
// elevation = el;
// edge = Some(e);
// next = v;
// }
// }
// if let Some(edge) = edge {
// map.edges[edge.index()].kind = EdgeKind::River;
// vertex = next;
// } else {
// break;
// }
// }
// }
// }
// }
}
#[derive(Default)]
struct Visitor {
corners: IdVec<Corner, CornerData>,
borders: IdVec<Border, BorderData>,
regions: IdVec<Region, RegionData>,
}
impl Visitor {
fn common_regions(&self, corner0: Corner, corner1: Corner) -> (Region, Region) {
let mut regions = (Region::invalid(), Region::invalid());
for ®ion0 in self.corners[corner0].regions.iter() {
for ®ion1 in self.corners[corner1].regions.iter() {
if region0 == region1 {
if regions.0.is_invalid() {
regions.0 = region0;
} else {
regions.1 = region0;
}
}
}
}
regions
}
}
impl sv::Visitor for Visitor {
fn vertex(&mut self, position: Vector3<f64>, cells: [usize; 3]) {
let region0 = Region(cells[0]);
let region1 = Region(cells[1]);
let region2 = Region(cells[2]);
let corner = self.corners.push(CornerData {
regions: vec![region0, region1, region2],
position: position,
elevation: 0.0,
kind: CornerKind::Water,
});
self.regions[region0].corners.push(corner);
self.regions[region1].corners.push(corner);
self.regions[region2].corners.push(corner);
}
fn edge(&mut self, vertices: [usize; 2]) {
let corner0 = Corner(vertices[0]);
let corner1 = Corner(vertices[1]);
let (region0, region1) = self.common_regions(corner0, corner1);
let border = self.borders.push(BorderData {
kind: BorderKind::None,
corners: (corner0, corner1),
regions: (region0, region1),
});
self.regions[region0].borders.push(border);
self.regions[region1].borders.push(border);
}
fn cell(&mut self) {
self.regions.push(RegionData {
corners: Vec::new(),
borders: Vec::new(),
center: Vector3::zero(),
elevation: 0.0,
biome: Biome(0),
});
}
}
fn generate_points(count: usize) -> Vec<Vector3<f64>> {
let mut points = Vec::with_capacity(count);
let mut created = 0;
while created < count {
let x1 = thread_rng().gen_range(-1.0f64, 1.0);
let x2 = thread_rng().gen_range(-1.0f64, 1.0);
let norm2 = x1 * x1 + x2 * x2;
if norm2 < 1.0 {
created += 1;
let x = 2.0 * x1 * (1.0 - norm2).sqrt();
let y = 2.0 * x2 * (1.0 - norm2).sqrt();
let z = 1.0 - 2.0 * norm2;
points.push(Vector3::new(x, y, z));
}
}
points
}
fn get_element<T>(items: &[T], index: f64) -> &T {
&items[((items.len() as f64) * index).floor() as usize]
}
| CornerData | identifier_name |
map.rs | use std::ops::Range;
use cgmath::{Vector3, InnerSpace, Zero};
use noise::{BasicMulti, Seedable, NoiseModule};
use spherical_voronoi as sv;
use rand::{thread_rng, Rng, Rand};
use color::Color;
use ideal::{IdVec, IdsIter};
use settings;
#[derive(Copy, Clone, PartialEq)]
#[derive(Serialize, Deserialize)]
pub enum CornerKind {
Water,
Land,
Coast,
River,
}
#[derive(Clone)]
#[derive(Serialize, Deserialize)]
pub struct CornerData {
regions: Vec<Region>,
position: Vector3<f64>,
kind: CornerKind,
elevation: f64,
}
create_id!(Corner);
#[derive(Copy, Clone, PartialEq)]
#[derive(Serialize, Deserialize)]
pub enum BorderKind {
River,
Coast,
None,
}
#[derive(Clone)]
#[derive(Serialize, Deserialize)]
pub struct BorderData {
kind: BorderKind,
corners: (Corner, Corner),
regions: (Region, Region),
}
create_id!(Border);
#[derive(Clone, PartialEq, Debug)]
#[derive(Serialize, Deserialize)]
pub struct BiomeData {
name: String,
color: Color,
is_land: bool,
}
create_id!(Biome);
#[derive(Clone)]
#[derive(Serialize, Deserialize)]
pub struct RegionData {
biome: Biome,
corners: Vec<Corner>,
borders: Vec<Border>,
center: Vector3<f64>,
elevation: f64,
}
create_id!(Region);
#[derive(Serialize, Deserialize)]
pub struct Map {
biomes: IdVec<Biome, BiomeData>,
corners: IdVec<Corner, CornerData>,
borders: IdVec<Border, BorderData>,
regions: IdVec<Region, RegionData>, | borders: &'a IdVec<Border, BorderData>,
region: Region,
inner: ::std::slice::Iter<'b, Border>,
}
impl<'a, 'b> ::std::iter::Iterator for Neighbors<'a, 'b> {
type Item = Region;
fn next(&mut self) -> Option<Self::Item> {
if let Some(border) = self.inner.next() {
let (region0, region1) = self.borders[*border].regions;
if region0 == self.region {
Some(region1)
} else {
Some(region0)
}
} else {
None
}
}
}
impl Map {
pub fn regions(&self) -> IdsIter<Region> {
self.regions.ids()
}
pub fn borders(&self) -> IdsIter<Border> {
self.borders.ids()
}
pub fn corners(&self) -> IdsIter<Corner> {
self.corners.ids()
}
pub fn neighbors(&self, region: Region) -> Neighbors {
Neighbors {
borders: &self.borders,
region: region,
inner: self.regions[region].borders.iter(),
}
}
pub fn border_corners(&self, border: Border) -> (Corner, Corner) {
self.borders[border].corners
}
pub fn border_regions(&self, border: Border) -> (Region, Region) {
self.borders[border].regions
}
pub fn border_kind(&self, border: Border) -> BorderKind {
self.borders[border].kind
}
pub fn biome(&self, region: Region) -> Biome {
self.regions[region].biome
}
pub fn is_land(&self, region: Region) -> bool {
self.biomes[self.biome(region)].is_land
}
pub fn biome_color(&self, biome: Biome) -> Color {
self.biomes[biome].color
}
pub fn region_center(&self, region: Region) -> Vector3<f64> {
self.regions[region].center
}
pub fn region_borders(&self, region: Region) -> &[Border] {
&self.regions[region].borders
}
pub fn region_elevation(&self, region: Region) -> f64 {
self.regions[region].elevation
}
pub fn corner_elevation(&self, corner: Corner) -> f64 {
self.corners[corner].elevation
}
pub fn corner_position(&self, corner: Corner) -> Vector3<f64> {
self.corners[corner].position
}
pub fn corner_regions(&self, corner: Corner) -> &[Region] {
&self.corners[corner].regions
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Generator {
size: usize,
relaxations: usize,
sea_level: f64,
elevation_equator_bias: f64,
temperature_equator_bias: f64,
moisture_equator_bias: f64,
noise: settings::NoiseSettings,
biomes: Vec<BiomeData>,
ocean: Biome,
sea: Biome,
land_biomes: Vec<Vec<Biome>>,
}
impl Generator {
pub fn generate(&self) -> Map {
let mut visitor = Visitor::default();
sv::build_relaxed(&generate_points(self.size), &mut visitor, self.relaxations);
let Visitor { mut corners, mut borders, mut regions } = visitor;
for region in regions.ids() {
regions[region].center = regions[region].corners
.iter()
.fold(Vector3::zero(), |acc, &corner| acc + corners[corner].position)
.normalize()
.into();
}
let mut biomes = IdVec::default();
for biome in self.biomes.iter() {
biomes.push(biome.clone());
}
let mut map = Map {
biomes: biomes,
corners: corners,
borders: borders,
regions: regions,
};
self.generate_biomes(&mut map);
//self.generate_rivers(&mut map);
map
}
fn generate_biomes(&self, map: &mut Map) {
let elevations = self.generate_noise(map, self.elevation_equator_bias);
let temperatures = self.generate_noise(map, self.temperature_equator_bias);
let moistures = self.generate_noise(map, self.moisture_equator_bias);
for region in map.regions() {
let elevation = elevations[region];
map.regions[region].elevation = elevation;
if elevation < self.sea_level {
map.regions[region].biome = self.ocean;
} else {
map.regions[region].biome = self.get_biome(temperatures[region], moistures[region]);
}
}
for region in map.regions() {
if map.biome(region) == self.ocean &&
map.neighbors(region).any(|neighbor| map.is_land(neighbor)) {
map.regions[region].biome = self.sea;
}
}
for corner in map.corners() {
let elevation = {
let regions = map.corner_regions(corner);
let len = regions.len() as f64;
regions.iter().map(|®ion| map.region_elevation(region)).sum::<f64>() / len
};
map.corners[corner].elevation = elevation;
}
}
fn get_biome(&self, temperature: f64, moisture: f64) -> Biome {
let biomes = get_element(self.land_biomes.as_slice(), temperature);
*get_element(biomes, moisture)
}
fn generate_noise(&self, map: &Map, equator_bias: f64) -> IdVec<Region, f64> {
let noise = BasicMulti::new().set_seed(thread_rng().gen());
let mut pairs = Vec::new();
for region in map.regions() {
let center = map.region_center(region);
pairs.push((region, noise.get([center.x, center.y, center.z]) + equator_bias * (1.0 - center[2].abs())));
}
pairs.sort_by(|left, right| left.1.partial_cmp(&right.1).unwrap());
let mut values = IdVec::from(vec![0.0; pairs.len()]);
for (index, &(region, _)) in pairs.iter().enumerate() {
values[region] = index as f64 / pairs.len() as f64;
}
values
}
// fn generate_rivers(&self, map: &mut Map) {
// for vertex in map.diagram.vertices() {
// let mut elevation = map.vertex_elevation(vertex);
// if elevation > 0.8 {
// let mut vertex = vertex;
// while map.vertex_kind(vertex) == VertexKind::Land {
// map.vertices[vertex.index()].kind = VertexKind::River;
// let mut edge = None;
// let mut next = vertex;
// // find the lowest adjacent corner
// for &e in map.diagram.vertex_edges(vertex) {
// let v = map.diagram.other_edge_vertex(e, vertex);
// let el = map.vertex_elevation(v);
// if el < elevation {
// elevation = el;
// edge = Some(e);
// next = v;
// }
// }
// if let Some(edge) = edge {
// map.edges[edge.index()].kind = EdgeKind::River;
// vertex = next;
// } else {
// break;
// }
// }
// }
// }
// }
}
#[derive(Default)]
struct Visitor {
corners: IdVec<Corner, CornerData>,
borders: IdVec<Border, BorderData>,
regions: IdVec<Region, RegionData>,
}
impl Visitor {
fn common_regions(&self, corner0: Corner, corner1: Corner) -> (Region, Region) {
let mut regions = (Region::invalid(), Region::invalid());
for ®ion0 in self.corners[corner0].regions.iter() {
for ®ion1 in self.corners[corner1].regions.iter() {
if region0 == region1 {
if regions.0.is_invalid() {
regions.0 = region0;
} else {
regions.1 = region0;
}
}
}
}
regions
}
}
impl sv::Visitor for Visitor {
fn vertex(&mut self, position: Vector3<f64>, cells: [usize; 3]) {
let region0 = Region(cells[0]);
let region1 = Region(cells[1]);
let region2 = Region(cells[2]);
let corner = self.corners.push(CornerData {
regions: vec![region0, region1, region2],
position: position,
elevation: 0.0,
kind: CornerKind::Water,
});
self.regions[region0].corners.push(corner);
self.regions[region1].corners.push(corner);
self.regions[region2].corners.push(corner);
}
fn edge(&mut self, vertices: [usize; 2]) {
let corner0 = Corner(vertices[0]);
let corner1 = Corner(vertices[1]);
let (region0, region1) = self.common_regions(corner0, corner1);
let border = self.borders.push(BorderData {
kind: BorderKind::None,
corners: (corner0, corner1),
regions: (region0, region1),
});
self.regions[region0].borders.push(border);
self.regions[region1].borders.push(border);
}
fn cell(&mut self) {
self.regions.push(RegionData {
corners: Vec::new(),
borders: Vec::new(),
center: Vector3::zero(),
elevation: 0.0,
biome: Biome(0),
});
}
}
fn generate_points(count: usize) -> Vec<Vector3<f64>> {
let mut points = Vec::with_capacity(count);
let mut created = 0;
while created < count {
let x1 = thread_rng().gen_range(-1.0f64, 1.0);
let x2 = thread_rng().gen_range(-1.0f64, 1.0);
let norm2 = x1 * x1 + x2 * x2;
if norm2 < 1.0 {
created += 1;
let x = 2.0 * x1 * (1.0 - norm2).sqrt();
let y = 2.0 * x2 * (1.0 - norm2).sqrt();
let z = 1.0 - 2.0 * norm2;
points.push(Vector3::new(x, y, z));
}
}
points
}
fn get_element<T>(items: &[T], index: f64) -> &T {
&items[((items.len() as f64) * index).floor() as usize]
} | }
pub struct Neighbors<'a, 'b> { | random_line_split |
train.py | # coding=utf-8
# Copyright 2019 The Interval Bound Propagation Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Trains a verifiable model on Mnist or CIFAR-10."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import app
from absl import flags
from absl import logging
import interval_bound_propagation as ibp
import tensorflow.compat.v1 as tf
FLAGS = flags.FLAGS
flags.DEFINE_enum('dataset', 'mnist', ['mnist', 'cifar10'],
'Dataset (either "mnist" or "cifar10").')
flags.DEFINE_enum('model', 'tiny', ['tiny', 'small', 'medium', 'large'],
'Model size.')
flags.DEFINE_string('output_dir', '/tmp/ibp_model', 'Output directory.')
# Options.
flags.DEFINE_integer('steps', 60001, 'Number of steps in total.')
flags.DEFINE_integer('test_every_n', 2000,
'Number of steps between testing iterations.')
flags.DEFINE_integer('warmup_steps', 2000, 'Number of warm-up steps.')
flags.DEFINE_integer('rampup_steps', 10000, 'Number of ramp-up steps.')
flags.DEFINE_integer('batch_size', 200, 'Batch size.')
flags.DEFINE_float('epsilon', .3, 'Target epsilon.')
flags.DEFINE_float('epsilon_train', .33, 'Train epsilon.')
flags.DEFINE_string('learning_rate', '1e-3,1e-4@15000,1e-5@25000',
'Learning rate schedule of the form: '
'initial_learning_rate[,learning:steps]*. E.g., "1e-3" or '
'"1e-3,1e-4@15000,1e-5@25000".')
flags.DEFINE_float('nominal_xent_init', 1.,
'Initial weight for the nominal cross-entropy.')
flags.DEFINE_float('nominal_xent_final', .5,
'Final weight for the nominal cross-entropy.')
flags.DEFINE_float('verified_xent_init', 0.,
'Initial weight for the verified cross-entropy.')
flags.DEFINE_float('verified_xent_final', .5,
'Final weight for the verified cross-entropy.')
flags.DEFINE_float('crown_bound_init', 0.,
'Initial weight for mixing the CROWN bound with the IBP '
'bound in the verified cross-entropy.')
flags.DEFINE_float('crown_bound_final', 0.,
'Final weight for mixing the CROWN bound with the IBP '
'bound in the verified cross-entropy.')
flags.DEFINE_float('attack_xent_init', 0.,
'Initial weight for the attack cross-entropy.')
flags.DEFINE_float('attack_xent_final', 0.,
'Initial weight for the attack cross-entropy.')
def show_metrics(step_value, metric_values, loss_value=None):
print('{}: {}nominal accuracy = {:.2f}%, '
'verified = {:.2f}%, attack = {:.2f}%'.format(
step_value,
'loss = {}, '.format(loss_value) if loss_value is not None else '',
metric_values.nominal_accuracy * 100.,
metric_values.verified_accuracy * 100.,
metric_values.attack_accuracy * 100.))
def layers(model_size):
|
def main(unused_args):
logging.info('Training IBP on %s...', FLAGS.dataset.upper())
step = tf.train.get_or_create_global_step()
# Learning rate.
learning_rate = ibp.parse_learning_rate(step, FLAGS.learning_rate)
# Dataset.
input_bounds = (0., 1.)
num_classes = 10
if FLAGS.dataset == 'mnist':
data_train, data_test = tf.keras.datasets.mnist.load_data()
else:
assert FLAGS.dataset == 'cifar10', (
'Unknown dataset "{}"'.format(FLAGS.dataset))
data_train, data_test = tf.keras.datasets.cifar10.load_data()
data_train = (data_train[0], data_train[1].flatten())
data_test = (data_test[0], data_test[1].flatten())
data = ibp.build_dataset(data_train, batch_size=FLAGS.batch_size,
sequential=False)
if FLAGS.dataset == 'cifar10':
data = data._replace(image=ibp.randomize(
data.image, (32, 32, 3), expand_shape=(40, 40, 3),
crop_shape=(32, 32, 3), vertical_flip=True))
# Base predictor network.
original_predictor = ibp.DNN(num_classes, layers(FLAGS.model))
predictor = original_predictor
if FLAGS.dataset == 'cifar10':
mean = (0.4914, 0.4822, 0.4465)
std = (0.2023, 0.1994, 0.2010)
predictor = ibp.add_image_normalization(original_predictor, mean, std)
if FLAGS.crown_bound_init > 0 or FLAGS.crown_bound_final > 0:
logging.info('Using CROWN-IBP loss.')
model_wrapper = ibp.crown.VerifiableModelWrapper
loss_helper = ibp.crown.create_classification_losses
else:
model_wrapper = ibp.VerifiableModelWrapper
loss_helper = ibp.create_classification_losses
predictor = model_wrapper(predictor)
# Training.
train_losses, train_loss, _ = loss_helper(
step,
data.image,
data.label,
predictor,
FLAGS.epsilon_train,
loss_weights={
'nominal': {
'init': FLAGS.nominal_xent_init,
'final': FLAGS.nominal_xent_final,
'warmup': FLAGS.verified_xent_init + FLAGS.nominal_xent_init
},
'attack': {
'init': FLAGS.attack_xent_init,
'final': FLAGS.attack_xent_final
},
'verified': {
'init': FLAGS.verified_xent_init,
'final': FLAGS.verified_xent_final,
'warmup': 0.
},
'crown_bound': {
'init': FLAGS.crown_bound_init,
'final': FLAGS.crown_bound_final,
'warmup': 0.
},
},
warmup_steps=FLAGS.warmup_steps,
rampup_steps=FLAGS.rampup_steps,
input_bounds=input_bounds)
saver = tf.train.Saver(original_predictor.get_variables())
optimizer = tf.train.AdamOptimizer(learning_rate)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(train_loss, step)
# Test using while loop.
def get_test_metrics(batch_size, attack_builder=ibp.UntargetedPGDAttack):
"""Returns the test metrics."""
num_test_batches = len(data_test[0]) // batch_size
assert len(data_test[0]) % batch_size == 0, (
'Test data is not a multiple of batch size.')
def cond(i, *unused_args):
return i < num_test_batches
def body(i, metrics):
"""Compute the sum of all metrics."""
test_data = ibp.build_dataset(data_test, batch_size=batch_size,
sequential=True)
predictor(test_data.image, override=True, is_training=False)
input_interval_bounds = ibp.IntervalBounds(
tf.maximum(test_data.image - FLAGS.epsilon, input_bounds[0]),
tf.minimum(test_data.image + FLAGS.epsilon, input_bounds[1]))
predictor.propagate_bounds(input_interval_bounds)
test_specification = ibp.ClassificationSpecification(
test_data.label, num_classes)
test_attack = attack_builder(predictor, test_specification, FLAGS.epsilon,
input_bounds=input_bounds,
optimizer_builder=ibp.UnrolledAdam)
test_losses = ibp.Losses(predictor, test_specification, test_attack)
test_losses(test_data.label)
new_metrics = []
for m, n in zip(metrics, test_losses.scalar_metrics):
new_metrics.append(m + n)
return i + 1, new_metrics
total_count = tf.constant(0, dtype=tf.int32)
total_metrics = [tf.constant(0, dtype=tf.float32)
for _ in range(len(ibp.ScalarMetrics._fields))]
total_count, total_metrics = tf.while_loop(
cond,
body,
loop_vars=[total_count, total_metrics],
back_prop=False,
parallel_iterations=1)
total_count = tf.cast(total_count, tf.float32)
test_metrics = []
for m in total_metrics:
test_metrics.append(m / total_count)
return ibp.ScalarMetrics(*test_metrics)
test_metrics = get_test_metrics(
FLAGS.batch_size, ibp.UntargetedPGDAttack)
summaries = []
for f in test_metrics._fields:
summaries.append(
tf.summary.scalar(f, getattr(test_metrics, f)))
test_summaries = tf.summary.merge(summaries)
test_writer = tf.summary.FileWriter(os.path.join(FLAGS.output_dir, 'test'))
# Run everything.
tf_config = tf.ConfigProto()
tf_config.gpu_options.allow_growth = True
with tf.train.SingularMonitoredSession(config=tf_config) as sess:
for _ in range(FLAGS.steps):
iteration, loss_value, _ = sess.run(
[step, train_losses.scalar_losses.nominal_cross_entropy, train_op])
if iteration % FLAGS.test_every_n == 0:
metric_values, summary = sess.run([test_metrics, test_summaries])
test_writer.add_summary(summary, iteration)
show_metrics(iteration, metric_values, loss_value=loss_value)
saver.save(sess._tf_sess(), # pylint: disable=protected-access
os.path.join(FLAGS.output_dir, 'model'),
global_step=FLAGS.steps - 1)
if __name__ == '__main__':
app.run(main)
| """Returns the layer specification for a given model name."""
if model_size == 'tiny':
return (
('linear', 100),
('activation', 'relu'))
elif model_size == 'small':
return (
('conv2d', (4, 4), 16, 'VALID', 2),
('activation', 'relu'),
('conv2d', (4, 4), 32, 'VALID', 1),
('activation', 'relu'),
('linear', 100),
('activation', 'relu'))
elif model_size == 'medium':
return (
('conv2d', (3, 3), 32, 'VALID', 1),
('activation', 'relu'),
('conv2d', (4, 4), 32, 'VALID', 2),
('activation', 'relu'),
('conv2d', (3, 3), 64, 'VALID', 1),
('activation', 'relu'),
('conv2d', (4, 4), 64, 'VALID', 2),
('activation', 'relu'),
('linear', 512),
('activation', 'relu'),
('linear', 512),
('activation', 'relu'))
elif model_size == 'large':
return (
('conv2d', (3, 3), 64, 'SAME', 1),
('activation', 'relu'),
('conv2d', (3, 3), 64, 'SAME', 1),
('activation', 'relu'),
('conv2d', (3, 3), 128, 'SAME', 2),
('activation', 'relu'),
('conv2d', (3, 3), 128, 'SAME', 1),
('activation', 'relu'),
('conv2d', (3, 3), 128, 'SAME', 1),
('activation', 'relu'),
('linear', 512),
('activation', 'relu'))
else:
raise ValueError('Unknown model: "{}"'.format(model_size)) | identifier_body |
train.py | # coding=utf-8
# Copyright 2019 The Interval Bound Propagation Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Trains a verifiable model on Mnist or CIFAR-10."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import app
from absl import flags
from absl import logging
import interval_bound_propagation as ibp
import tensorflow.compat.v1 as tf
FLAGS = flags.FLAGS
flags.DEFINE_enum('dataset', 'mnist', ['mnist', 'cifar10'],
'Dataset (either "mnist" or "cifar10").')
flags.DEFINE_enum('model', 'tiny', ['tiny', 'small', 'medium', 'large'],
'Model size.')
flags.DEFINE_string('output_dir', '/tmp/ibp_model', 'Output directory.')
# Options.
flags.DEFINE_integer('steps', 60001, 'Number of steps in total.')
flags.DEFINE_integer('test_every_n', 2000,
'Number of steps between testing iterations.')
flags.DEFINE_integer('warmup_steps', 2000, 'Number of warm-up steps.')
flags.DEFINE_integer('rampup_steps', 10000, 'Number of ramp-up steps.')
flags.DEFINE_integer('batch_size', 200, 'Batch size.')
flags.DEFINE_float('epsilon', .3, 'Target epsilon.')
flags.DEFINE_float('epsilon_train', .33, 'Train epsilon.')
flags.DEFINE_string('learning_rate', '1e-3,1e-4@15000,1e-5@25000',
'Learning rate schedule of the form: '
'initial_learning_rate[,learning:steps]*. E.g., "1e-3" or '
'"1e-3,1e-4@15000,1e-5@25000".')
flags.DEFINE_float('nominal_xent_init', 1.,
'Initial weight for the nominal cross-entropy.')
flags.DEFINE_float('nominal_xent_final', .5,
'Final weight for the nominal cross-entropy.')
flags.DEFINE_float('verified_xent_init', 0.,
'Initial weight for the verified cross-entropy.')
flags.DEFINE_float('verified_xent_final', .5,
'Final weight for the verified cross-entropy.')
flags.DEFINE_float('crown_bound_init', 0.,
'Initial weight for mixing the CROWN bound with the IBP '
'bound in the verified cross-entropy.')
flags.DEFINE_float('crown_bound_final', 0.,
'Final weight for mixing the CROWN bound with the IBP '
'bound in the verified cross-entropy.')
flags.DEFINE_float('attack_xent_init', 0.,
'Initial weight for the attack cross-entropy.')
flags.DEFINE_float('attack_xent_final', 0.,
'Initial weight for the attack cross-entropy.')
def show_metrics(step_value, metric_values, loss_value=None):
print('{}: {}nominal accuracy = {:.2f}%, '
'verified = {:.2f}%, attack = {:.2f}%'.format(
step_value,
'loss = {}, '.format(loss_value) if loss_value is not None else '',
metric_values.nominal_accuracy * 100.,
metric_values.verified_accuracy * 100.,
metric_values.attack_accuracy * 100.))
def layers(model_size):
"""Returns the layer specification for a given model name."""
if model_size == 'tiny':
return (
('linear', 100),
('activation', 'relu'))
elif model_size == 'small':
return (
('conv2d', (4, 4), 16, 'VALID', 2),
('activation', 'relu'),
('conv2d', (4, 4), 32, 'VALID', 1),
('activation', 'relu'),
('linear', 100),
('activation', 'relu'))
elif model_size == 'medium':
return (
('conv2d', (3, 3), 32, 'VALID', 1),
('activation', 'relu'),
('conv2d', (4, 4), 32, 'VALID', 2),
('activation', 'relu'),
('conv2d', (3, 3), 64, 'VALID', 1),
('activation', 'relu'),
('conv2d', (4, 4), 64, 'VALID', 2),
('activation', 'relu'),
('linear', 512),
('activation', 'relu'),
('linear', 512),
('activation', 'relu'))
elif model_size == 'large':
return (
('conv2d', (3, 3), 64, 'SAME', 1),
('activation', 'relu'),
('conv2d', (3, 3), 64, 'SAME', 1),
('activation', 'relu'),
('conv2d', (3, 3), 128, 'SAME', 2),
('activation', 'relu'),
('conv2d', (3, 3), 128, 'SAME', 1),
('activation', 'relu'),
('conv2d', (3, 3), 128, 'SAME', 1),
('activation', 'relu'),
('linear', 512),
('activation', 'relu'))
else:
raise ValueError('Unknown model: "{}"'.format(model_size))
def main(unused_args):
logging.info('Training IBP on %s...', FLAGS.dataset.upper())
step = tf.train.get_or_create_global_step()
# Learning rate.
learning_rate = ibp.parse_learning_rate(step, FLAGS.learning_rate)
# Dataset.
input_bounds = (0., 1.)
num_classes = 10
if FLAGS.dataset == 'mnist':
data_train, data_test = tf.keras.datasets.mnist.load_data()
else:
assert FLAGS.dataset == 'cifar10', (
'Unknown dataset "{}"'.format(FLAGS.dataset))
data_train, data_test = tf.keras.datasets.cifar10.load_data()
data_train = (data_train[0], data_train[1].flatten())
data_test = (data_test[0], data_test[1].flatten())
data = ibp.build_dataset(data_train, batch_size=FLAGS.batch_size,
sequential=False)
if FLAGS.dataset == 'cifar10':
data = data._replace(image=ibp.randomize(
data.image, (32, 32, 3), expand_shape=(40, 40, 3),
crop_shape=(32, 32, 3), vertical_flip=True))
# Base predictor network.
original_predictor = ibp.DNN(num_classes, layers(FLAGS.model))
predictor = original_predictor
if FLAGS.dataset == 'cifar10':
mean = (0.4914, 0.4822, 0.4465)
std = (0.2023, 0.1994, 0.2010)
predictor = ibp.add_image_normalization(original_predictor, mean, std)
if FLAGS.crown_bound_init > 0 or FLAGS.crown_bound_final > 0:
logging.info('Using CROWN-IBP loss.')
model_wrapper = ibp.crown.VerifiableModelWrapper
loss_helper = ibp.crown.create_classification_losses
else:
model_wrapper = ibp.VerifiableModelWrapper
loss_helper = ibp.create_classification_losses
predictor = model_wrapper(predictor)
# Training.
train_losses, train_loss, _ = loss_helper(
step,
data.image,
data.label,
predictor,
FLAGS.epsilon_train,
loss_weights={
'nominal': {
'init': FLAGS.nominal_xent_init,
'final': FLAGS.nominal_xent_final,
'warmup': FLAGS.verified_xent_init + FLAGS.nominal_xent_init
},
'attack': {
'init': FLAGS.attack_xent_init,
'final': FLAGS.attack_xent_final
},
'verified': {
'init': FLAGS.verified_xent_init,
'final': FLAGS.verified_xent_final,
'warmup': 0.
},
'crown_bound': {
'init': FLAGS.crown_bound_init,
'final': FLAGS.crown_bound_final,
'warmup': 0.
},
},
warmup_steps=FLAGS.warmup_steps,
rampup_steps=FLAGS.rampup_steps,
input_bounds=input_bounds)
saver = tf.train.Saver(original_predictor.get_variables())
optimizer = tf.train.AdamOptimizer(learning_rate)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(train_loss, step)
# Test using while loop.
def get_test_metrics(batch_size, attack_builder=ibp.UntargetedPGDAttack):
"""Returns the test metrics."""
num_test_batches = len(data_test[0]) // batch_size
assert len(data_test[0]) % batch_size == 0, (
'Test data is not a multiple of batch size.')
def cond(i, *unused_args):
return i < num_test_batches
def body(i, metrics):
"""Compute the sum of all metrics."""
test_data = ibp.build_dataset(data_test, batch_size=batch_size,
sequential=True)
predictor(test_data.image, override=True, is_training=False)
input_interval_bounds = ibp.IntervalBounds(
tf.maximum(test_data.image - FLAGS.epsilon, input_bounds[0]),
tf.minimum(test_data.image + FLAGS.epsilon, input_bounds[1]))
predictor.propagate_bounds(input_interval_bounds)
test_specification = ibp.ClassificationSpecification(
test_data.label, num_classes)
test_attack = attack_builder(predictor, test_specification, FLAGS.epsilon,
input_bounds=input_bounds,
optimizer_builder=ibp.UnrolledAdam)
test_losses = ibp.Losses(predictor, test_specification, test_attack)
test_losses(test_data.label)
new_metrics = []
for m, n in zip(metrics, test_losses.scalar_metrics):
new_metrics.append(m + n)
return i + 1, new_metrics
total_count = tf.constant(0, dtype=tf.int32)
total_metrics = [tf.constant(0, dtype=tf.float32)
for _ in range(len(ibp.ScalarMetrics._fields))]
total_count, total_metrics = tf.while_loop(
cond,
body,
loop_vars=[total_count, total_metrics],
back_prop=False,
parallel_iterations=1)
total_count = tf.cast(total_count, tf.float32)
test_metrics = []
for m in total_metrics:
test_metrics.append(m / total_count)
return ibp.ScalarMetrics(*test_metrics)
test_metrics = get_test_metrics(
FLAGS.batch_size, ibp.UntargetedPGDAttack)
summaries = []
for f in test_metrics._fields:
summaries.append(
tf.summary.scalar(f, getattr(test_metrics, f)))
test_summaries = tf.summary.merge(summaries)
test_writer = tf.summary.FileWriter(os.path.join(FLAGS.output_dir, 'test'))
# Run everything.
tf_config = tf.ConfigProto()
tf_config.gpu_options.allow_growth = True
with tf.train.SingularMonitoredSession(config=tf_config) as sess:
for _ in range(FLAGS.steps):
iteration, loss_value, _ = sess.run(
[step, train_losses.scalar_losses.nominal_cross_entropy, train_op])
if iteration % FLAGS.test_every_n == 0:
|
saver.save(sess._tf_sess(), # pylint: disable=protected-access
os.path.join(FLAGS.output_dir, 'model'),
global_step=FLAGS.steps - 1)
if __name__ == '__main__':
app.run(main)
| metric_values, summary = sess.run([test_metrics, test_summaries])
test_writer.add_summary(summary, iteration)
show_metrics(iteration, metric_values, loss_value=loss_value) | conditional_block |
train.py | # coding=utf-8
# Copyright 2019 The Interval Bound Propagation Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Trains a verifiable model on Mnist or CIFAR-10."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import app
from absl import flags
from absl import logging
import interval_bound_propagation as ibp
import tensorflow.compat.v1 as tf
FLAGS = flags.FLAGS
flags.DEFINE_enum('dataset', 'mnist', ['mnist', 'cifar10'],
'Dataset (either "mnist" or "cifar10").')
flags.DEFINE_enum('model', 'tiny', ['tiny', 'small', 'medium', 'large'],
'Model size.')
flags.DEFINE_string('output_dir', '/tmp/ibp_model', 'Output directory.')
# Options.
flags.DEFINE_integer('steps', 60001, 'Number of steps in total.')
flags.DEFINE_integer('test_every_n', 2000,
'Number of steps between testing iterations.')
flags.DEFINE_integer('warmup_steps', 2000, 'Number of warm-up steps.')
flags.DEFINE_integer('rampup_steps', 10000, 'Number of ramp-up steps.')
flags.DEFINE_integer('batch_size', 200, 'Batch size.')
flags.DEFINE_float('epsilon', .3, 'Target epsilon.')
flags.DEFINE_float('epsilon_train', .33, 'Train epsilon.')
flags.DEFINE_string('learning_rate', '1e-3,1e-4@15000,1e-5@25000',
'Learning rate schedule of the form: '
'initial_learning_rate[,learning:steps]*. E.g., "1e-3" or '
'"1e-3,1e-4@15000,1e-5@25000".')
flags.DEFINE_float('nominal_xent_init', 1.,
'Initial weight for the nominal cross-entropy.')
flags.DEFINE_float('nominal_xent_final', .5,
'Final weight for the nominal cross-entropy.')
flags.DEFINE_float('verified_xent_init', 0.,
'Initial weight for the verified cross-entropy.')
flags.DEFINE_float('verified_xent_final', .5,
'Final weight for the verified cross-entropy.')
flags.DEFINE_float('crown_bound_init', 0.,
'Initial weight for mixing the CROWN bound with the IBP '
'bound in the verified cross-entropy.')
flags.DEFINE_float('crown_bound_final', 0.,
'Final weight for mixing the CROWN bound with the IBP '
'bound in the verified cross-entropy.')
flags.DEFINE_float('attack_xent_init', 0.,
'Initial weight for the attack cross-entropy.')
flags.DEFINE_float('attack_xent_final', 0.,
'Initial weight for the attack cross-entropy.')
def show_metrics(step_value, metric_values, loss_value=None):
print('{}: {}nominal accuracy = {:.2f}%, '
'verified = {:.2f}%, attack = {:.2f}%'.format(
step_value,
'loss = {}, '.format(loss_value) if loss_value is not None else '',
metric_values.nominal_accuracy * 100.,
metric_values.verified_accuracy * 100.,
metric_values.attack_accuracy * 100.))
def layers(model_size):
"""Returns the layer specification for a given model name."""
if model_size == 'tiny':
return (
('linear', 100),
('activation', 'relu'))
elif model_size == 'small':
return (
('conv2d', (4, 4), 16, 'VALID', 2),
('activation', 'relu'),
('conv2d', (4, 4), 32, 'VALID', 1),
('activation', 'relu'),
('linear', 100),
('activation', 'relu'))
elif model_size == 'medium':
return (
('conv2d', (3, 3), 32, 'VALID', 1),
('activation', 'relu'),
('conv2d', (4, 4), 32, 'VALID', 2),
('activation', 'relu'),
('conv2d', (3, 3), 64, 'VALID', 1),
('activation', 'relu'),
('conv2d', (4, 4), 64, 'VALID', 2),
('activation', 'relu'),
('linear', 512),
('activation', 'relu'),
('linear', 512),
('activation', 'relu'))
elif model_size == 'large':
return (
('conv2d', (3, 3), 64, 'SAME', 1),
('activation', 'relu'),
('conv2d', (3, 3), 64, 'SAME', 1),
('activation', 'relu'),
('conv2d', (3, 3), 128, 'SAME', 2),
('activation', 'relu'),
('conv2d', (3, 3), 128, 'SAME', 1),
('activation', 'relu'),
('conv2d', (3, 3), 128, 'SAME', 1),
('activation', 'relu'),
('linear', 512),
('activation', 'relu'))
else:
raise ValueError('Unknown model: "{}"'.format(model_size))
def main(unused_args):
logging.info('Training IBP on %s...', FLAGS.dataset.upper())
step = tf.train.get_or_create_global_step()
# Learning rate.
learning_rate = ibp.parse_learning_rate(step, FLAGS.learning_rate)
# Dataset.
input_bounds = (0., 1.)
num_classes = 10
if FLAGS.dataset == 'mnist':
data_train, data_test = tf.keras.datasets.mnist.load_data()
else:
assert FLAGS.dataset == 'cifar10', (
'Unknown dataset "{}"'.format(FLAGS.dataset))
data_train, data_test = tf.keras.datasets.cifar10.load_data()
data_train = (data_train[0], data_train[1].flatten())
data_test = (data_test[0], data_test[1].flatten())
data = ibp.build_dataset(data_train, batch_size=FLAGS.batch_size,
sequential=False)
if FLAGS.dataset == 'cifar10':
data = data._replace(image=ibp.randomize(
data.image, (32, 32, 3), expand_shape=(40, 40, 3),
crop_shape=(32, 32, 3), vertical_flip=True))
# Base predictor network.
original_predictor = ibp.DNN(num_classes, layers(FLAGS.model))
predictor = original_predictor
if FLAGS.dataset == 'cifar10':
mean = (0.4914, 0.4822, 0.4465)
std = (0.2023, 0.1994, 0.2010)
predictor = ibp.add_image_normalization(original_predictor, mean, std)
if FLAGS.crown_bound_init > 0 or FLAGS.crown_bound_final > 0:
logging.info('Using CROWN-IBP loss.')
model_wrapper = ibp.crown.VerifiableModelWrapper
loss_helper = ibp.crown.create_classification_losses
else:
model_wrapper = ibp.VerifiableModelWrapper
loss_helper = ibp.create_classification_losses
predictor = model_wrapper(predictor)
# Training.
train_losses, train_loss, _ = loss_helper(
step,
data.image,
data.label,
predictor,
FLAGS.epsilon_train,
loss_weights={
'nominal': {
'init': FLAGS.nominal_xent_init,
'final': FLAGS.nominal_xent_final,
'warmup': FLAGS.verified_xent_init + FLAGS.nominal_xent_init
},
'attack': {
'init': FLAGS.attack_xent_init,
'final': FLAGS.attack_xent_final
},
'verified': {
'init': FLAGS.verified_xent_init,
'final': FLAGS.verified_xent_final,
'warmup': 0.
},
'crown_bound': {
'init': FLAGS.crown_bound_init,
'final': FLAGS.crown_bound_final,
'warmup': 0.
},
},
warmup_steps=FLAGS.warmup_steps,
rampup_steps=FLAGS.rampup_steps,
input_bounds=input_bounds)
saver = tf.train.Saver(original_predictor.get_variables())
optimizer = tf.train.AdamOptimizer(learning_rate)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(train_loss, step)
# Test using while loop.
def get_test_metrics(batch_size, attack_builder=ibp.UntargetedPGDAttack):
"""Returns the test metrics."""
num_test_batches = len(data_test[0]) // batch_size
assert len(data_test[0]) % batch_size == 0, (
'Test data is not a multiple of batch size.')
def cond(i, *unused_args):
return i < num_test_batches
def body(i, metrics):
"""Compute the sum of all metrics."""
test_data = ibp.build_dataset(data_test, batch_size=batch_size,
sequential=True)
predictor(test_data.image, override=True, is_training=False)
input_interval_bounds = ibp.IntervalBounds(
tf.maximum(test_data.image - FLAGS.epsilon, input_bounds[0]),
tf.minimum(test_data.image + FLAGS.epsilon, input_bounds[1]))
predictor.propagate_bounds(input_interval_bounds)
test_specification = ibp.ClassificationSpecification(
test_data.label, num_classes)
test_attack = attack_builder(predictor, test_specification, FLAGS.epsilon,
input_bounds=input_bounds,
optimizer_builder=ibp.UnrolledAdam)
test_losses = ibp.Losses(predictor, test_specification, test_attack)
test_losses(test_data.label)
new_metrics = []
for m, n in zip(metrics, test_losses.scalar_metrics):
new_metrics.append(m + n) | total_metrics = [tf.constant(0, dtype=tf.float32)
for _ in range(len(ibp.ScalarMetrics._fields))]
total_count, total_metrics = tf.while_loop(
cond,
body,
loop_vars=[total_count, total_metrics],
back_prop=False,
parallel_iterations=1)
total_count = tf.cast(total_count, tf.float32)
test_metrics = []
for m in total_metrics:
test_metrics.append(m / total_count)
return ibp.ScalarMetrics(*test_metrics)
test_metrics = get_test_metrics(
FLAGS.batch_size, ibp.UntargetedPGDAttack)
summaries = []
for f in test_metrics._fields:
summaries.append(
tf.summary.scalar(f, getattr(test_metrics, f)))
test_summaries = tf.summary.merge(summaries)
test_writer = tf.summary.FileWriter(os.path.join(FLAGS.output_dir, 'test'))
# Run everything.
tf_config = tf.ConfigProto()
tf_config.gpu_options.allow_growth = True
with tf.train.SingularMonitoredSession(config=tf_config) as sess:
for _ in range(FLAGS.steps):
iteration, loss_value, _ = sess.run(
[step, train_losses.scalar_losses.nominal_cross_entropy, train_op])
if iteration % FLAGS.test_every_n == 0:
metric_values, summary = sess.run([test_metrics, test_summaries])
test_writer.add_summary(summary, iteration)
show_metrics(iteration, metric_values, loss_value=loss_value)
saver.save(sess._tf_sess(), # pylint: disable=protected-access
os.path.join(FLAGS.output_dir, 'model'),
global_step=FLAGS.steps - 1)
if __name__ == '__main__':
app.run(main) | return i + 1, new_metrics
total_count = tf.constant(0, dtype=tf.int32) | random_line_split |
train.py | # coding=utf-8
# Copyright 2019 The Interval Bound Propagation Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Trains a verifiable model on Mnist or CIFAR-10."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import app
from absl import flags
from absl import logging
import interval_bound_propagation as ibp
import tensorflow.compat.v1 as tf
FLAGS = flags.FLAGS
flags.DEFINE_enum('dataset', 'mnist', ['mnist', 'cifar10'],
'Dataset (either "mnist" or "cifar10").')
flags.DEFINE_enum('model', 'tiny', ['tiny', 'small', 'medium', 'large'],
'Model size.')
flags.DEFINE_string('output_dir', '/tmp/ibp_model', 'Output directory.')
# Options.
flags.DEFINE_integer('steps', 60001, 'Number of steps in total.')
flags.DEFINE_integer('test_every_n', 2000,
'Number of steps between testing iterations.')
flags.DEFINE_integer('warmup_steps', 2000, 'Number of warm-up steps.')
flags.DEFINE_integer('rampup_steps', 10000, 'Number of ramp-up steps.')
flags.DEFINE_integer('batch_size', 200, 'Batch size.')
flags.DEFINE_float('epsilon', .3, 'Target epsilon.')
flags.DEFINE_float('epsilon_train', .33, 'Train epsilon.')
flags.DEFINE_string('learning_rate', '1e-3,1e-4@15000,1e-5@25000',
'Learning rate schedule of the form: '
'initial_learning_rate[,learning:steps]*. E.g., "1e-3" or '
'"1e-3,1e-4@15000,1e-5@25000".')
flags.DEFINE_float('nominal_xent_init', 1.,
'Initial weight for the nominal cross-entropy.')
flags.DEFINE_float('nominal_xent_final', .5,
'Final weight for the nominal cross-entropy.')
flags.DEFINE_float('verified_xent_init', 0.,
'Initial weight for the verified cross-entropy.')
flags.DEFINE_float('verified_xent_final', .5,
'Final weight for the verified cross-entropy.')
flags.DEFINE_float('crown_bound_init', 0.,
'Initial weight for mixing the CROWN bound with the IBP '
'bound in the verified cross-entropy.')
flags.DEFINE_float('crown_bound_final', 0.,
'Final weight for mixing the CROWN bound with the IBP '
'bound in the verified cross-entropy.')
flags.DEFINE_float('attack_xent_init', 0.,
'Initial weight for the attack cross-entropy.')
flags.DEFINE_float('attack_xent_final', 0.,
'Initial weight for the attack cross-entropy.')
def show_metrics(step_value, metric_values, loss_value=None):
print('{}: {}nominal accuracy = {:.2f}%, '
'verified = {:.2f}%, attack = {:.2f}%'.format(
step_value,
'loss = {}, '.format(loss_value) if loss_value is not None else '',
metric_values.nominal_accuracy * 100.,
metric_values.verified_accuracy * 100.,
metric_values.attack_accuracy * 100.))
def layers(model_size):
"""Returns the layer specification for a given model name."""
if model_size == 'tiny':
return (
('linear', 100),
('activation', 'relu'))
elif model_size == 'small':
return (
('conv2d', (4, 4), 16, 'VALID', 2),
('activation', 'relu'),
('conv2d', (4, 4), 32, 'VALID', 1),
('activation', 'relu'),
('linear', 100),
('activation', 'relu'))
elif model_size == 'medium':
return (
('conv2d', (3, 3), 32, 'VALID', 1),
('activation', 'relu'),
('conv2d', (4, 4), 32, 'VALID', 2),
('activation', 'relu'),
('conv2d', (3, 3), 64, 'VALID', 1),
('activation', 'relu'),
('conv2d', (4, 4), 64, 'VALID', 2),
('activation', 'relu'),
('linear', 512),
('activation', 'relu'),
('linear', 512),
('activation', 'relu'))
elif model_size == 'large':
return (
('conv2d', (3, 3), 64, 'SAME', 1),
('activation', 'relu'),
('conv2d', (3, 3), 64, 'SAME', 1),
('activation', 'relu'),
('conv2d', (3, 3), 128, 'SAME', 2),
('activation', 'relu'),
('conv2d', (3, 3), 128, 'SAME', 1),
('activation', 'relu'),
('conv2d', (3, 3), 128, 'SAME', 1),
('activation', 'relu'),
('linear', 512),
('activation', 'relu'))
else:
raise ValueError('Unknown model: "{}"'.format(model_size))
def main(unused_args):
logging.info('Training IBP on %s...', FLAGS.dataset.upper())
step = tf.train.get_or_create_global_step()
# Learning rate.
learning_rate = ibp.parse_learning_rate(step, FLAGS.learning_rate)
# Dataset.
input_bounds = (0., 1.)
num_classes = 10
if FLAGS.dataset == 'mnist':
data_train, data_test = tf.keras.datasets.mnist.load_data()
else:
assert FLAGS.dataset == 'cifar10', (
'Unknown dataset "{}"'.format(FLAGS.dataset))
data_train, data_test = tf.keras.datasets.cifar10.load_data()
data_train = (data_train[0], data_train[1].flatten())
data_test = (data_test[0], data_test[1].flatten())
data = ibp.build_dataset(data_train, batch_size=FLAGS.batch_size,
sequential=False)
if FLAGS.dataset == 'cifar10':
data = data._replace(image=ibp.randomize(
data.image, (32, 32, 3), expand_shape=(40, 40, 3),
crop_shape=(32, 32, 3), vertical_flip=True))
# Base predictor network.
original_predictor = ibp.DNN(num_classes, layers(FLAGS.model))
predictor = original_predictor
if FLAGS.dataset == 'cifar10':
mean = (0.4914, 0.4822, 0.4465)
std = (0.2023, 0.1994, 0.2010)
predictor = ibp.add_image_normalization(original_predictor, mean, std)
if FLAGS.crown_bound_init > 0 or FLAGS.crown_bound_final > 0:
logging.info('Using CROWN-IBP loss.')
model_wrapper = ibp.crown.VerifiableModelWrapper
loss_helper = ibp.crown.create_classification_losses
else:
model_wrapper = ibp.VerifiableModelWrapper
loss_helper = ibp.create_classification_losses
predictor = model_wrapper(predictor)
# Training.
train_losses, train_loss, _ = loss_helper(
step,
data.image,
data.label,
predictor,
FLAGS.epsilon_train,
loss_weights={
'nominal': {
'init': FLAGS.nominal_xent_init,
'final': FLAGS.nominal_xent_final,
'warmup': FLAGS.verified_xent_init + FLAGS.nominal_xent_init
},
'attack': {
'init': FLAGS.attack_xent_init,
'final': FLAGS.attack_xent_final
},
'verified': {
'init': FLAGS.verified_xent_init,
'final': FLAGS.verified_xent_final,
'warmup': 0.
},
'crown_bound': {
'init': FLAGS.crown_bound_init,
'final': FLAGS.crown_bound_final,
'warmup': 0.
},
},
warmup_steps=FLAGS.warmup_steps,
rampup_steps=FLAGS.rampup_steps,
input_bounds=input_bounds)
saver = tf.train.Saver(original_predictor.get_variables())
optimizer = tf.train.AdamOptimizer(learning_rate)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_op = optimizer.minimize(train_loss, step)
# Test using while loop.
def get_test_metrics(batch_size, attack_builder=ibp.UntargetedPGDAttack):
"""Returns the test metrics."""
num_test_batches = len(data_test[0]) // batch_size
assert len(data_test[0]) % batch_size == 0, (
'Test data is not a multiple of batch size.')
def cond(i, *unused_args):
return i < num_test_batches
def | (i, metrics):
"""Compute the sum of all metrics."""
test_data = ibp.build_dataset(data_test, batch_size=batch_size,
sequential=True)
predictor(test_data.image, override=True, is_training=False)
input_interval_bounds = ibp.IntervalBounds(
tf.maximum(test_data.image - FLAGS.epsilon, input_bounds[0]),
tf.minimum(test_data.image + FLAGS.epsilon, input_bounds[1]))
predictor.propagate_bounds(input_interval_bounds)
test_specification = ibp.ClassificationSpecification(
test_data.label, num_classes)
test_attack = attack_builder(predictor, test_specification, FLAGS.epsilon,
input_bounds=input_bounds,
optimizer_builder=ibp.UnrolledAdam)
test_losses = ibp.Losses(predictor, test_specification, test_attack)
test_losses(test_data.label)
new_metrics = []
for m, n in zip(metrics, test_losses.scalar_metrics):
new_metrics.append(m + n)
return i + 1, new_metrics
total_count = tf.constant(0, dtype=tf.int32)
total_metrics = [tf.constant(0, dtype=tf.float32)
for _ in range(len(ibp.ScalarMetrics._fields))]
total_count, total_metrics = tf.while_loop(
cond,
body,
loop_vars=[total_count, total_metrics],
back_prop=False,
parallel_iterations=1)
total_count = tf.cast(total_count, tf.float32)
test_metrics = []
for m in total_metrics:
test_metrics.append(m / total_count)
return ibp.ScalarMetrics(*test_metrics)
test_metrics = get_test_metrics(
FLAGS.batch_size, ibp.UntargetedPGDAttack)
summaries = []
for f in test_metrics._fields:
summaries.append(
tf.summary.scalar(f, getattr(test_metrics, f)))
test_summaries = tf.summary.merge(summaries)
test_writer = tf.summary.FileWriter(os.path.join(FLAGS.output_dir, 'test'))
# Run everything.
tf_config = tf.ConfigProto()
tf_config.gpu_options.allow_growth = True
with tf.train.SingularMonitoredSession(config=tf_config) as sess:
for _ in range(FLAGS.steps):
iteration, loss_value, _ = sess.run(
[step, train_losses.scalar_losses.nominal_cross_entropy, train_op])
if iteration % FLAGS.test_every_n == 0:
metric_values, summary = sess.run([test_metrics, test_summaries])
test_writer.add_summary(summary, iteration)
show_metrics(iteration, metric_values, loss_value=loss_value)
saver.save(sess._tf_sess(), # pylint: disable=protected-access
os.path.join(FLAGS.output_dir, 'model'),
global_step=FLAGS.steps - 1)
if __name__ == '__main__':
app.run(main)
| body | identifier_name |
lib.rs | //! This crate provides the basic environments for Kailua.
//!
//! * Location types ([`Unit`](./struct.Unit.html), [`Pos`](./struct.Pos.html),
//! [`Span`](./struct.Span.html)) and a location-bundled container | //!
//! * The resolver for locations
//! ([`kailua_env::source`](./source/index.html))
//!
//! * An arbitrary mapping from location ranges to values
//! ([`kailua_env::spanmap`](./spanmap/index.html))
mod loc;
pub mod scope;
pub mod source;
pub mod spanmap;
pub use loc::{Unit, Pos, Span, Spanned, WithLoc};
pub use scope::{Scope, ScopedId, ScopeMap};
pub use source::{Source, SourceFile, SourceSlice, SourceData};
pub use spanmap::SpanMap; | //! ([`Spanned`](./struct.Spanned.html))
//!
//! * Scope identifiers and a location-to-scope map
//! ([`kailua_env::scope`](./scope/index.html)) | random_line_split |
template.py | from boto.resultset import ResultSet
class Template: | def startElement(self, name, attrs, connection):
if name == "Parameters":
self.template_parameters = ResultSet([('member', TemplateParameter)])
return self.template_parameters
else:
return None
def endElement(self, name, value, connection):
if name == "Description":
self.description = value
else:
setattr(self, name, value)
class TemplateParameter:
def __init__(self, parent):
self.parent = parent
self.default_value = None
self.description = None
self.no_echo = None
self.parameter_key = None
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == "DefaultValue":
self.default_value = value
elif name == "Description":
self.description = value
elif name == "NoEcho":
self.no_echo = bool(value)
elif name == "ParameterKey":
self.parameter_key = value
else:
setattr(self, name, value) | def __init__(self, connection=None):
self.connection = connection
self.description = None
self.template_parameters = None
| random_line_split |
template.py | from boto.resultset import ResultSet
class Template:
def __init__(self, connection=None):
self.connection = connection
self.description = None
self.template_parameters = None
def startElement(self, name, attrs, connection):
if name == "Parameters":
self.template_parameters = ResultSet([('member', TemplateParameter)])
return self.template_parameters
else:
return None
def endElement(self, name, value, connection):
if name == "Description":
self.description = value
else:
|
class TemplateParameter:
def __init__(self, parent):
self.parent = parent
self.default_value = None
self.description = None
self.no_echo = None
self.parameter_key = None
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == "DefaultValue":
self.default_value = value
elif name == "Description":
self.description = value
elif name == "NoEcho":
self.no_echo = bool(value)
elif name == "ParameterKey":
self.parameter_key = value
else:
setattr(self, name, value)
| setattr(self, name, value) | conditional_block |
template.py | from boto.resultset import ResultSet
class Template:
def | (self, connection=None):
self.connection = connection
self.description = None
self.template_parameters = None
def startElement(self, name, attrs, connection):
if name == "Parameters":
self.template_parameters = ResultSet([('member', TemplateParameter)])
return self.template_parameters
else:
return None
def endElement(self, name, value, connection):
if name == "Description":
self.description = value
else:
setattr(self, name, value)
class TemplateParameter:
def __init__(self, parent):
self.parent = parent
self.default_value = None
self.description = None
self.no_echo = None
self.parameter_key = None
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == "DefaultValue":
self.default_value = value
elif name == "Description":
self.description = value
elif name == "NoEcho":
self.no_echo = bool(value)
elif name == "ParameterKey":
self.parameter_key = value
else:
setattr(self, name, value)
| __init__ | identifier_name |
template.py | from boto.resultset import ResultSet
class Template:
|
class TemplateParameter:
def __init__(self, parent):
self.parent = parent
self.default_value = None
self.description = None
self.no_echo = None
self.parameter_key = None
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
if name == "DefaultValue":
self.default_value = value
elif name == "Description":
self.description = value
elif name == "NoEcho":
self.no_echo = bool(value)
elif name == "ParameterKey":
self.parameter_key = value
else:
setattr(self, name, value)
| def __init__(self, connection=None):
self.connection = connection
self.description = None
self.template_parameters = None
def startElement(self, name, attrs, connection):
if name == "Parameters":
self.template_parameters = ResultSet([('member', TemplateParameter)])
return self.template_parameters
else:
return None
def endElement(self, name, value, connection):
if name == "Description":
self.description = value
else:
setattr(self, name, value) | identifier_body |
extensions.rs | use serde::{Deserialize, Serialize, Serializer};
use std::convert::From;
use std::fmt;
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
/// Represents all the possible [CloudEvents extension](https://github.com/cloudevents/spec/blob/master/spec.md#extension-context-attributes) values
pub enum ExtensionValue {
/// Represents a [`String`] value.
String(String),
/// Represents a [`bool`] value.
Boolean(bool),
/// Represents an integer [`i64`] value.
Integer(i64),
}
impl From<&str> for ExtensionValue {
fn from(s: &str) -> Self {
ExtensionValue::String(String::from(s))
}
}
impl From<String> for ExtensionValue {
fn from(s: String) -> Self |
}
impl From<bool> for ExtensionValue {
fn from(s: bool) -> Self {
ExtensionValue::Boolean(s)
}
}
impl From<i64> for ExtensionValue {
fn from(s: i64) -> Self {
ExtensionValue::Integer(s)
}
}
impl ExtensionValue {
pub fn from_string<S>(s: S) -> Self
where
S: Into<String>,
{
ExtensionValue::from(s.into())
}
pub fn from_i64<S>(s: S) -> Self
where
S: Into<i64>,
{
ExtensionValue::from(s.into())
}
pub fn from_bool<S>(s: S) -> Self
where
S: Into<bool>,
{
ExtensionValue::from(s.into())
}
}
impl fmt::Display for ExtensionValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ExtensionValue::String(s) => f.write_str(s),
ExtensionValue::Boolean(b) => f.serialize_bool(*b),
ExtensionValue::Integer(i) => f.serialize_i64(*i),
}
}
}
| {
ExtensionValue::String(s)
} | identifier_body |
extensions.rs | use serde::{Deserialize, Serialize, Serializer};
use std::convert::From;
use std::fmt;
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
/// Represents all the possible [CloudEvents extension](https://github.com/cloudevents/spec/blob/master/spec.md#extension-context-attributes) values
pub enum ExtensionValue {
/// Represents a [`String`] value.
String(String),
/// Represents a [`bool`] value.
Boolean(bool),
/// Represents an integer [`i64`] value.
Integer(i64),
}
impl From<&str> for ExtensionValue {
fn from(s: &str) -> Self {
ExtensionValue::String(String::from(s))
}
}
impl From<String> for ExtensionValue {
fn | (s: String) -> Self {
ExtensionValue::String(s)
}
}
impl From<bool> for ExtensionValue {
fn from(s: bool) -> Self {
ExtensionValue::Boolean(s)
}
}
impl From<i64> for ExtensionValue {
fn from(s: i64) -> Self {
ExtensionValue::Integer(s)
}
}
impl ExtensionValue {
pub fn from_string<S>(s: S) -> Self
where
S: Into<String>,
{
ExtensionValue::from(s.into())
}
pub fn from_i64<S>(s: S) -> Self
where
S: Into<i64>,
{
ExtensionValue::from(s.into())
}
pub fn from_bool<S>(s: S) -> Self
where
S: Into<bool>,
{
ExtensionValue::from(s.into())
}
}
impl fmt::Display for ExtensionValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ExtensionValue::String(s) => f.write_str(s),
ExtensionValue::Boolean(b) => f.serialize_bool(*b),
ExtensionValue::Integer(i) => f.serialize_i64(*i),
}
}
}
| from | identifier_name |
extensions.rs | use std::convert::From;
use std::fmt;
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
/// Represents all the possible [CloudEvents extension](https://github.com/cloudevents/spec/blob/master/spec.md#extension-context-attributes) values
pub enum ExtensionValue {
/// Represents a [`String`] value.
String(String),
/// Represents a [`bool`] value.
Boolean(bool),
/// Represents an integer [`i64`] value.
Integer(i64),
}
impl From<&str> for ExtensionValue {
fn from(s: &str) -> Self {
ExtensionValue::String(String::from(s))
}
}
impl From<String> for ExtensionValue {
fn from(s: String) -> Self {
ExtensionValue::String(s)
}
}
impl From<bool> for ExtensionValue {
fn from(s: bool) -> Self {
ExtensionValue::Boolean(s)
}
}
impl From<i64> for ExtensionValue {
fn from(s: i64) -> Self {
ExtensionValue::Integer(s)
}
}
impl ExtensionValue {
pub fn from_string<S>(s: S) -> Self
where
S: Into<String>,
{
ExtensionValue::from(s.into())
}
pub fn from_i64<S>(s: S) -> Self
where
S: Into<i64>,
{
ExtensionValue::from(s.into())
}
pub fn from_bool<S>(s: S) -> Self
where
S: Into<bool>,
{
ExtensionValue::from(s.into())
}
}
impl fmt::Display for ExtensionValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ExtensionValue::String(s) => f.write_str(s),
ExtensionValue::Boolean(b) => f.serialize_bool(*b),
ExtensionValue::Integer(i) => f.serialize_i64(*i),
}
}
} | use serde::{Deserialize, Serialize, Serializer}; | random_line_split | |
Main.spec.js | describe( 'MainController', function() {
var MainCtrl, $location, $httpBackend, $scope, MapService, state, queryService;
beforeEach( module( 'SolrHeatmapApp' ) );
beforeEach( inject( function( $controller, _$location_, $rootScope, _$httpBackend_, _Map_, _$state_, _queryService_) {
$location = _$location_;
$httpBackend = _$httpBackend_;
$scope = $rootScope.$new();
MapService = _Map_;
state = _$state_;
queryService = _queryService_;
MainCtrl = $controller( 'MainController', { $scope: $scope });
}));
describe('#response', function() {
describe('without a config', function() {
it( 'throws error', function() {
expect(MainCtrl.response).toThrowError('Could not find the mapConfig');
});
});
describe('with a config', function() {
var mapServiceSpy, setupSpy;
beforeEach(function() {
mapServiceSpy = spyOn(MapService, 'init');
setupSpy = spyOn(MainCtrl, 'setupEvents');
});
it( 'calls MapService init', function() {
MainCtrl.response({data: {mapConfig: { view: { projection: 'EPSG:4326'}}}});
expect(mapServiceSpy).toHaveBeenCalled();
});
describe('with a geo state', function() {
var serviceSpy;
beforeEach(function() { | it( 'calls MapService getExtentForProjectionFromQuery', function() {
MainCtrl.response({data: {mapConfig: { view: { projection: 'EPSG:4326'}}}});
expect(serviceSpy).toHaveBeenCalled();
});
});
});
});
describe('#badResponse', function() {
it( 'throws error', function() {
expect(MainCtrl.badResponse).toThrowError('Error while loading the config.json');
});
});
}); | serviceSpy = spyOn(queryService, 'getExtentForProjectionFromQuery');
spyOn(MapService, 'calculateFullScreenExtentFromBoundingBox');
MainCtrl.$state = { geo: '[1,1 TO 1,1]'};
}); | random_line_split |
options.js | 'use strict'
const defaultAPIURL = 'https://api.runmycode.online/run'
const $ = s => document.querySelector(s)
const $$ = s => document.querySelectorAll(s)
const editBtn = $('#edit')
const error = $('#error')
const apiUrl = $('#api-url')
const apiKey = $('#api-key')
const saveBtn = $('#save')
const inputs = Array.from($$('input'))
const toggleInputs = () => {
inputs.forEach((el) => {
if (el.type === 'button') el.disabled = !el.disabled
else if (el.type === 'text') {
el.getAttribute('readonly') ? el.removeAttribute('readonly') : el.setAttribute('readonly', 'readonly')
}
})
}
const enableEdit = () => {
saveBtn.value = 'Save'
toggleInputs()
}
const saveOptions = (e) => {
if (apiUrl.value === '') apiUrl.value = defaultAPIURL
error.style.display = 'block'
if (apiUrl.value !== defaultAPIURL && apiUrl.value.indexOf('.amazonaws.com') === -1) {
error.textContent = `Only ${defaultAPIURL} and AWS API Gateway URLs are supported as API URL`
return
} else if (!apiKey.value && apiUrl.value === defaultAPIURL) |
error.style.display = 'none'
browser.storage.local.set({
'apiUrl': apiUrl.value,
'apiKey': apiKey.value
})
saveBtn.value = 'Saved'
if (e) toggleInputs() // toggle inputs only if save from btn click
}
const restoreOptions = () => {
const getApiUrl = browser.storage.local.get('apiUrl')
const getApiKey = browser.storage.local.get('apiKey')
Promise.all([getApiUrl, getApiKey])
.then((result) => {
apiUrl.value = result[0]['apiUrl'] || defaultAPIURL
apiKey.value = result[1]['apiKey'] || ''
saveOptions()
})
.catch((error) => {
console.log('Error: ', error)
})
}
document.addEventListener('DOMContentLoaded', restoreOptions)
saveBtn.addEventListener('click', saveOptions)
editBtn.addEventListener('click', enableEdit)
| {
error.textContent = 'Key cannot be empty for https://api.runmycode.online/run'
return
// key may be not required for custom RunMyCode deployment
} | conditional_block |
options.js | 'use strict'
const defaultAPIURL = 'https://api.runmycode.online/run'
const $ = s => document.querySelector(s)
const $$ = s => document.querySelectorAll(s)
const editBtn = $('#edit')
const error = $('#error')
const apiUrl = $('#api-url')
const apiKey = $('#api-key')
const saveBtn = $('#save')
const inputs = Array.from($$('input'))
const toggleInputs = () => {
inputs.forEach((el) => {
if (el.type === 'button') el.disabled = !el.disabled
else if (el.type === 'text') {
el.getAttribute('readonly') ? el.removeAttribute('readonly') : el.setAttribute('readonly', 'readonly')
}
}) | }
const saveOptions = (e) => {
if (apiUrl.value === '') apiUrl.value = defaultAPIURL
error.style.display = 'block'
if (apiUrl.value !== defaultAPIURL && apiUrl.value.indexOf('.amazonaws.com') === -1) {
error.textContent = `Only ${defaultAPIURL} and AWS API Gateway URLs are supported as API URL`
return
} else if (!apiKey.value && apiUrl.value === defaultAPIURL) {
error.textContent = 'Key cannot be empty for https://api.runmycode.online/run'
return
// key may be not required for custom RunMyCode deployment
}
error.style.display = 'none'
browser.storage.local.set({
'apiUrl': apiUrl.value,
'apiKey': apiKey.value
})
saveBtn.value = 'Saved'
if (e) toggleInputs() // toggle inputs only if save from btn click
}
const restoreOptions = () => {
const getApiUrl = browser.storage.local.get('apiUrl')
const getApiKey = browser.storage.local.get('apiKey')
Promise.all([getApiUrl, getApiKey])
.then((result) => {
apiUrl.value = result[0]['apiUrl'] || defaultAPIURL
apiKey.value = result[1]['apiKey'] || ''
saveOptions()
})
.catch((error) => {
console.log('Error: ', error)
})
}
document.addEventListener('DOMContentLoaded', restoreOptions)
saveBtn.addEventListener('click', saveOptions)
editBtn.addEventListener('click', enableEdit) | }
const enableEdit = () => {
saveBtn.value = 'Save'
toggleInputs() | random_line_split |
issue-7867.rs | // 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.
enum A { B, C }
mod foo { pub fn bar() | }
fn main() {
match (true, false) {
A::B => (), //~ ERROR expected `(bool, bool)`, found `A` (expected tuple, found enum A)
_ => ()
}
match &Some(42i) {
Some(x) => (), //~ ERROR expected `&core::option::Option<int>`,
// found `core::option::Option<_>`
None => () //~ ERROR expected `&core::option::Option<int>`,
// found `core::option::Option<_>`
}
}
| {} | identifier_body |
issue-7867.rs | // 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.
enum A { B, C }
mod foo { pub fn | () {} }
fn main() {
match (true, false) {
A::B => (), //~ ERROR expected `(bool, bool)`, found `A` (expected tuple, found enum A)
_ => ()
}
match &Some(42i) {
Some(x) => (), //~ ERROR expected `&core::option::Option<int>`,
// found `core::option::Option<_>`
None => () //~ ERROR expected `&core::option::Option<int>`,
// found `core::option::Option<_>`
}
}
| bar | identifier_name |
issue-7867.rs | // 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.
| match (true, false) {
A::B => (), //~ ERROR expected `(bool, bool)`, found `A` (expected tuple, found enum A)
_ => ()
}
match &Some(42i) {
Some(x) => (), //~ ERROR expected `&core::option::Option<int>`,
// found `core::option::Option<_>`
None => () //~ ERROR expected `&core::option::Option<int>`,
// found `core::option::Option<_>`
}
} | enum A { B, C }
mod foo { pub fn bar() {} }
fn main() { | random_line_split |
file.component.ts | import {
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges,
} from "@angular/core";
import { Dataset, Job, Tool } from "chipster-js-common";
import * as _ from "lodash";
import { Subject } from "rxjs";
import { mergeMap, takeUntil } from "rxjs/operators";
import { RestErrorService } from "../../../../../core/errorhandler/rest-error.service";
import { SessionData } from "../../../../../model/session/session-data";
import { DialogModalService } from "../../dialogmodal/dialogmodal.service";
import { GetSessionDataService } from "../../get-session-data.service";
import { SelectionHandlerService } from "../../selection-handler.service";
import { SelectionService } from "../../selection.service";
import { SessionDataService } from "../../session-data.service";
import { SessionEventService } from "../../session-event.service";
import { DatasetModalService } from "../datasetmodal.service";
@Component({
selector: "ch-file",
templateUrl: "./file.component.html",
styleUrls: ["./file.component.less"],
})
export class FileComponent implements OnInit, OnChanges, OnDestroy {
@Input()
dataset: Dataset;
@Input()
private jobs: Map<string, Job>;
@Input()
sessionData: SessionData;
@Input()
tools: Tool[];
@Output() doScrollFix = new EventEmitter();
datasetName: string;
private unsubscribe: Subject<any> = new Subject();
constructor(
public selectionService: SelectionService, // used in template
private sessionDataService: SessionDataService,
private datasetModalService: DatasetModalService,
private dialogModalService: DialogModalService,
private restErrorService: RestErrorService,
private sessionEventService: SessionEventService,
private getSessionDataService: GetSessionDataService,
private selectionHandlerService: SelectionHandlerService,
private changeDetectorRef: ChangeDetectorRef
) {}
ngOnChanges(changes: SimpleChanges): void {
this.datasetName = this.dataset.name;
}
ngOnInit(): void {
// subscribe to selected dataset content changes, needed for getting new file name after Rename
this.sessionEventService
.getSelectedDatasetsContentsUpdatedStream()
.pipe(takeUntil(this.unsubscribe))
.subscribe({
next: (datasetId) => {
if (datasetId === this.dataset?.datasetId) |
},
});
}
renameDataset() {
const dataset = _.clone(this.dataset);
this.dialogModalService
.openStringModal("Rename file", "File name", dataset.name, "Rename")
.pipe(
mergeMap((name) => {
dataset.name = name;
return this.sessionDataService.updateDataset(dataset);
})
)
.subscribe({
error: (err) => this.restErrorService.showError("Rename file failed", err),
});
}
deleteDatasets() {
this.sessionDataService.deleteDatasetsLater(this.selectionService.selectedDatasets);
}
exportDatasets() {
this.sessionDataService.exportDatasets([this.dataset]);
}
showHistory() {
this.datasetModalService.openDatasetHistoryModal(this.dataset, this.sessionData, this.tools);
}
wrangleDataset() {
this.datasetModalService.openWrangleModal(this.dataset, this.sessionData);
}
defineDatasetGroups() {
this.datasetModalService.openGroupsModal(this.selectionService.selectedDatasets, this.sessionData);
}
selectChildren() {
const children = this.getSessionDataService.getChildren(this.selectionService.selectedDatasets);
this.selectionHandlerService.setDatasetSelection(children);
}
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}
}
| {
this.datasetName = this.sessionData.datasetsMap.get(this.dataset.datasetId)?.name;
} | conditional_block |
file.component.ts | import {
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges,
} from "@angular/core";
import { Dataset, Job, Tool } from "chipster-js-common";
import * as _ from "lodash";
import { Subject } from "rxjs";
import { mergeMap, takeUntil } from "rxjs/operators";
import { RestErrorService } from "../../../../../core/errorhandler/rest-error.service";
import { SessionData } from "../../../../../model/session/session-data";
import { DialogModalService } from "../../dialogmodal/dialogmodal.service";
import { GetSessionDataService } from "../../get-session-data.service";
import { SelectionHandlerService } from "../../selection-handler.service";
import { SelectionService } from "../../selection.service";
import { SessionDataService } from "../../session-data.service";
import { SessionEventService } from "../../session-event.service";
import { DatasetModalService } from "../datasetmodal.service";
@Component({
selector: "ch-file",
templateUrl: "./file.component.html",
styleUrls: ["./file.component.less"],
})
export class FileComponent implements OnInit, OnChanges, OnDestroy {
@Input()
dataset: Dataset;
@Input()
private jobs: Map<string, Job>;
@Input()
sessionData: SessionData;
@Input()
tools: Tool[];
@Output() doScrollFix = new EventEmitter();
datasetName: string;
private unsubscribe: Subject<any> = new Subject();
constructor(
public selectionService: SelectionService, // used in template
private sessionDataService: SessionDataService,
private datasetModalService: DatasetModalService,
private dialogModalService: DialogModalService,
private restErrorService: RestErrorService,
private sessionEventService: SessionEventService,
private getSessionDataService: GetSessionDataService,
private selectionHandlerService: SelectionHandlerService,
private changeDetectorRef: ChangeDetectorRef
) {}
ngOnChanges(changes: SimpleChanges): void {
this.datasetName = this.dataset.name;
}
ngOnInit(): void {
// subscribe to selected dataset content changes, needed for getting new file name after Rename
this.sessionEventService
.getSelectedDatasetsContentsUpdatedStream()
.pipe(takeUntil(this.unsubscribe))
.subscribe({
next: (datasetId) => {
if (datasetId === this.dataset?.datasetId) {
this.datasetName = this.sessionData.datasetsMap.get(this.dataset.datasetId)?.name;
}
},
});
}
renameDataset() {
const dataset = _.clone(this.dataset);
this.dialogModalService
.openStringModal("Rename file", "File name", dataset.name, "Rename")
.pipe(
mergeMap((name) => {
dataset.name = name;
return this.sessionDataService.updateDataset(dataset);
})
)
.subscribe({
error: (err) => this.restErrorService.showError("Rename file failed", err),
});
}
deleteDatasets() {
this.sessionDataService.deleteDatasetsLater(this.selectionService.selectedDatasets);
}
exportDatasets() {
this.sessionDataService.exportDatasets([this.dataset]);
}
showHistory() {
this.datasetModalService.openDatasetHistoryModal(this.dataset, this.sessionData, this.tools);
}
wrangleDataset() |
defineDatasetGroups() {
this.datasetModalService.openGroupsModal(this.selectionService.selectedDatasets, this.sessionData);
}
selectChildren() {
const children = this.getSessionDataService.getChildren(this.selectionService.selectedDatasets);
this.selectionHandlerService.setDatasetSelection(children);
}
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}
}
| {
this.datasetModalService.openWrangleModal(this.dataset, this.sessionData);
} | identifier_body |
file.component.ts | import {
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges,
} from "@angular/core";
import { Dataset, Job, Tool } from "chipster-js-common";
import * as _ from "lodash";
import { Subject } from "rxjs";
import { mergeMap, takeUntil } from "rxjs/operators";
import { RestErrorService } from "../../../../../core/errorhandler/rest-error.service";
import { SessionData } from "../../../../../model/session/session-data";
import { DialogModalService } from "../../dialogmodal/dialogmodal.service";
import { GetSessionDataService } from "../../get-session-data.service";
import { SelectionHandlerService } from "../../selection-handler.service";
import { SelectionService } from "../../selection.service";
import { SessionDataService } from "../../session-data.service";
import { SessionEventService } from "../../session-event.service";
import { DatasetModalService } from "../datasetmodal.service";
@Component({
selector: "ch-file",
templateUrl: "./file.component.html",
styleUrls: ["./file.component.less"],
})
export class FileComponent implements OnInit, OnChanges, OnDestroy {
@Input()
dataset: Dataset;
@Input()
private jobs: Map<string, Job>;
@Input()
sessionData: SessionData;
@Input()
tools: Tool[];
@Output() doScrollFix = new EventEmitter();
datasetName: string;
private unsubscribe: Subject<any> = new Subject();
constructor(
public selectionService: SelectionService, // used in template
private sessionDataService: SessionDataService,
private datasetModalService: DatasetModalService,
private dialogModalService: DialogModalService,
private restErrorService: RestErrorService,
private sessionEventService: SessionEventService,
private getSessionDataService: GetSessionDataService,
private selectionHandlerService: SelectionHandlerService,
private changeDetectorRef: ChangeDetectorRef
) {}
ngOnChanges(changes: SimpleChanges): void {
this.datasetName = this.dataset.name;
}
ngOnInit(): void {
// subscribe to selected dataset content changes, needed for getting new file name after Rename
this.sessionEventService
.getSelectedDatasetsContentsUpdatedStream()
.pipe(takeUntil(this.unsubscribe))
.subscribe({
next: (datasetId) => {
if (datasetId === this.dataset?.datasetId) {
this.datasetName = this.sessionData.datasetsMap.get(this.dataset.datasetId)?.name;
}
},
});
}
renameDataset() {
const dataset = _.clone(this.dataset);
this.dialogModalService
.openStringModal("Rename file", "File name", dataset.name, "Rename")
.pipe(
mergeMap((name) => {
dataset.name = name;
return this.sessionDataService.updateDataset(dataset);
})
)
.subscribe({
error: (err) => this.restErrorService.showError("Rename file failed", err),
});
}
deleteDatasets() {
this.sessionDataService.deleteDatasetsLater(this.selectionService.selectedDatasets);
}
exportDatasets() {
this.sessionDataService.exportDatasets([this.dataset]);
}
showHistory() {
this.datasetModalService.openDatasetHistoryModal(this.dataset, this.sessionData, this.tools);
}
wrangleDataset() {
this.datasetModalService.openWrangleModal(this.dataset, this.sessionData);
}
defineDatasetGroups() {
this.datasetModalService.openGroupsModal(this.selectionService.selectedDatasets, this.sessionData);
}
selectChildren() {
const children = this.getSessionDataService.getChildren(this.selectionService.selectedDatasets);
this.selectionHandlerService.setDatasetSelection(children);
}
| () {
this.unsubscribe.next();
this.unsubscribe.complete();
}
}
| ngOnDestroy | identifier_name |
file.component.ts | import {
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges,
} from "@angular/core";
import { Dataset, Job, Tool } from "chipster-js-common";
import * as _ from "lodash";
import { Subject } from "rxjs";
import { mergeMap, takeUntil } from "rxjs/operators";
import { RestErrorService } from "../../../../../core/errorhandler/rest-error.service";
import { SessionData } from "../../../../../model/session/session-data";
import { DialogModalService } from "../../dialogmodal/dialogmodal.service";
import { GetSessionDataService } from "../../get-session-data.service";
import { SelectionHandlerService } from "../../selection-handler.service";
import { SelectionService } from "../../selection.service";
import { SessionDataService } from "../../session-data.service";
import { SessionEventService } from "../../session-event.service";
import { DatasetModalService } from "../datasetmodal.service";
@Component({
selector: "ch-file",
templateUrl: "./file.component.html",
styleUrls: ["./file.component.less"],
})
export class FileComponent implements OnInit, OnChanges, OnDestroy {
@Input()
dataset: Dataset;
@Input()
private jobs: Map<string, Job>;
@Input()
sessionData: SessionData;
@Input()
tools: Tool[];
|
constructor(
public selectionService: SelectionService, // used in template
private sessionDataService: SessionDataService,
private datasetModalService: DatasetModalService,
private dialogModalService: DialogModalService,
private restErrorService: RestErrorService,
private sessionEventService: SessionEventService,
private getSessionDataService: GetSessionDataService,
private selectionHandlerService: SelectionHandlerService,
private changeDetectorRef: ChangeDetectorRef
) {}
ngOnChanges(changes: SimpleChanges): void {
this.datasetName = this.dataset.name;
}
ngOnInit(): void {
// subscribe to selected dataset content changes, needed for getting new file name after Rename
this.sessionEventService
.getSelectedDatasetsContentsUpdatedStream()
.pipe(takeUntil(this.unsubscribe))
.subscribe({
next: (datasetId) => {
if (datasetId === this.dataset?.datasetId) {
this.datasetName = this.sessionData.datasetsMap.get(this.dataset.datasetId)?.name;
}
},
});
}
renameDataset() {
const dataset = _.clone(this.dataset);
this.dialogModalService
.openStringModal("Rename file", "File name", dataset.name, "Rename")
.pipe(
mergeMap((name) => {
dataset.name = name;
return this.sessionDataService.updateDataset(dataset);
})
)
.subscribe({
error: (err) => this.restErrorService.showError("Rename file failed", err),
});
}
deleteDatasets() {
this.sessionDataService.deleteDatasetsLater(this.selectionService.selectedDatasets);
}
exportDatasets() {
this.sessionDataService.exportDatasets([this.dataset]);
}
showHistory() {
this.datasetModalService.openDatasetHistoryModal(this.dataset, this.sessionData, this.tools);
}
wrangleDataset() {
this.datasetModalService.openWrangleModal(this.dataset, this.sessionData);
}
defineDatasetGroups() {
this.datasetModalService.openGroupsModal(this.selectionService.selectedDatasets, this.sessionData);
}
selectChildren() {
const children = this.getSessionDataService.getChildren(this.selectionService.selectedDatasets);
this.selectionHandlerService.setDatasetSelection(children);
}
ngOnDestroy() {
this.unsubscribe.next();
this.unsubscribe.complete();
}
} | @Output() doScrollFix = new EventEmitter();
datasetName: string;
private unsubscribe: Subject<any> = new Subject(); | random_line_split |
set-replication-status.ts | import type { AdapterPool } from './types'
import type { ReplicationState, OldEvent } from '@resolve-js/eventstore-base'
import initReplicationStateTable from './init-replication-state-table'
const setReplicationStatus = async (
pool: AdapterPool,
lockId: string,
{
statusAndData,
lastEvent,
iterator,
}: {
statusAndData: ReplicationState['statusAndData']
lastEvent?: OldEvent
iterator?: ReplicationState['iterator']
}
): Promise<ReplicationState | null> => {
const { executeStatement, escapeId, escape } = pool
const replicationStateTableName = await initReplicationStateTable(pool)
const rows = await executeStatement(
`UPDATE ${escapeId(replicationStateTableName)}
SET
"Status" = ${escape(statusAndData.status)},
"StatusData" = ${
statusAndData.data != null
? escape(JSON.stringify(statusAndData.data))
: 'NULL'
}
${
lastEvent != null
? `, "SuccessEvent" = ${escape(JSON.stringify(lastEvent))}`
: ``
}
${
iterator !== undefined
? `, "Iterator" = ${
iterator != null ? escape(JSON.stringify(iterator)) : 'NULL'
}`
: ``
}
WHERE "LockId" = ${escape(lockId)}
RETURNING "Status", "StatusData", "Iterator", "IsPaused", "SuccessEvent",
("LockExpirationTime" > CAST(strftime('%s','now') || substr(strftime('%f','now'),4) AS INTEGER)) as "Locked", "LockId"`
)
if (rows.length === 1) {
const row = rows[0]
let lastEvent: OldEvent | null = null
if (row.SuccessEvent != null) {
lastEvent = JSON.parse(row.SuccessEvent) as OldEvent
}
return {
statusAndData: {
status: row.Status,
data: row.StatusData != null ? JSON.parse(row.StatusData) : null,
} as ReplicationState['statusAndData'],
paused: row.IsPaused !== 0,
iterator: row.Iterator != null ? JSON.parse(row.Iterator) : null,
successEvent: lastEvent,
locked: !!row.Locked,
lockId: row.lockId,
}
} else |
}
export default setReplicationStatus
| {
return null
} | conditional_block |
set-replication-status.ts | import type { AdapterPool } from './types'
import type { ReplicationState, OldEvent } from '@resolve-js/eventstore-base'
import initReplicationStateTable from './init-replication-state-table'
const setReplicationStatus = async (
pool: AdapterPool,
lockId: string,
{
statusAndData,
lastEvent, | lastEvent?: OldEvent
iterator?: ReplicationState['iterator']
}
): Promise<ReplicationState | null> => {
const { executeStatement, escapeId, escape } = pool
const replicationStateTableName = await initReplicationStateTable(pool)
const rows = await executeStatement(
`UPDATE ${escapeId(replicationStateTableName)}
SET
"Status" = ${escape(statusAndData.status)},
"StatusData" = ${
statusAndData.data != null
? escape(JSON.stringify(statusAndData.data))
: 'NULL'
}
${
lastEvent != null
? `, "SuccessEvent" = ${escape(JSON.stringify(lastEvent))}`
: ``
}
${
iterator !== undefined
? `, "Iterator" = ${
iterator != null ? escape(JSON.stringify(iterator)) : 'NULL'
}`
: ``
}
WHERE "LockId" = ${escape(lockId)}
RETURNING "Status", "StatusData", "Iterator", "IsPaused", "SuccessEvent",
("LockExpirationTime" > CAST(strftime('%s','now') || substr(strftime('%f','now'),4) AS INTEGER)) as "Locked", "LockId"`
)
if (rows.length === 1) {
const row = rows[0]
let lastEvent: OldEvent | null = null
if (row.SuccessEvent != null) {
lastEvent = JSON.parse(row.SuccessEvent) as OldEvent
}
return {
statusAndData: {
status: row.Status,
data: row.StatusData != null ? JSON.parse(row.StatusData) : null,
} as ReplicationState['statusAndData'],
paused: row.IsPaused !== 0,
iterator: row.Iterator != null ? JSON.parse(row.Iterator) : null,
successEvent: lastEvent,
locked: !!row.Locked,
lockId: row.lockId,
}
} else {
return null
}
}
export default setReplicationStatus | iterator,
}: {
statusAndData: ReplicationState['statusAndData'] | random_line_split |
asm-target-clobbers.rs | // only-x86_64
// revisions: base avx512
// [avx512]compile-flags: -C target-feature=+avx512f
#![crate_type = "rlib"]
#![feature(asm)]
// CHECK-LABEL: @avx512_clobber
// base: call void asm sideeffect inteldialect "", "~{xmm31}"()
// avx512: call float asm sideeffect inteldialect "", "=&{xmm31}"()
#[no_mangle]
pub unsafe fn avx512_clobber() |
// CHECK-LABEL: @eax_clobber
// CHECK: call i32 asm sideeffect inteldialect "", "=&{ax}"()
#[no_mangle]
pub unsafe fn eax_clobber() {
asm!("", out("eax") _, options(nostack, nomem, preserves_flags));
}
| {
asm!("", out("zmm31") _, options(nostack, nomem, preserves_flags));
} | identifier_body |
asm-target-clobbers.rs | // only-x86_64
// revisions: base avx512
// [avx512]compile-flags: -C target-feature=+avx512f
#![crate_type = "rlib"]
#![feature(asm)]
// CHECK-LABEL: @avx512_clobber
// base: call void asm sideeffect inteldialect "", "~{xmm31}"()
// avx512: call float asm sideeffect inteldialect "", "=&{xmm31}"()
#[no_mangle]
pub unsafe fn | () {
asm!("", out("zmm31") _, options(nostack, nomem, preserves_flags));
}
// CHECK-LABEL: @eax_clobber
// CHECK: call i32 asm sideeffect inteldialect "", "=&{ax}"()
#[no_mangle]
pub unsafe fn eax_clobber() {
asm!("", out("eax") _, options(nostack, nomem, preserves_flags));
}
| avx512_clobber | identifier_name |
asm-target-clobbers.rs | // only-x86_64
// revisions: base avx512
// [avx512]compile-flags: -C target-feature=+avx512f
#![crate_type = "rlib"]
#![feature(asm)]
// CHECK-LABEL: @avx512_clobber
// base: call void asm sideeffect inteldialect "", "~{xmm31}"() | pub unsafe fn avx512_clobber() {
asm!("", out("zmm31") _, options(nostack, nomem, preserves_flags));
}
// CHECK-LABEL: @eax_clobber
// CHECK: call i32 asm sideeffect inteldialect "", "=&{ax}"()
#[no_mangle]
pub unsafe fn eax_clobber() {
asm!("", out("eax") _, options(nostack, nomem, preserves_flags));
} | // avx512: call float asm sideeffect inteldialect "", "=&{xmm31}"()
#[no_mangle] | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.