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 |
---|---|---|---|---|
file_info.rs | extern crate libc;
use std::mem;
use crate::libproc::helpers;
use crate::libproc::proc_pid::{ListPIDInfo, PidInfoFlavor};
#[cfg(target_os = "macos")]
use self::libc::{c_int, c_void};
// this extern block links to the libproc library
// Original signatures of functions can be found at http://opensource.apple.com/source/Libc/Libc-594.9.4/darwin/libproc.c
#[cfg(target_os = "macos")]
#[link(name = "proc", kind = "dylib")]
extern {
// This method is supported in the minimum version of Mac OS X which is 10.5
fn proc_pidfdinfo(pid: c_int, fd: c_int, flavor: c_int, buffer: *mut c_void, buffersize: c_int) -> c_int;
}
/// Flavor of Pid FileDescriptor info for different types of File Descriptors
pub enum PIDFDInfoFlavor {
/// VNode Info
VNodeInfo = 1,
/// VNode Path Info
VNodePathInfo = 2,
/// Socket info
SocketInfo = 3,
/// PSEM Info
PSEMInfo = 4,
/// PSHM Info
PSHMInfo = 5,
/// Pipe Info
PipeInfo = 6,
/// KQueue Info
KQueueInfo = 7,
/// Apple Talk Info
ATalkInfo = 8,
}
/// Struct for Listing File Descriptors
pub struct ListFDs;
impl ListPIDInfo for ListFDs {
type Item = ProcFDInfo;
fn flavor() -> PidInfoFlavor { PidInfoFlavor::ListFDs }
}
/// Struct to hold info about a Processes FileDescriptor Info
#[repr(C)]
pub struct ProcFDInfo {
/// File Descriptor
pub proc_fd: i32,
/// File Descriptor type
pub proc_fdtype: u32,
}
/// Enum for different File Descriptor types
#[derive(Copy, Clone, Debug)]
pub enum ProcFDType {
/// AppleTalk
ATalk = 0,
/// Vnode
VNode = 1,
/// Socket
Socket = 2,
/// POSIX shared memory
PSHM = 3,
/// POSIX semaphore
PSEM = 4,
/// Kqueue
KQueue = 5,
/// Pipe
Pipe = 6,
/// FSEvents
FSEvents = 7,
/// Unknown
Unknown,
}
impl From<u32> for ProcFDType {
fn from(value: u32) -> ProcFDType {
match value {
0 => ProcFDType::ATalk,
1 => ProcFDType::VNode,
2 => ProcFDType::Socket,
3 => ProcFDType::PSHM,
4 => ProcFDType::PSEM,
5 => ProcFDType::KQueue,
6 => ProcFDType::Pipe,
7 => ProcFDType::FSEvents,
_ => ProcFDType::Unknown,
}
}
}
/// The `PIDFDInfo` trait is needed for polymorphism on pidfdinfo types, also abstracting flavor in order to provide
/// type-guaranteed flavor correctness
pub trait PIDFDInfo: Default {
/// Return the Pid File Descriptor Info flavor of the implementing struct
fn flavor() -> PIDFDInfoFlavor;
}
/// Returns the information about file descriptors of the process that match pid passed in.
///
/// # Examples
///
/// ```
/// use std::io::Write;
/// use std::net::TcpListener;
/// use libproc::libproc::proc_pid::{listpidinfo, pidinfo, ListThreads};
/// use libproc::libproc::bsd_info::{BSDInfo};
/// use libproc::libproc::net_info::{SocketFDInfo, SocketInfoKind};
/// use libproc::libproc::file_info::{pidfdinfo, ListFDs, ProcFDType};
/// use std::process;
///
/// let pid = process::id() as i32;
///
/// // Open TCP port:8000 to test.
/// let _listener = TcpListener::bind("127.0.0.1:8000");
///
/// if let Ok(info) = pidinfo::<BSDInfo>(pid, 0) {
/// if let Ok(fds) = listpidinfo::<ListFDs>(pid, info.pbi_nfiles as usize) {
/// for fd in &fds {
/// match fd.proc_fdtype.into() {
/// ProcFDType::Socket => {
/// if let Ok(socket) = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd) {
/// match socket.psi.soi_kind.into() {
/// SocketInfoKind::Tcp => {
/// // access to the member of `soi_proto` is unsafe becasuse of union type.
/// let info = unsafe { socket.psi.soi_proto.pri_tcp };
///
/// // change endian and cut off because insi_lport is network endian and 16bit witdh.
/// let mut port = 0;
/// port |= info.tcpsi_ini.insi_lport >> 8 & 0x00ff;
/// port |= info.tcpsi_ini.insi_lport << 8 & 0xff00;
///
/// // access to the member of `insi_laddr` is unsafe becasuse of union type.
/// let s_addr = unsafe { info.tcpsi_ini.insi_laddr.ina_46.i46a_addr4.s_addr };
///
/// // change endian because insi_laddr is network endian.
/// let mut addr = 0;
/// addr |= s_addr >> 24 & 0x000000ff;
/// addr |= s_addr >> 8 & 0x0000ff00;
/// addr |= s_addr << 8 & 0x00ff0000;
/// addr |= s_addr << 24 & 0xff000000;
///
/// println!("{}.{}.{}.{}:{}", addr >> 24 & 0xff, addr >> 16 & 0xff, addr >> 8 & 0xff, addr & 0xff, port);
/// }
/// _ => (),
/// }
/// }
/// }
/// _ => (),
/// }
/// }
/// }
/// }
/// ```
///
#[cfg(target_os = "macos")]
pub fn pidfdinfo<T: PIDFDInfo>(pid: i32, fd: i32) -> Result<T, String> {
let flavor = T::flavor() as i32;
let buffer_size = mem::size_of::<T>() as i32;
let mut pidinfo = T::default();
let buffer_ptr = &mut pidinfo as *mut _ as *mut c_void;
let ret: i32;
unsafe {
ret = proc_pidfdinfo(pid, fd, flavor, buffer_ptr, buffer_size);
};
if ret <= 0 | else {
Ok(pidinfo)
}
}
#[cfg(not(target_os = "macos"))]
pub fn pidfdinfo<T: PIDFDInfo>(_pid: i32, _fd: i32) -> Result<T, String> {
unimplemented!()
}
#[cfg(all(test, target_os = "macos"))]
mod test {
use crate::libproc::bsd_info::BSDInfo;
use crate::libproc::file_info::{ListFDs, ProcFDType};
use crate::libproc::net_info::{SocketFDInfo, SocketInfoKind};
use crate::libproc::proc_pid::{listpidinfo, pidinfo};
use super::pidfdinfo;
#[test]
fn pidfdinfo_test() {
use std::process;
use std::net::TcpListener;
let pid = process::id() as i32;
let _listener = TcpListener::bind("127.0.0.1:65535");
let info = pidinfo::<BSDInfo>(pid, 0).expect("pidinfo() failed");
let fds = listpidinfo::<ListFDs>(pid, info.pbi_nfiles as usize).expect("listpidinfo() failed");
for fd in fds {
if let ProcFDType::Socket = fd.proc_fdtype.into() {
let socket = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd).expect("pidfdinfo() failed");
if let SocketInfoKind::Tcp = socket.psi.soi_kind.into() {
unsafe {
let info = socket.psi.soi_proto.pri_tcp;
assert_eq!(socket.psi.soi_protocol, libc::IPPROTO_TCP);
assert_eq!(info.tcpsi_ini.insi_lport as u32, 65535);
}
}
}
}
}
} | {
Err(helpers::get_errno_with_message(ret))
} | conditional_block |
file_info.rs | extern crate libc;
use std::mem;
use crate::libproc::helpers;
use crate::libproc::proc_pid::{ListPIDInfo, PidInfoFlavor};
#[cfg(target_os = "macos")]
use self::libc::{c_int, c_void};
// this extern block links to the libproc library
// Original signatures of functions can be found at http://opensource.apple.com/source/Libc/Libc-594.9.4/darwin/libproc.c
#[cfg(target_os = "macos")]
#[link(name = "proc", kind = "dylib")]
extern {
// This method is supported in the minimum version of Mac OS X which is 10.5
fn proc_pidfdinfo(pid: c_int, fd: c_int, flavor: c_int, buffer: *mut c_void, buffersize: c_int) -> c_int;
}
/// Flavor of Pid FileDescriptor info for different types of File Descriptors
pub enum PIDFDInfoFlavor {
/// VNode Info
VNodeInfo = 1,
/// VNode Path Info
VNodePathInfo = 2,
/// Socket info
SocketInfo = 3,
/// PSEM Info
PSEMInfo = 4,
/// PSHM Info
PSHMInfo = 5,
/// Pipe Info
PipeInfo = 6,
/// KQueue Info
KQueueInfo = 7,
/// Apple Talk Info
ATalkInfo = 8,
}
/// Struct for Listing File Descriptors
pub struct ListFDs;
impl ListPIDInfo for ListFDs {
type Item = ProcFDInfo;
fn flavor() -> PidInfoFlavor { PidInfoFlavor::ListFDs }
}
/// Struct to hold info about a Processes FileDescriptor Info
#[repr(C)]
pub struct ProcFDInfo {
/// File Descriptor
pub proc_fd: i32,
/// File Descriptor type
pub proc_fdtype: u32,
}
/// Enum for different File Descriptor types
#[derive(Copy, Clone, Debug)]
pub enum ProcFDType {
/// AppleTalk
ATalk = 0,
/// Vnode
VNode = 1,
/// Socket
Socket = 2,
/// POSIX shared memory
PSHM = 3,
/// POSIX semaphore
PSEM = 4,
/// Kqueue
KQueue = 5,
/// Pipe
Pipe = 6,
/// FSEvents
FSEvents = 7,
/// Unknown
Unknown,
}
impl From<u32> for ProcFDType {
fn from(value: u32) -> ProcFDType {
match value {
0 => ProcFDType::ATalk,
1 => ProcFDType::VNode,
2 => ProcFDType::Socket,
3 => ProcFDType::PSHM,
4 => ProcFDType::PSEM,
5 => ProcFDType::KQueue,
6 => ProcFDType::Pipe,
7 => ProcFDType::FSEvents,
_ => ProcFDType::Unknown,
}
}
}
/// The `PIDFDInfo` trait is needed for polymorphism on pidfdinfo types, also abstracting flavor in order to provide
/// type-guaranteed flavor correctness
pub trait PIDFDInfo: Default {
/// Return the Pid File Descriptor Info flavor of the implementing struct
fn flavor() -> PIDFDInfoFlavor;
}
/// Returns the information about file descriptors of the process that match pid passed in.
///
/// # Examples
///
/// ```
/// use std::io::Write;
/// use std::net::TcpListener;
/// use libproc::libproc::proc_pid::{listpidinfo, pidinfo, ListThreads};
/// use libproc::libproc::bsd_info::{BSDInfo};
/// use libproc::libproc::net_info::{SocketFDInfo, SocketInfoKind};
/// use libproc::libproc::file_info::{pidfdinfo, ListFDs, ProcFDType};
/// use std::process;
///
/// let pid = process::id() as i32;
///
/// // Open TCP port:8000 to test.
/// let _listener = TcpListener::bind("127.0.0.1:8000");
///
/// if let Ok(info) = pidinfo::<BSDInfo>(pid, 0) {
/// if let Ok(fds) = listpidinfo::<ListFDs>(pid, info.pbi_nfiles as usize) {
/// for fd in &fds {
/// match fd.proc_fdtype.into() {
/// ProcFDType::Socket => {
/// if let Ok(socket) = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd) {
/// match socket.psi.soi_kind.into() {
/// SocketInfoKind::Tcp => {
/// // access to the member of `soi_proto` is unsafe becasuse of union type.
/// let info = unsafe { socket.psi.soi_proto.pri_tcp };
///
/// // change endian and cut off because insi_lport is network endian and 16bit witdh.
/// let mut port = 0;
/// port |= info.tcpsi_ini.insi_lport >> 8 & 0x00ff;
/// port |= info.tcpsi_ini.insi_lport << 8 & 0xff00;
///
/// // access to the member of `insi_laddr` is unsafe becasuse of union type.
/// let s_addr = unsafe { info.tcpsi_ini.insi_laddr.ina_46.i46a_addr4.s_addr };
///
/// // change endian because insi_laddr is network endian.
/// let mut addr = 0;
/// addr |= s_addr >> 24 & 0x000000ff;
/// addr |= s_addr >> 8 & 0x0000ff00;
/// addr |= s_addr << 8 & 0x00ff0000;
/// addr |= s_addr << 24 & 0xff000000;
///
/// println!("{}.{}.{}.{}:{}", addr >> 24 & 0xff, addr >> 16 & 0xff, addr >> 8 & 0xff, addr & 0xff, port);
/// }
/// _ => (),
/// }
/// }
/// }
/// _ => (),
/// }
/// }
/// }
/// }
/// ```
///
#[cfg(target_os = "macos")]
pub fn pidfdinfo<T: PIDFDInfo>(pid: i32, fd: i32) -> Result<T, String> {
let flavor = T::flavor() as i32;
let buffer_size = mem::size_of::<T>() as i32;
let mut pidinfo = T::default();
let buffer_ptr = &mut pidinfo as *mut _ as *mut c_void;
let ret: i32;
unsafe {
ret = proc_pidfdinfo(pid, fd, flavor, buffer_ptr, buffer_size);
};
if ret <= 0 {
Err(helpers::get_errno_with_message(ret))
} else {
Ok(pidinfo)
}
}
#[cfg(not(target_os = "macos"))]
pub fn pidfdinfo<T: PIDFDInfo>(_pid: i32, _fd: i32) -> Result<T, String> |
#[cfg(all(test, target_os = "macos"))]
mod test {
use crate::libproc::bsd_info::BSDInfo;
use crate::libproc::file_info::{ListFDs, ProcFDType};
use crate::libproc::net_info::{SocketFDInfo, SocketInfoKind};
use crate::libproc::proc_pid::{listpidinfo, pidinfo};
use super::pidfdinfo;
#[test]
fn pidfdinfo_test() {
use std::process;
use std::net::TcpListener;
let pid = process::id() as i32;
let _listener = TcpListener::bind("127.0.0.1:65535");
let info = pidinfo::<BSDInfo>(pid, 0).expect("pidinfo() failed");
let fds = listpidinfo::<ListFDs>(pid, info.pbi_nfiles as usize).expect("listpidinfo() failed");
for fd in fds {
if let ProcFDType::Socket = fd.proc_fdtype.into() {
let socket = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd).expect("pidfdinfo() failed");
if let SocketInfoKind::Tcp = socket.psi.soi_kind.into() {
unsafe {
let info = socket.psi.soi_proto.pri_tcp;
assert_eq!(socket.psi.soi_protocol, libc::IPPROTO_TCP);
assert_eq!(info.tcpsi_ini.insi_lport as u32, 65535);
}
}
}
}
}
} | {
unimplemented!()
} | identifier_body |
file_info.rs | use std::mem;
use crate::libproc::helpers;
use crate::libproc::proc_pid::{ListPIDInfo, PidInfoFlavor};
#[cfg(target_os = "macos")]
use self::libc::{c_int, c_void};
// this extern block links to the libproc library
// Original signatures of functions can be found at http://opensource.apple.com/source/Libc/Libc-594.9.4/darwin/libproc.c
#[cfg(target_os = "macos")]
#[link(name = "proc", kind = "dylib")]
extern {
// This method is supported in the minimum version of Mac OS X which is 10.5
fn proc_pidfdinfo(pid: c_int, fd: c_int, flavor: c_int, buffer: *mut c_void, buffersize: c_int) -> c_int;
}
/// Flavor of Pid FileDescriptor info for different types of File Descriptors
pub enum PIDFDInfoFlavor {
/// VNode Info
VNodeInfo = 1,
/// VNode Path Info
VNodePathInfo = 2,
/// Socket info
SocketInfo = 3,
/// PSEM Info
PSEMInfo = 4,
/// PSHM Info
PSHMInfo = 5,
/// Pipe Info
PipeInfo = 6,
/// KQueue Info
KQueueInfo = 7,
/// Apple Talk Info
ATalkInfo = 8,
}
/// Struct for Listing File Descriptors
pub struct ListFDs;
impl ListPIDInfo for ListFDs {
type Item = ProcFDInfo;
fn flavor() -> PidInfoFlavor { PidInfoFlavor::ListFDs }
}
/// Struct to hold info about a Processes FileDescriptor Info
#[repr(C)]
pub struct ProcFDInfo {
/// File Descriptor
pub proc_fd: i32,
/// File Descriptor type
pub proc_fdtype: u32,
}
/// Enum for different File Descriptor types
#[derive(Copy, Clone, Debug)]
pub enum ProcFDType {
/// AppleTalk
ATalk = 0,
/// Vnode
VNode = 1,
/// Socket
Socket = 2,
/// POSIX shared memory
PSHM = 3,
/// POSIX semaphore
PSEM = 4,
/// Kqueue
KQueue = 5,
/// Pipe
Pipe = 6,
/// FSEvents
FSEvents = 7,
/// Unknown
Unknown,
}
impl From<u32> for ProcFDType {
fn from(value: u32) -> ProcFDType {
match value {
0 => ProcFDType::ATalk,
1 => ProcFDType::VNode,
2 => ProcFDType::Socket,
3 => ProcFDType::PSHM,
4 => ProcFDType::PSEM,
5 => ProcFDType::KQueue,
6 => ProcFDType::Pipe,
7 => ProcFDType::FSEvents,
_ => ProcFDType::Unknown,
}
}
}
/// The `PIDFDInfo` trait is needed for polymorphism on pidfdinfo types, also abstracting flavor in order to provide
/// type-guaranteed flavor correctness
pub trait PIDFDInfo: Default {
/// Return the Pid File Descriptor Info flavor of the implementing struct
fn flavor() -> PIDFDInfoFlavor;
}
/// Returns the information about file descriptors of the process that match pid passed in.
///
/// # Examples
///
/// ```
/// use std::io::Write;
/// use std::net::TcpListener;
/// use libproc::libproc::proc_pid::{listpidinfo, pidinfo, ListThreads};
/// use libproc::libproc::bsd_info::{BSDInfo};
/// use libproc::libproc::net_info::{SocketFDInfo, SocketInfoKind};
/// use libproc::libproc::file_info::{pidfdinfo, ListFDs, ProcFDType};
/// use std::process;
///
/// let pid = process::id() as i32;
///
/// // Open TCP port:8000 to test.
/// let _listener = TcpListener::bind("127.0.0.1:8000");
///
/// if let Ok(info) = pidinfo::<BSDInfo>(pid, 0) {
/// if let Ok(fds) = listpidinfo::<ListFDs>(pid, info.pbi_nfiles as usize) {
/// for fd in &fds {
/// match fd.proc_fdtype.into() {
/// ProcFDType::Socket => {
/// if let Ok(socket) = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd) {
/// match socket.psi.soi_kind.into() {
/// SocketInfoKind::Tcp => {
/// // access to the member of `soi_proto` is unsafe becasuse of union type.
/// let info = unsafe { socket.psi.soi_proto.pri_tcp };
///
/// // change endian and cut off because insi_lport is network endian and 16bit witdh.
/// let mut port = 0;
/// port |= info.tcpsi_ini.insi_lport >> 8 & 0x00ff;
/// port |= info.tcpsi_ini.insi_lport << 8 & 0xff00;
///
/// // access to the member of `insi_laddr` is unsafe becasuse of union type.
/// let s_addr = unsafe { info.tcpsi_ini.insi_laddr.ina_46.i46a_addr4.s_addr };
///
/// // change endian because insi_laddr is network endian.
/// let mut addr = 0;
/// addr |= s_addr >> 24 & 0x000000ff;
/// addr |= s_addr >> 8 & 0x0000ff00;
/// addr |= s_addr << 8 & 0x00ff0000;
/// addr |= s_addr << 24 & 0xff000000;
///
/// println!("{}.{}.{}.{}:{}", addr >> 24 & 0xff, addr >> 16 & 0xff, addr >> 8 & 0xff, addr & 0xff, port);
/// }
/// _ => (),
/// }
/// }
/// }
/// _ => (),
/// }
/// }
/// }
/// }
/// ```
///
#[cfg(target_os = "macos")]
pub fn pidfdinfo<T: PIDFDInfo>(pid: i32, fd: i32) -> Result<T, String> {
let flavor = T::flavor() as i32;
let buffer_size = mem::size_of::<T>() as i32;
let mut pidinfo = T::default();
let buffer_ptr = &mut pidinfo as *mut _ as *mut c_void;
let ret: i32;
unsafe {
ret = proc_pidfdinfo(pid, fd, flavor, buffer_ptr, buffer_size);
};
if ret <= 0 {
Err(helpers::get_errno_with_message(ret))
} else {
Ok(pidinfo)
}
}
#[cfg(not(target_os = "macos"))]
pub fn pidfdinfo<T: PIDFDInfo>(_pid: i32, _fd: i32) -> Result<T, String> {
unimplemented!()
}
#[cfg(all(test, target_os = "macos"))]
mod test {
use crate::libproc::bsd_info::BSDInfo;
use crate::libproc::file_info::{ListFDs, ProcFDType};
use crate::libproc::net_info::{SocketFDInfo, SocketInfoKind};
use crate::libproc::proc_pid::{listpidinfo, pidinfo};
use super::pidfdinfo;
#[test]
fn pidfdinfo_test() {
use std::process;
use std::net::TcpListener;
let pid = process::id() as i32;
let _listener = TcpListener::bind("127.0.0.1:65535");
let info = pidinfo::<BSDInfo>(pid, 0).expect("pidinfo() failed");
let fds = listpidinfo::<ListFDs>(pid, info.pbi_nfiles as usize).expect("listpidinfo() failed");
for fd in fds {
if let ProcFDType::Socket = fd.proc_fdtype.into() {
let socket = pidfdinfo::<SocketFDInfo>(pid, fd.proc_fd).expect("pidfdinfo() failed");
if let SocketInfoKind::Tcp = socket.psi.soi_kind.into() {
unsafe {
let info = socket.psi.soi_proto.pri_tcp;
assert_eq!(socket.psi.soi_protocol, libc::IPPROTO_TCP);
assert_eq!(info.tcpsi_ini.insi_lport as u32, 65535);
}
}
}
}
}
} | extern crate libc;
| random_line_split |
|
index.ts | /**
* @ngdoc filter
* @module superdesk.apps.products
* @name ProductsFilter
* @description Returns a function that allows filtering an array of
* products by various criteria.
*/
export function ProductsFilter() {
/**
* @description Returns a new array based on the passed filter.
* @param {Array<Object>} items - Array of templates to filter.
* @param {Object} search - The filter. search by name and product type.
* @returns {Array<Object>} The filtered array.
*/
return function(items, search) {
if (!search) {
return items;
}
let filteredItems = items;
if (search.name && search.name !== '') |
if (search.product_type && search.product_type !== '') {
filteredItems = filteredItems.filter((item) => (item.product_type || 'both') === search.product_type);
}
return filteredItems;
};
}
| {
const regExp = new RegExp(search.name, 'i');
filteredItems = filteredItems.filter((item) => item.name.match(regExp));
} | conditional_block |
index.ts | /**
* @ngdoc filter
* @module superdesk.apps.products
* @name ProductsFilter
* @description Returns a function that allows filtering an array of
* products by various criteria.
*/
export function | () {
/**
* @description Returns a new array based on the passed filter.
* @param {Array<Object>} items - Array of templates to filter.
* @param {Object} search - The filter. search by name and product type.
* @returns {Array<Object>} The filtered array.
*/
return function(items, search) {
if (!search) {
return items;
}
let filteredItems = items;
if (search.name && search.name !== '') {
const regExp = new RegExp(search.name, 'i');
filteredItems = filteredItems.filter((item) => item.name.match(regExp));
}
if (search.product_type && search.product_type !== '') {
filteredItems = filteredItems.filter((item) => (item.product_type || 'both') === search.product_type);
}
return filteredItems;
};
}
| ProductsFilter | identifier_name |
index.ts | /**
* @ngdoc filter
* @module superdesk.apps.products
* @name ProductsFilter
* @description Returns a function that allows filtering an array of
* products by various criteria.
*/
export function ProductsFilter() | {
/**
* @description Returns a new array based on the passed filter.
* @param {Array<Object>} items - Array of templates to filter.
* @param {Object} search - The filter. search by name and product type.
* @returns {Array<Object>} The filtered array.
*/
return function(items, search) {
if (!search) {
return items;
}
let filteredItems = items;
if (search.name && search.name !== '') {
const regExp = new RegExp(search.name, 'i');
filteredItems = filteredItems.filter((item) => item.name.match(regExp));
}
if (search.product_type && search.product_type !== '') {
filteredItems = filteredItems.filter((item) => (item.product_type || 'both') === search.product_type);
}
return filteredItems;
};
} | identifier_body |
|
index.ts | /**
* @ngdoc filter
* @module superdesk.apps.products
* @name ProductsFilter
* @description Returns a function that allows filtering an array of | */
export function ProductsFilter() {
/**
* @description Returns a new array based on the passed filter.
* @param {Array<Object>} items - Array of templates to filter.
* @param {Object} search - The filter. search by name and product type.
* @returns {Array<Object>} The filtered array.
*/
return function(items, search) {
if (!search) {
return items;
}
let filteredItems = items;
if (search.name && search.name !== '') {
const regExp = new RegExp(search.name, 'i');
filteredItems = filteredItems.filter((item) => item.name.match(regExp));
}
if (search.product_type && search.product_type !== '') {
filteredItems = filteredItems.filter((item) => (item.product_type || 'both') === search.product_type);
}
return filteredItems;
};
} | * products by various criteria. | random_line_split |
tools.js | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import Color from 'color';
/**
* Adjust a given token's lightness by a specified percentage
* Example: token = hsl(10, 10, 10);
* adjustLightness(token, 5) === hsl(10, 10, 15);
* adjustLightness(token, -5) === hsl(10, 10, 5);
* @param {string} token
* @param {integer} shift The number of percentage points (positive or negative) by which to shift the lightness of a token.
* @returns {string}
*/
export function | (token, shift) {
const original = Color(token).hsl().object();
return Color({ ...original, l: (original.l += shift) })
.round()
.hex()
.toLowerCase();
}
| adjustLightness | identifier_name |
tools.js | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import Color from 'color';
/**
* Adjust a given token's lightness by a specified percentage
* Example: token = hsl(10, 10, 10);
* adjustLightness(token, 5) === hsl(10, 10, 15);
* adjustLightness(token, -5) === hsl(10, 10, 5);
* @param {string} token
* @param {integer} shift The number of percentage points (positive or negative) by which to shift the lightness of a token.
* @returns {string}
*/
export function adjustLightness(token, shift) | {
const original = Color(token).hsl().object();
return Color({ ...original, l: (original.l += shift) })
.round()
.hex()
.toLowerCase();
} | identifier_body |
|
tools.js | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import Color from 'color';
/**
* Adjust a given token's lightness by a specified percentage
* Example: token = hsl(10, 10, 10);
* adjustLightness(token, 5) === hsl(10, 10, 15);
* adjustLightness(token, -5) === hsl(10, 10, 5);
* @param {string} token
* @param {integer} shift The number of percentage points (positive or negative) by which to shift the lightness of a token.
* @returns {string}
*/
export function adjustLightness(token, shift) {
const original = Color(token).hsl().object();
return Color({ ...original, l: (original.l += shift) })
.round()
.hex() | } | .toLowerCase(); | random_line_split |
help.py | from wrappers import *
from inspect import getdoc
@plugin
class Help:
@command("list")
def list(self, message):
"""list the loaded plugins"""
return message.reply(list(self.bot.plugins.keys()), "loaded plugins: " + ", ".join(self.bot.plugins.keys()))
@command("commands")
def listcoms(self, message):
"""list the available commands"""
return message.reply(list(self.bot.commands.keys()), "available commands: " + ", ".join(self.bot.commands.keys()))
@command("aliases")
def listaliases(self, message):
"""list the saved aliases"""
return message.reply(list(self.bot.aliases.keys()), "saved aliases: " + ", ".join(self.bot.aliases.keys()))
@command("expand")
def expand(self, message):
"""show what an alias does"""
if message.text:
command = message.text.split()[0].strip()
if command in self.bot.aliases:
x = self.bot.aliases[command]
x = self.bot.command_char+ "alias %s = " % command + " || ".join(["%s%s" % (cmd, (" " + arg) if arg else "") for cmd, arg in x])
return message.reply(x)
@command("help", simple=True)
def help_(self, message):
"""help <command> => returns the help for the specified command"""
if not isinstance(message.data, str):
doc = getdoc(message.data)
if not doc:
return message.reply("No help found for passed object '%s'" % message.data.__class__.__name__)
else:
firstline = "%s: %s" % (message.data.__class__.__name__, doc.split("\n")[0])
return message.reply(doc, firstline)
elif message.data:
try:
com = message.data.split()[0]
func = self.bot.commands[com][0]
except:
raise Exception("specifed command not found")
doc = func.__doc__
if not doc:
return message.reply("No help found for specified command")
else:
|
else:
return message.reply("Help can be found at https://github.com/ellxc/piperbot/blob/master/README.md or by joining #piperbot on freenode") | firstline = "%s: %s" % (com, doc.split("\n")[0])
return message.reply(doc, firstline) | conditional_block |
help.py | from wrappers import *
from inspect import getdoc
@plugin
class Help:
@command("list")
def list(self, message):
"""list the loaded plugins"""
return message.reply(list(self.bot.plugins.keys()), "loaded plugins: " + ", ".join(self.bot.plugins.keys()))
@command("commands")
def | (self, message):
"""list the available commands"""
return message.reply(list(self.bot.commands.keys()), "available commands: " + ", ".join(self.bot.commands.keys()))
@command("aliases")
def listaliases(self, message):
"""list the saved aliases"""
return message.reply(list(self.bot.aliases.keys()), "saved aliases: " + ", ".join(self.bot.aliases.keys()))
@command("expand")
def expand(self, message):
"""show what an alias does"""
if message.text:
command = message.text.split()[0].strip()
if command in self.bot.aliases:
x = self.bot.aliases[command]
x = self.bot.command_char+ "alias %s = " % command + " || ".join(["%s%s" % (cmd, (" " + arg) if arg else "") for cmd, arg in x])
return message.reply(x)
@command("help", simple=True)
def help_(self, message):
"""help <command> => returns the help for the specified command"""
if not isinstance(message.data, str):
doc = getdoc(message.data)
if not doc:
return message.reply("No help found for passed object '%s'" % message.data.__class__.__name__)
else:
firstline = "%s: %s" % (message.data.__class__.__name__, doc.split("\n")[0])
return message.reply(doc, firstline)
elif message.data:
try:
com = message.data.split()[0]
func = self.bot.commands[com][0]
except:
raise Exception("specifed command not found")
doc = func.__doc__
if not doc:
return message.reply("No help found for specified command")
else:
firstline = "%s: %s" % (com, doc.split("\n")[0])
return message.reply(doc, firstline)
else:
return message.reply("Help can be found at https://github.com/ellxc/piperbot/blob/master/README.md or by joining #piperbot on freenode") | listcoms | identifier_name |
help.py | from wrappers import *
from inspect import getdoc
@plugin
class Help:
| @command("list")
def list(self, message):
"""list the loaded plugins"""
return message.reply(list(self.bot.plugins.keys()), "loaded plugins: " + ", ".join(self.bot.plugins.keys()))
@command("commands")
def listcoms(self, message):
"""list the available commands"""
return message.reply(list(self.bot.commands.keys()), "available commands: " + ", ".join(self.bot.commands.keys()))
@command("aliases")
def listaliases(self, message):
"""list the saved aliases"""
return message.reply(list(self.bot.aliases.keys()), "saved aliases: " + ", ".join(self.bot.aliases.keys()))
@command("expand")
def expand(self, message):
"""show what an alias does"""
if message.text:
command = message.text.split()[0].strip()
if command in self.bot.aliases:
x = self.bot.aliases[command]
x = self.bot.command_char+ "alias %s = " % command + " || ".join(["%s%s" % (cmd, (" " + arg) if arg else "") for cmd, arg in x])
return message.reply(x)
@command("help", simple=True)
def help_(self, message):
"""help <command> => returns the help for the specified command"""
if not isinstance(message.data, str):
doc = getdoc(message.data)
if not doc:
return message.reply("No help found for passed object '%s'" % message.data.__class__.__name__)
else:
firstline = "%s: %s" % (message.data.__class__.__name__, doc.split("\n")[0])
return message.reply(doc, firstline)
elif message.data:
try:
com = message.data.split()[0]
func = self.bot.commands[com][0]
except:
raise Exception("specifed command not found")
doc = func.__doc__
if not doc:
return message.reply("No help found for specified command")
else:
firstline = "%s: %s" % (com, doc.split("\n")[0])
return message.reply(doc, firstline)
else:
return message.reply("Help can be found at https://github.com/ellxc/piperbot/blob/master/README.md or by joining #piperbot on freenode") | identifier_body |
|
help.py | from wrappers import *
from inspect import getdoc
@plugin
class Help:
@command("list")
def list(self, message):
"""list the loaded plugins"""
return message.reply(list(self.bot.plugins.keys()), "loaded plugins: " + ", ".join(self.bot.plugins.keys()))
@command("commands")
def listcoms(self, message):
"""list the available commands"""
return message.reply(list(self.bot.commands.keys()), "available commands: " + ", ".join(self.bot.commands.keys()))
@command("aliases")
def listaliases(self, message):
"""list the saved aliases"""
return message.reply(list(self.bot.aliases.keys()), "saved aliases: " + ", ".join(self.bot.aliases.keys()))
@command("expand")
def expand(self, message):
"""show what an alias does"""
if message.text:
command = message.text.split()[0].strip()
if command in self.bot.aliases:
x = self.bot.aliases[command]
x = self.bot.command_char+ "alias %s = " % command + " || ".join(["%s%s" % (cmd, (" " + arg) if arg else "") for cmd, arg in x])
return message.reply(x)
@command("help", simple=True)
def help_(self, message):
"""help <command> => returns the help for the specified command"""
if not isinstance(message.data, str):
doc = getdoc(message.data)
if not doc:
return message.reply("No help found for passed object '%s'" % message.data.__class__.__name__)
else:
| return message.reply(doc, firstline)
elif message.data:
try:
com = message.data.split()[0]
func = self.bot.commands[com][0]
except:
raise Exception("specifed command not found")
doc = func.__doc__
if not doc:
return message.reply("No help found for specified command")
else:
firstline = "%s: %s" % (com, doc.split("\n")[0])
return message.reply(doc, firstline)
else:
return message.reply("Help can be found at https://github.com/ellxc/piperbot/blob/master/README.md or by joining #piperbot on freenode") | firstline = "%s: %s" % (message.data.__class__.__name__, doc.split("\n")[0])
| random_line_split |
errors.rs | /*
Copyright (c) 2016-2017, Robert Ou <[email protected]> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
use crate::util::{b2s};
use std::error;
use std::fmt;
use jedec::*;
/// Errors that can occur when parsing a bitstream
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum XC2BitError {
/// The .jed file could not be parsed
JedParseError(JedParserError), | /// The device name is invalid
BadDeviceName(String),
/// The number of fuses was incorrect for the device
WrongFuseCount,
/// An unknown value was used in the `Oe` field
UnsupportedOeConfiguration([bool; 4]),
/// An unknown value was used in the ZIA selection bits
UnsupportedZIAConfiguration(Vec<bool>),
}
impl From<JedParserError> for XC2BitError {
fn from(err: JedParserError) -> Self {
XC2BitError::JedParseError(err)
}
}
impl From<()> for XC2BitError {
fn from(_: ()) -> Self {
// FIXME
unreachable!();
}
}
impl error::Error for XC2BitError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
&XC2BitError::JedParseError(ref err) => Some(err),
&XC2BitError::BadDeviceName(_) => None,
&XC2BitError::WrongFuseCount => None,
&XC2BitError::UnsupportedOeConfiguration(_) => None,
&XC2BitError::UnsupportedZIAConfiguration(_) => None,
}
}
}
impl fmt::Display for XC2BitError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&XC2BitError::JedParseError(err) => {
write!(f, ".jed parsing failed: {}", err)
},
&XC2BitError::BadDeviceName(ref devname) => {
write!(f, "device name \"{}\" is invalid/unsupported", devname)
},
&XC2BitError::WrongFuseCount => {
write!(f, "wrong number of fuses")
},
&XC2BitError::UnsupportedOeConfiguration(bits) => {
write!(f, "unknown Oe field value {}{}{}{}",
b2s(bits[0]), b2s(bits[1]),
b2s(bits[2]), b2s(bits[3]))
},
&XC2BitError::UnsupportedZIAConfiguration(ref bits) => {
write!(f, "unknown ZIA selection bit pattern ")?;
for &bit in bits {
write!(f, "{}", b2s(bit))?;
}
Ok(())
},
}
}
} | random_line_split |
|
errors.rs | /*
Copyright (c) 2016-2017, Robert Ou <[email protected]> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
use crate::util::{b2s};
use std::error;
use std::fmt;
use jedec::*;
/// Errors that can occur when parsing a bitstream
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum XC2BitError {
/// The .jed file could not be parsed
JedParseError(JedParserError),
/// The device name is invalid
BadDeviceName(String),
/// The number of fuses was incorrect for the device
WrongFuseCount,
/// An unknown value was used in the `Oe` field
UnsupportedOeConfiguration([bool; 4]),
/// An unknown value was used in the ZIA selection bits
UnsupportedZIAConfiguration(Vec<bool>),
}
impl From<JedParserError> for XC2BitError {
fn from(err: JedParserError) -> Self {
XC2BitError::JedParseError(err)
}
}
impl From<()> for XC2BitError {
fn | (_: ()) -> Self {
// FIXME
unreachable!();
}
}
impl error::Error for XC2BitError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
&XC2BitError::JedParseError(ref err) => Some(err),
&XC2BitError::BadDeviceName(_) => None,
&XC2BitError::WrongFuseCount => None,
&XC2BitError::UnsupportedOeConfiguration(_) => None,
&XC2BitError::UnsupportedZIAConfiguration(_) => None,
}
}
}
impl fmt::Display for XC2BitError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&XC2BitError::JedParseError(err) => {
write!(f, ".jed parsing failed: {}", err)
},
&XC2BitError::BadDeviceName(ref devname) => {
write!(f, "device name \"{}\" is invalid/unsupported", devname)
},
&XC2BitError::WrongFuseCount => {
write!(f, "wrong number of fuses")
},
&XC2BitError::UnsupportedOeConfiguration(bits) => {
write!(f, "unknown Oe field value {}{}{}{}",
b2s(bits[0]), b2s(bits[1]),
b2s(bits[2]), b2s(bits[3]))
},
&XC2BitError::UnsupportedZIAConfiguration(ref bits) => {
write!(f, "unknown ZIA selection bit pattern ")?;
for &bit in bits {
write!(f, "{}", b2s(bit))?;
}
Ok(())
},
}
}
}
| from | identifier_name |
errors.rs | /*
Copyright (c) 2016-2017, Robert Ou <[email protected]> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
use crate::util::{b2s};
use std::error;
use std::fmt;
use jedec::*;
/// Errors that can occur when parsing a bitstream
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum XC2BitError {
/// The .jed file could not be parsed
JedParseError(JedParserError),
/// The device name is invalid
BadDeviceName(String),
/// The number of fuses was incorrect for the device
WrongFuseCount,
/// An unknown value was used in the `Oe` field
UnsupportedOeConfiguration([bool; 4]),
/// An unknown value was used in the ZIA selection bits
UnsupportedZIAConfiguration(Vec<bool>),
}
impl From<JedParserError> for XC2BitError {
fn from(err: JedParserError) -> Self {
XC2BitError::JedParseError(err)
}
}
impl From<()> for XC2BitError {
fn from(_: ()) -> Self {
// FIXME
unreachable!();
}
}
impl error::Error for XC2BitError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
&XC2BitError::JedParseError(ref err) => Some(err),
&XC2BitError::BadDeviceName(_) => None,
&XC2BitError::WrongFuseCount => None,
&XC2BitError::UnsupportedOeConfiguration(_) => None,
&XC2BitError::UnsupportedZIAConfiguration(_) => None,
}
}
}
impl fmt::Display for XC2BitError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&XC2BitError::JedParseError(err) => {
write!(f, ".jed parsing failed: {}", err)
},
&XC2BitError::BadDeviceName(ref devname) => {
write!(f, "device name \"{}\" is invalid/unsupported", devname)
},
&XC2BitError::WrongFuseCount => {
write!(f, "wrong number of fuses")
},
&XC2BitError::UnsupportedOeConfiguration(bits) => {
write!(f, "unknown Oe field value {}{}{}{}",
b2s(bits[0]), b2s(bits[1]),
b2s(bits[2]), b2s(bits[3]))
},
&XC2BitError::UnsupportedZIAConfiguration(ref bits) => | ,
}
}
}
| {
write!(f, "unknown ZIA selection bit pattern ")?;
for &bit in bits {
write!(f, "{}", b2s(bit))?;
}
Ok(())
} | conditional_block |
errors.rs | /*
Copyright (c) 2016-2017, Robert Ou <[email protected]> and contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
use crate::util::{b2s};
use std::error;
use std::fmt;
use jedec::*;
/// Errors that can occur when parsing a bitstream
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum XC2BitError {
/// The .jed file could not be parsed
JedParseError(JedParserError),
/// The device name is invalid
BadDeviceName(String),
/// The number of fuses was incorrect for the device
WrongFuseCount,
/// An unknown value was used in the `Oe` field
UnsupportedOeConfiguration([bool; 4]),
/// An unknown value was used in the ZIA selection bits
UnsupportedZIAConfiguration(Vec<bool>),
}
impl From<JedParserError> for XC2BitError {
fn from(err: JedParserError) -> Self {
XC2BitError::JedParseError(err)
}
}
impl From<()> for XC2BitError {
fn from(_: ()) -> Self {
// FIXME
unreachable!();
}
}
impl error::Error for XC2BitError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> |
}
impl fmt::Display for XC2BitError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&XC2BitError::JedParseError(err) => {
write!(f, ".jed parsing failed: {}", err)
},
&XC2BitError::BadDeviceName(ref devname) => {
write!(f, "device name \"{}\" is invalid/unsupported", devname)
},
&XC2BitError::WrongFuseCount => {
write!(f, "wrong number of fuses")
},
&XC2BitError::UnsupportedOeConfiguration(bits) => {
write!(f, "unknown Oe field value {}{}{}{}",
b2s(bits[0]), b2s(bits[1]),
b2s(bits[2]), b2s(bits[3]))
},
&XC2BitError::UnsupportedZIAConfiguration(ref bits) => {
write!(f, "unknown ZIA selection bit pattern ")?;
for &bit in bits {
write!(f, "{}", b2s(bit))?;
}
Ok(())
},
}
}
}
| {
match self {
&XC2BitError::JedParseError(ref err) => Some(err),
&XC2BitError::BadDeviceName(_) => None,
&XC2BitError::WrongFuseCount => None,
&XC2BitError::UnsupportedOeConfiguration(_) => None,
&XC2BitError::UnsupportedZIAConfiguration(_) => None,
}
} | identifier_body |
stack_switcher.rs | // This file was generated by gir (17af302) from gir-files (11e0e6d)
// DO NOT EDIT
use Box;
use Buildable;
use Container;
use Orientable;
#[cfg(feature = "3.10")]
use Stack;
use Widget;
use ffi;
use glib::object::Downcast;
use glib::translate::*;
glib_wrapper! {
pub struct StackSwitcher(Object<ffi::GtkStackSwitcher>): Widget, Container, Box, Buildable, Orientable;
match fn {
get_type => || ffi::gtk_stack_switcher_get_type(),
}
}
impl StackSwitcher {
#[cfg(feature = "3.10")]
pub fn new() -> StackSwitcher {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_stack_switcher_new()).downcast_unchecked()
}
}
#[cfg(feature = "3.10")]
pub fn get_stack(&self) -> Option<Stack> {
unsafe {
from_glib_none(ffi::gtk_stack_switcher_get_stack(self.to_glib_none().0))
}
}
#[cfg(feature = "3.10")]
pub fn set_stack(&self, stack: Option<&Stack>) |
}
| {
unsafe {
ffi::gtk_stack_switcher_set_stack(self.to_glib_none().0, stack.to_glib_none().0);
}
} | identifier_body |
stack_switcher.rs | // This file was generated by gir (17af302) from gir-files (11e0e6d)
// DO NOT EDIT
use Box;
use Buildable;
use Container;
use Orientable;
#[cfg(feature = "3.10")]
use Stack;
use Widget;
use ffi;
use glib::object::Downcast;
use glib::translate::*;
glib_wrapper! {
pub struct StackSwitcher(Object<ffi::GtkStackSwitcher>): Widget, Container, Box, Buildable, Orientable;
match fn {
get_type => || ffi::gtk_stack_switcher_get_type(),
}
}
impl StackSwitcher {
#[cfg(feature = "3.10")]
pub fn new() -> StackSwitcher {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_stack_switcher_new()).downcast_unchecked()
}
}
#[cfg(feature = "3.10")]
pub fn | (&self) -> Option<Stack> {
unsafe {
from_glib_none(ffi::gtk_stack_switcher_get_stack(self.to_glib_none().0))
}
}
#[cfg(feature = "3.10")]
pub fn set_stack(&self, stack: Option<&Stack>) {
unsafe {
ffi::gtk_stack_switcher_set_stack(self.to_glib_none().0, stack.to_glib_none().0);
}
}
}
| get_stack | identifier_name |
stack_switcher.rs | // This file was generated by gir (17af302) from gir-files (11e0e6d)
// DO NOT EDIT
use Box;
use Buildable;
use Container;
use Orientable;
#[cfg(feature = "3.10")]
use Stack;
use Widget;
use ffi;
use glib::object::Downcast;
use glib::translate::*;
glib_wrapper! {
pub struct StackSwitcher(Object<ffi::GtkStackSwitcher>): Widget, Container, Box, Buildable, Orientable;
match fn { | }
}
impl StackSwitcher {
#[cfg(feature = "3.10")]
pub fn new() -> StackSwitcher {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_stack_switcher_new()).downcast_unchecked()
}
}
#[cfg(feature = "3.10")]
pub fn get_stack(&self) -> Option<Stack> {
unsafe {
from_glib_none(ffi::gtk_stack_switcher_get_stack(self.to_glib_none().0))
}
}
#[cfg(feature = "3.10")]
pub fn set_stack(&self, stack: Option<&Stack>) {
unsafe {
ffi::gtk_stack_switcher_set_stack(self.to_glib_none().0, stack.to_glib_none().0);
}
}
} | get_type => || ffi::gtk_stack_switcher_get_type(), | random_line_split |
index.tsx | import { color } from "@artsy/palette"
import { avantgarde } from "@artsy/reaction/dist/Assets/Fonts"
import { IconEditEmbed } from "@artsy/reaction/dist/Components/Publishing/Icon/IconEditEmbed"
import { IconEditImages } from "@artsy/reaction/dist/Components/Publishing/Icon/IconEditImages"
import { IconEditSection } from "@artsy/reaction/dist/Components/Publishing/Icon/IconEditSection"
import { IconEditText } from "@artsy/reaction/dist/Components/Publishing/Icon/IconEditText"
import { IconEditVideo } from "@artsy/reaction/dist/Components/Publishing/Icon/IconEditVideo"
import { IconHeroImage } from "@artsy/reaction/dist/Components/Publishing/Icon/IconHeroImage"
import { IconHeroVideo } from "@artsy/reaction/dist/Components/Publishing/Icon/IconHeroVideo"
import { getSectionWidth } from "@artsy/reaction/dist/Components/Publishing/Sections/SectionContainer"
import {
ArticleData,
SectionData,
} from "@artsy/reaction/dist/Components/Publishing/Typings"
import { newHeroSection, newSection } from "client/actions/edit/sectionActions"
import React, { Component } from "react"
import { connect } from "react-redux"
import styled from "styled-components"
interface Props {
article: ArticleData
firstSection?: boolean
index: number
isEditing?: boolean
isHero?: boolean
isPartnerChannel: boolean
newHeroSectionAction: (type: string) => void
newSectionAction: (type: string, index: number) => void
onSetEditing: (editing: boolean | number) => void
sections: SectionData[]
}
export class SectionTool extends Component<Props> {
state = {
isOpen: false,
}
toggleOpen = () => {
this.setState({ isOpen: !this.state.isOpen })
}
newSection = type => {
const { index, newSectionAction } = this.props
newSectionAction(type, index + 1)
this.setState({ isOpen: false })
}
setHero = type => {
const { newHeroSectionAction, onSetEditing } = this.props
newHeroSectionAction(type)
this.setState({ isOpen: false })
onSetEditing(true)
}
renderHeroMenu() {
if (this.state.isOpen) {
return (
<SectionToolMenu>
<SectionToolMenuItem onClick={() => this.setHero("image_collection")}>
<IconHeroImage />
Large Format Image
</SectionToolMenuItem>
<SectionToolMenuItem onClick={() => this.setHero("video")}>
<IconHeroVideo />
Large Format Video
</SectionToolMenuItem>
</SectionToolMenu>
)
}
}
renderSectionMenu() {
const {
article: { layout },
firstSection,
isPartnerChannel,
} = this.props
const { isOpen } = this.state
const isNews = layout === "news"
if (isOpen) {
return (
<SectionToolMenu>
<SectionToolMenuItem onClick={() => this.newSection("text")}>
<IconEditText />
Text
</SectionToolMenuItem>
<SectionToolMenuItem
onClick={() => this.newSection("image_collection")}
>
<IconEditImages />
{isNews ? "Image" : "Images"}
</SectionToolMenuItem>
{!isNews && (
<SectionToolMenuItem onClick={() => this.newSection("video")}>
<IconEditVideo />
Video
</SectionToolMenuItem>
)}
{!isPartnerChannel &&
!isNews && (
<SectionToolMenuItem onClick={() => this.newSection("embed")}>
<IconEditEmbed />
Embed
</SectionToolMenuItem>
)}
{layout !== "classic" &&
!firstSection && (
<SectionToolMenuItem
onClick={() => this.newSection("social_embed")}
>
<IconEditEmbed />
Social Embed
</SectionToolMenuItem>
)}
</SectionToolMenu>
)
}
}
render() {
const {
article,
firstSection,
index,
isEditing,
isHero,
sections,
} = this.props
const { isOpen } = this.state
const isFirstSection = sections && firstSection && sections.length === 0
const isLastSection = sections && index === sections.length - 1
const sectionWidth = getSectionWidth(undefined, article.layout)
const isVisible = isFirstSection || isLastSection || isHero
return (
<SectionToolContainer
isEditing={isEditing}
isOpen={isOpen}
isHero={isHero}
isVisible={isVisible}
width={sectionWidth}
>
<SectionToolIcon
width={sectionWidth}
isHero={isHero}
isVisible={isVisible}
isOpen={isOpen}
onClick={this.toggleOpen}
>
<IconEditSection
fill={isOpen || !isHero ? "#000" : color("black10")}
isClosing={isOpen}
/>
</SectionToolIcon>
{isHero ? this.renderHeroMenu() : this.renderSectionMenu()}
</SectionToolContainer> | )
}
}
const mapStateToProps = state => ({
article: state.edit.article,
isPartnerChannel: state.app.isPartnerChannel,
})
const mapDispatchToProps = {
newHeroSectionAction: newHeroSection,
newSectionAction: newSection,
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(SectionTool)
interface SectionToolProps {
width?: string
isEditing?: boolean
isOpen?: boolean
isVisible?: boolean
isHero?: boolean
}
const SectionToolContainer = styled.div<SectionToolProps>`
z-index: 1;
max-height: 0;
position: relative;
margin-left: auto;
margin-right: auto;
max-width: ${props => (props.width ? props.width : "100%")};
width: 100%;
transition: max-height 0.15s linear, opacity 0.15s linear;
${props =>
props.isEditing &&
`
z-index: -1;
`} &:last-child {
opacity: 1;
margin-top: 15px;
}
${props =>
props.isOpen &&
`
max-height: inherit;
`};
${props =>
props.isVisible &&
!props.isHero &&
`
padding-bottom: 40px;
`};
`
export const SectionToolIcon = styled.div<SectionToolProps>`
${avantgarde("s13")};
position: relative;
cursor: pointer;
top: -6px;
opacity: 0;
transition: opacity 0.15s ease-out;
svg {
z-index: 1;
width: 40px;
height: 40px;
position: absolute;
left: -18px;
top: -13px;
}
path {
transition: fill 0.1s;
}
&::before {
content: ".";
border-top: 2px solid black;
position: absolute;
top: 6px;
left: 16px;
max-width: 0;
width: calc(${props => props.width} - 16px);
color: transparent;
opacity: 0;
transition: opacity 0.15s ease-out, max-width 0.15s ease-out;
height: 20px;
z-index: 2;
}
${props =>
(props.isVisible || props.isOpen) &&
`
opacity: 1;
`};
${props =>
props.isVisible &&
!props.isOpen &&
!props.isHero &&
`
&::after {
content: 'Add a section';
width: 150px;
display: block;
float: left;
position: absolute;
top: -3px;
left: 35px;
}
`} &:hover {
opacity: 1;
path {
fill: black;
}
&::before {
max-width: 100%;
opacity: 1;
}
&::after {
display: none;
}
}
`
const SectionToolMenu = styled.ul`
display: flex;
border: 2px solid black;
position: relative;
left: 0;
width: 100%;
overflow: hidden;
`
const SectionToolMenuItem = styled.li`
${avantgarde("s11")};
background: white;
height: 89px;
border-right: 1px solid ${color("black10")};
border-bottom: 1px solid ${color("black10")};
vertical-align: top;
display: flex;
flex: 1;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: pointer;
position: relative;
&:last-child {
border-right: none;
}
svg {
max-width: 40px;
max-height: 35px;
height: 35px;
margin-bottom: 5px;
}
` | random_line_split |
|
index.tsx | import { color } from "@artsy/palette"
import { avantgarde } from "@artsy/reaction/dist/Assets/Fonts"
import { IconEditEmbed } from "@artsy/reaction/dist/Components/Publishing/Icon/IconEditEmbed"
import { IconEditImages } from "@artsy/reaction/dist/Components/Publishing/Icon/IconEditImages"
import { IconEditSection } from "@artsy/reaction/dist/Components/Publishing/Icon/IconEditSection"
import { IconEditText } from "@artsy/reaction/dist/Components/Publishing/Icon/IconEditText"
import { IconEditVideo } from "@artsy/reaction/dist/Components/Publishing/Icon/IconEditVideo"
import { IconHeroImage } from "@artsy/reaction/dist/Components/Publishing/Icon/IconHeroImage"
import { IconHeroVideo } from "@artsy/reaction/dist/Components/Publishing/Icon/IconHeroVideo"
import { getSectionWidth } from "@artsy/reaction/dist/Components/Publishing/Sections/SectionContainer"
import {
ArticleData,
SectionData,
} from "@artsy/reaction/dist/Components/Publishing/Typings"
import { newHeroSection, newSection } from "client/actions/edit/sectionActions"
import React, { Component } from "react"
import { connect } from "react-redux"
import styled from "styled-components"
interface Props {
article: ArticleData
firstSection?: boolean
index: number
isEditing?: boolean
isHero?: boolean
isPartnerChannel: boolean
newHeroSectionAction: (type: string) => void
newSectionAction: (type: string, index: number) => void
onSetEditing: (editing: boolean | number) => void
sections: SectionData[]
}
export class SectionTool extends Component<Props> {
state = {
isOpen: false,
}
toggleOpen = () => {
this.setState({ isOpen: !this.state.isOpen })
}
newSection = type => {
const { index, newSectionAction } = this.props
newSectionAction(type, index + 1)
this.setState({ isOpen: false })
}
setHero = type => {
const { newHeroSectionAction, onSetEditing } = this.props
newHeroSectionAction(type)
this.setState({ isOpen: false })
onSetEditing(true)
}
renderHeroMenu() {
if (this.state.isOpen) | >
<IconHeroVideo />
Large Format Video
</SectionToolMenuItem>
</SectionToolMenu>
)
}
}
renderSectionMenu() {
const {
article: { layout },
firstSection,
isPartnerChannel,
} = this.props
const { isOpen } = this.state
const isNews = layout === "news"
if (isOpen) {
return (
<SectionToolMenu>
<SectionToolMenuItem onClick={() => this.newSection("text")}>
<IconEditText />
Text
</SectionToolMenuItem>
<SectionToolMenuItem
onClick={() => this.newSection("image_collection")}
>
<IconEditImages />
{isNews ? "Image" : "Images"}
</SectionToolMenuItem>
{!isNews && (
<SectionToolMenuItem onClick={() => this.newSection("video")}>
<IconEditVideo />
Video
</SectionToolMenuItem>
)}
{!isPartnerChannel &&
!isNews && (
<SectionToolMenuItem onClick={() => this.newSection("embed")}>
<IconEditEmbed />
Embed
</SectionToolMenuItem>
)}
{layout !== "classic" &&
!firstSection && (
<SectionToolMenuItem
onClick={() => this.newSection("social_embed")}
>
<IconEditEmbed />
Social Embed
</SectionToolMenuItem>
)}
</SectionToolMenu>
)
}
}
render() {
const {
article,
firstSection,
index,
isEditing,
isHero,
sections,
} = this.props
const { isOpen } = this.state
const isFirstSection = sections && firstSection && sections.length === 0
const isLastSection = sections && index === sections.length - 1
const sectionWidth = getSectionWidth(undefined, article.layout)
const isVisible = isFirstSection || isLastSection || isHero
return (
<SectionToolContainer
isEditing={isEditing}
isOpen={isOpen}
isHero={isHero}
isVisible={isVisible}
width={sectionWidth}
>
<SectionToolIcon
width={sectionWidth}
isHero={isHero}
isVisible={isVisible}
isOpen={isOpen}
onClick={this.toggleOpen}
>
<IconEditSection
fill={isOpen || !isHero ? "#000" : color("black10")}
isClosing={isOpen}
/>
</SectionToolIcon>
{isHero ? this.renderHeroMenu() : this.renderSectionMenu()}
</SectionToolContainer>
)
}
}
const mapStateToProps = state => ({
article: state.edit.article,
isPartnerChannel: state.app.isPartnerChannel,
})
const mapDispatchToProps = {
newHeroSectionAction: newHeroSection,
newSectionAction: newSection,
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(SectionTool)
interface SectionToolProps {
width?: string
isEditing?: boolean
isOpen?: boolean
isVisible?: boolean
isHero?: boolean
}
const SectionToolContainer = styled.div<SectionToolProps>`
z-index: 1;
max-height: 0;
position: relative;
margin-left: auto;
margin-right: auto;
max-width: ${props => (props.width ? props.width : "100%")};
width: 100%;
transition: max-height 0.15s linear, opacity 0.15s linear;
${props =>
props.isEditing &&
`
z-index: -1;
`} &:last-child {
opacity: 1;
margin-top: 15px;
}
${props =>
props.isOpen &&
`
max-height: inherit;
`};
${props =>
props.isVisible &&
!props.isHero &&
`
padding-bottom: 40px;
`};
`
export const SectionToolIcon = styled.div<SectionToolProps>`
${avantgarde("s13")};
position: relative;
cursor: pointer;
top: -6px;
opacity: 0;
transition: opacity 0.15s ease-out;
svg {
z-index: 1;
width: 40px;
height: 40px;
position: absolute;
left: -18px;
top: -13px;
}
path {
transition: fill 0.1s;
}
&::before {
content: ".";
border-top: 2px solid black;
position: absolute;
top: 6px;
left: 16px;
max-width: 0;
width: calc(${props => props.width} - 16px);
color: transparent;
opacity: 0;
transition: opacity 0.15s ease-out, max-width 0.15s ease-out;
height: 20px;
z-index: 2;
}
${props =>
(props.isVisible || props.isOpen) &&
`
opacity: 1;
`};
${props =>
props.isVisible &&
!props.isOpen &&
!props.isHero &&
`
&::after {
content: 'Add a section';
width: 150px;
display: block;
float: left;
position: absolute;
top: -3px;
left: 35px;
}
`} &:hover {
opacity: 1;
path {
fill: black;
}
&::before {
max-width: 100%;
opacity: 1;
}
&::after {
display: none;
}
}
`
const SectionToolMenu = styled.ul`
display: flex;
border: 2px solid black;
position: relative;
left: 0;
width: 100%;
overflow: hidden;
`
const SectionToolMenuItem = styled.li`
${avantgarde("s11")};
background: white;
height: 89px;
border-right: 1px solid ${color("black10")};
border-bottom: 1px solid ${color("black10")};
vertical-align: top;
display: flex;
flex: 1;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: pointer;
position: relative;
&:last-child {
border-right: none;
}
svg {
max-width: 40px;
max-height: 35px;
height: 35px;
margin-bottom: 5px;
}
`
| {
return (
<SectionToolMenu>
<SectionToolMenuItem onClick={() => this.setHero("image_collection")}>
<IconHeroImage />
Large Format Image
</SectionToolMenuItem>
<SectionToolMenuItem onClick={() => this.setHero("video")} | conditional_block |
index.tsx | import { color } from "@artsy/palette"
import { avantgarde } from "@artsy/reaction/dist/Assets/Fonts"
import { IconEditEmbed } from "@artsy/reaction/dist/Components/Publishing/Icon/IconEditEmbed"
import { IconEditImages } from "@artsy/reaction/dist/Components/Publishing/Icon/IconEditImages"
import { IconEditSection } from "@artsy/reaction/dist/Components/Publishing/Icon/IconEditSection"
import { IconEditText } from "@artsy/reaction/dist/Components/Publishing/Icon/IconEditText"
import { IconEditVideo } from "@artsy/reaction/dist/Components/Publishing/Icon/IconEditVideo"
import { IconHeroImage } from "@artsy/reaction/dist/Components/Publishing/Icon/IconHeroImage"
import { IconHeroVideo } from "@artsy/reaction/dist/Components/Publishing/Icon/IconHeroVideo"
import { getSectionWidth } from "@artsy/reaction/dist/Components/Publishing/Sections/SectionContainer"
import {
ArticleData,
SectionData,
} from "@artsy/reaction/dist/Components/Publishing/Typings"
import { newHeroSection, newSection } from "client/actions/edit/sectionActions"
import React, { Component } from "react"
import { connect } from "react-redux"
import styled from "styled-components"
interface Props {
article: ArticleData
firstSection?: boolean
index: number
isEditing?: boolean
isHero?: boolean
isPartnerChannel: boolean
newHeroSectionAction: (type: string) => void
newSectionAction: (type: string, index: number) => void
onSetEditing: (editing: boolean | number) => void
sections: SectionData[]
}
export class SectionTool extends Component<Props> {
state = {
isOpen: false,
}
toggleOpen = () => {
this.setState({ isOpen: !this.state.isOpen })
}
newSection = type => {
const { index, newSectionAction } = this.props
newSectionAction(type, index + 1)
this.setState({ isOpen: false })
}
setHero = type => {
const { newHeroSectionAction, onSetEditing } = this.props
newHeroSectionAction(type)
this.setState({ isOpen: false })
onSetEditing(true)
}
| () {
if (this.state.isOpen) {
return (
<SectionToolMenu>
<SectionToolMenuItem onClick={() => this.setHero("image_collection")}>
<IconHeroImage />
Large Format Image
</SectionToolMenuItem>
<SectionToolMenuItem onClick={() => this.setHero("video")}>
<IconHeroVideo />
Large Format Video
</SectionToolMenuItem>
</SectionToolMenu>
)
}
}
renderSectionMenu() {
const {
article: { layout },
firstSection,
isPartnerChannel,
} = this.props
const { isOpen } = this.state
const isNews = layout === "news"
if (isOpen) {
return (
<SectionToolMenu>
<SectionToolMenuItem onClick={() => this.newSection("text")}>
<IconEditText />
Text
</SectionToolMenuItem>
<SectionToolMenuItem
onClick={() => this.newSection("image_collection")}
>
<IconEditImages />
{isNews ? "Image" : "Images"}
</SectionToolMenuItem>
{!isNews && (
<SectionToolMenuItem onClick={() => this.newSection("video")}>
<IconEditVideo />
Video
</SectionToolMenuItem>
)}
{!isPartnerChannel &&
!isNews && (
<SectionToolMenuItem onClick={() => this.newSection("embed")}>
<IconEditEmbed />
Embed
</SectionToolMenuItem>
)}
{layout !== "classic" &&
!firstSection && (
<SectionToolMenuItem
onClick={() => this.newSection("social_embed")}
>
<IconEditEmbed />
Social Embed
</SectionToolMenuItem>
)}
</SectionToolMenu>
)
}
}
render() {
const {
article,
firstSection,
index,
isEditing,
isHero,
sections,
} = this.props
const { isOpen } = this.state
const isFirstSection = sections && firstSection && sections.length === 0
const isLastSection = sections && index === sections.length - 1
const sectionWidth = getSectionWidth(undefined, article.layout)
const isVisible = isFirstSection || isLastSection || isHero
return (
<SectionToolContainer
isEditing={isEditing}
isOpen={isOpen}
isHero={isHero}
isVisible={isVisible}
width={sectionWidth}
>
<SectionToolIcon
width={sectionWidth}
isHero={isHero}
isVisible={isVisible}
isOpen={isOpen}
onClick={this.toggleOpen}
>
<IconEditSection
fill={isOpen || !isHero ? "#000" : color("black10")}
isClosing={isOpen}
/>
</SectionToolIcon>
{isHero ? this.renderHeroMenu() : this.renderSectionMenu()}
</SectionToolContainer>
)
}
}
const mapStateToProps = state => ({
article: state.edit.article,
isPartnerChannel: state.app.isPartnerChannel,
})
const mapDispatchToProps = {
newHeroSectionAction: newHeroSection,
newSectionAction: newSection,
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(SectionTool)
interface SectionToolProps {
width?: string
isEditing?: boolean
isOpen?: boolean
isVisible?: boolean
isHero?: boolean
}
const SectionToolContainer = styled.div<SectionToolProps>`
z-index: 1;
max-height: 0;
position: relative;
margin-left: auto;
margin-right: auto;
max-width: ${props => (props.width ? props.width : "100%")};
width: 100%;
transition: max-height 0.15s linear, opacity 0.15s linear;
${props =>
props.isEditing &&
`
z-index: -1;
`} &:last-child {
opacity: 1;
margin-top: 15px;
}
${props =>
props.isOpen &&
`
max-height: inherit;
`};
${props =>
props.isVisible &&
!props.isHero &&
`
padding-bottom: 40px;
`};
`
export const SectionToolIcon = styled.div<SectionToolProps>`
${avantgarde("s13")};
position: relative;
cursor: pointer;
top: -6px;
opacity: 0;
transition: opacity 0.15s ease-out;
svg {
z-index: 1;
width: 40px;
height: 40px;
position: absolute;
left: -18px;
top: -13px;
}
path {
transition: fill 0.1s;
}
&::before {
content: ".";
border-top: 2px solid black;
position: absolute;
top: 6px;
left: 16px;
max-width: 0;
width: calc(${props => props.width} - 16px);
color: transparent;
opacity: 0;
transition: opacity 0.15s ease-out, max-width 0.15s ease-out;
height: 20px;
z-index: 2;
}
${props =>
(props.isVisible || props.isOpen) &&
`
opacity: 1;
`};
${props =>
props.isVisible &&
!props.isOpen &&
!props.isHero &&
`
&::after {
content: 'Add a section';
width: 150px;
display: block;
float: left;
position: absolute;
top: -3px;
left: 35px;
}
`} &:hover {
opacity: 1;
path {
fill: black;
}
&::before {
max-width: 100%;
opacity: 1;
}
&::after {
display: none;
}
}
`
const SectionToolMenu = styled.ul`
display: flex;
border: 2px solid black;
position: relative;
left: 0;
width: 100%;
overflow: hidden;
`
const SectionToolMenuItem = styled.li`
${avantgarde("s11")};
background: white;
height: 89px;
border-right: 1px solid ${color("black10")};
border-bottom: 1px solid ${color("black10")};
vertical-align: top;
display: flex;
flex: 1;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: pointer;
position: relative;
&:last-child {
border-right: none;
}
svg {
max-width: 40px;
max-height: 35px;
height: 35px;
margin-bottom: 5px;
}
`
| renderHeroMenu | identifier_name |
process-args.ts | import { symbol } from 'ember-utils';
import { MUTABLE_CELL } from 'ember-views';
import { CapturedNamedArguments } from '@glimmer/runtime';
import { ARGS } from '../component';
import { ACTION } from '../helpers/action';
import { UPDATE } from './references';
// ComponentArgs takes EvaluatedNamedArgs and converts them into the
// inputs needed by CurlyComponents (attrs and props, with mutable
// cells, etc).
export function processComponentArgs(namedArgs: CapturedNamedArguments) {
let keys = namedArgs.names;
let attrs = namedArgs.value();
let props = Object.create(null);
let args = Object.create(null); | for (let i = 0; i < keys.length; i++) {
let name = keys[i];
let ref = namedArgs.get(name);
let value = attrs[name];
if (typeof value === 'function' && value[ACTION]) {
attrs[name] = value;
} else if (ref[UPDATE]) {
attrs[name] = new MutableCell(ref, value);
}
args[name] = ref;
props[name] = value;
}
props.attrs = attrs;
return props;
}
const REF = symbol('REF');
class MutableCell {
public value: any;
constructor(ref: any, value: any) {
this[MUTABLE_CELL] = true;
this[REF] = ref;
this.value = value;
}
update(val: any) {
this[REF][UPDATE](val);
}
} |
props[ARGS] = args;
| random_line_split |
process-args.ts | import { symbol } from 'ember-utils';
import { MUTABLE_CELL } from 'ember-views';
import { CapturedNamedArguments } from '@glimmer/runtime';
import { ARGS } from '../component';
import { ACTION } from '../helpers/action';
import { UPDATE } from './references';
// ComponentArgs takes EvaluatedNamedArgs and converts them into the
// inputs needed by CurlyComponents (attrs and props, with mutable
// cells, etc).
export function | (namedArgs: CapturedNamedArguments) {
let keys = namedArgs.names;
let attrs = namedArgs.value();
let props = Object.create(null);
let args = Object.create(null);
props[ARGS] = args;
for (let i = 0; i < keys.length; i++) {
let name = keys[i];
let ref = namedArgs.get(name);
let value = attrs[name];
if (typeof value === 'function' && value[ACTION]) {
attrs[name] = value;
} else if (ref[UPDATE]) {
attrs[name] = new MutableCell(ref, value);
}
args[name] = ref;
props[name] = value;
}
props.attrs = attrs;
return props;
}
const REF = symbol('REF');
class MutableCell {
public value: any;
constructor(ref: any, value: any) {
this[MUTABLE_CELL] = true;
this[REF] = ref;
this.value = value;
}
update(val: any) {
this[REF][UPDATE](val);
}
}
| processComponentArgs | identifier_name |
paths.rs | use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::{self, File, OpenOptions};
use std::io;
use std::io::prelude::*;
use std::iter;
use std::path::{Component, Path, PathBuf};
use filetime::FileTime;
use crate::util::errors::{CargoResult, CargoResultExt};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CargoResult<OsString> {
env::join_paths(paths.iter())
.chain_err(|| {
let paths = paths.iter().map(Path::new).collect::<Vec<_>>();
format!("failed to join path array: {:?}", paths)
})
.chain_err(|| {
format!(
"failed to join search paths together\n\
Does ${} have an unterminated quote character?",
env
)
})
}
pub fn dylib_path_envvar() -> &'static str {
if cfg!(windows) {
"PATH"
} else if cfg!(target_os = "macos") {
// When loading and linking a dynamic library or bundle, dlopen
// searches in LD_LIBRARY_PATH, DYLD_LIBRARY_PATH, PWD, and
// DYLD_FALLBACK_LIBRARY_PATH.
// In the Mach-O format, a dynamic library has an "install path."
// Clients linking against the library record this path, and the
// dynamic linker, dyld, uses it to locate the library.
// dyld searches DYLD_LIBRARY_PATH *before* the install path.
// dyld searches DYLD_FALLBACK_LIBRARY_PATH only if it cannot
// find the library in the install path.
// Setting DYLD_LIBRARY_PATH can easily have unintended
// consequences.
//
// Also, DYLD_LIBRARY_PATH appears to have significant performance
// penalty starting in 10.13. Cargo's testsuite ran more than twice as
// slow with it on CI.
"DYLD_FALLBACK_LIBRARY_PATH"
} else {
"LD_LIBRARY_PATH"
}
}
pub fn dylib_path() -> Vec<PathBuf> {
match env::var_os(dylib_path_envvar()) {
Some(var) => env::split_paths(&var).collect(),
None => Vec::new(),
}
}
pub fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => {
ret.push(component.as_os_str());
}
Component::CurDir => {}
Component::ParentDir => {
ret.pop();
}
Component::Normal(c) => {
ret.push(c);
}
}
}
ret
}
pub fn resolve_executable(exec: &Path) -> CargoResult<PathBuf> {
if exec.components().count() == 1 {
let paths = env::var_os("PATH").ok_or_else(|| anyhow::format_err!("no PATH"))?;
let candidates = env::split_paths(&paths).flat_map(|path| {
let candidate = path.join(&exec);
let with_exe = if env::consts::EXE_EXTENSION == "" {
None
} else {
Some(candidate.with_extension(env::consts::EXE_EXTENSION))
};
iter::once(candidate).chain(with_exe)
});
for candidate in candidates {
if candidate.is_file() {
// PATH may have a component like "." in it, so we still need to
// canonicalize.
return Ok(candidate.canonicalize()?);
}
}
anyhow::bail!("no executable for `{}` found in PATH", exec.display())
} else {
Ok(exec.canonicalize()?)
}
}
pub fn read(path: &Path) -> CargoResult<String> {
match String::from_utf8(read_bytes(path)?) {
Ok(s) => Ok(s),
Err(_) => anyhow::bail!("path at `{}` was not valid utf-8", path.display()),
}
}
pub fn read_bytes(path: &Path) -> CargoResult<Vec<u8>> {
let res = (|| -> CargoResult<_> {
let mut ret = Vec::new();
let mut f = File::open(path)?;
if let Ok(m) = f.metadata() {
ret.reserve(m.len() as usize + 1);
}
f.read_to_end(&mut ret)?;
Ok(ret)
})()
.chain_err(|| format!("failed to read `{}`", path.display()))?;
Ok(res)
}
pub fn write(path: &Path, contents: &[u8]) -> CargoResult<()> {
(|| -> CargoResult<()> {
let mut f = File::create(path)?;
f.write_all(contents)?;
Ok(())
})()
.chain_err(|| format!("failed to write `{}`", path.display()))?;
Ok(())
}
pub fn write_if_changed<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> CargoResult<()> {
(|| -> CargoResult<()> {
let contents = contents.as_ref();
let mut f = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)?;
let mut orig = Vec::new();
f.read_to_end(&mut orig)?;
if orig != contents {
f.set_len(0)?;
f.seek(io::SeekFrom::Start(0))?;
f.write_all(contents)?;
}
Ok(())
})()
.chain_err(|| format!("failed to write `{}`", path.as_ref().display()))?;
Ok(())
}
pub fn append(path: &Path, contents: &[u8]) -> CargoResult<()> {
(|| -> CargoResult<()> {
let mut f = OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(path)?;
f.write_all(contents)?;
Ok(())
})()
.chain_err(|| format!("failed to write `{}`", path.display()))?;
Ok(())
}
pub fn mtime(path: &Path) -> CargoResult<FileTime> {
let meta = fs::metadata(path).chain_err(|| format!("failed to stat `{}`", path.display()))?;
Ok(FileTime::from_last_modification_time(&meta))
}
/// Record the current time on the filesystem (using the filesystem's clock)
/// using a file at the given directory. Returns the current time.
pub fn set_invocation_time(path: &Path) -> CargoResult<FileTime> {
// note that if `FileTime::from_system_time(SystemTime::now());` is determined to be sufficient,
// then this can be removed.
let timestamp = path.join("invoked.timestamp");
write(
×tamp,
b"This file has an mtime of when this was started.",
)?;
let ft = mtime(×tamp)?;
log::debug!("invocation time for {:?} is {}", path, ft);
Ok(ft)
}
#[cfg(unix)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
use std::os::unix::prelude::*;
Ok(path.as_os_str().as_bytes())
}
#[cfg(windows)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
match path.as_os_str().to_str() {
Some(s) => Ok(s.as_bytes()),
None => Err(anyhow::format_err!(
"invalid non-unicode path: {}",
path.display()
)),
}
}
#[cfg(unix)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
use std::os::unix::prelude::*;
Ok(PathBuf::from(OsStr::from_bytes(bytes)))
}
#[cfg(windows)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(bytes) {
Ok(s) => Ok(PathBuf::from(s)),
Err(..) => Err(anyhow::format_err!("invalid non-unicode path")),
}
}
pub fn ancestors(path: &Path) -> PathAncestors<'_> {
PathAncestors::new(path)
}
pub struct PathAncestors<'a> {
current: Option<&'a Path>,
stop_at: Option<PathBuf>,
}
impl<'a> PathAncestors<'a> {
fn | (path: &Path) -> PathAncestors<'_> {
PathAncestors {
current: Some(path),
//HACK: avoid reading `~/.cargo/config` when testing Cargo itself.
stop_at: env::var("__CARGO_TEST_ROOT").ok().map(PathBuf::from),
}
}
}
impl<'a> Iterator for PathAncestors<'a> {
type Item = &'a Path;
fn next(&mut self) -> Option<&'a Path> {
if let Some(path) = self.current {
self.current = path.parent();
if let Some(ref stop_at) = self.stop_at {
if path == stop_at {
self.current = None;
}
}
Some(path)
} else {
None
}
}
}
pub fn create_dir_all(p: impl AsRef<Path>) -> CargoResult<()> {
_create_dir_all(p.as_ref())
}
fn _create_dir_all(p: &Path) -> CargoResult<()> {
fs::create_dir_all(p).chain_err(|| format!("failed to create directory `{}`", p.display()))?;
Ok(())
}
pub fn remove_dir_all<P: AsRef<Path>>(p: P) -> CargoResult<()> {
_remove_dir_all(p.as_ref())
}
fn _remove_dir_all(p: &Path) -> CargoResult<()> {
if p.symlink_metadata()?.file_type().is_symlink() {
return remove_file(p);
}
let entries = p
.read_dir()
.chain_err(|| format!("failed to read directory `{}`", p.display()))?;
for entry in entries {
let entry = entry?;
let path = entry.path();
if entry.file_type()?.is_dir() {
remove_dir_all(&path)?;
} else {
remove_file(&path)?;
}
}
remove_dir(&p)
}
pub fn remove_dir<P: AsRef<Path>>(p: P) -> CargoResult<()> {
_remove_dir(p.as_ref())
}
fn _remove_dir(p: &Path) -> CargoResult<()> {
fs::remove_dir(p).chain_err(|| format!("failed to remove directory `{}`", p.display()))?;
Ok(())
}
pub fn remove_file<P: AsRef<Path>>(p: P) -> CargoResult<()> {
_remove_file(p.as_ref())
}
fn _remove_file(p: &Path) -> CargoResult<()> {
let mut err = match fs::remove_file(p) {
Ok(()) => return Ok(()),
Err(e) => e,
};
if err.kind() == io::ErrorKind::PermissionDenied && set_not_readonly(p).unwrap_or(false) {
match fs::remove_file(p) {
Ok(()) => return Ok(()),
Err(e) => err = e,
}
}
Err(err).chain_err(|| format!("failed to remove file `{}`", p.display()))?;
Ok(())
}
fn set_not_readonly(p: &Path) -> io::Result<bool> {
let mut perms = p.metadata()?.permissions();
if !perms.readonly() {
return Ok(false);
}
perms.set_readonly(false);
fs::set_permissions(p, perms)?;
Ok(true)
}
/// Hardlink (file) or symlink (dir) src to dst if possible, otherwise copy it.
///
/// If the destination already exists, it is removed before linking.
pub fn link_or_copy(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> CargoResult<()> {
let src = src.as_ref();
let dst = dst.as_ref();
_link_or_copy(src, dst)
}
fn _link_or_copy(src: &Path, dst: &Path) -> CargoResult<()> {
log::debug!("linking {} to {}", src.display(), dst.display());
if same_file::is_same_file(src, dst).unwrap_or(false) {
return Ok(());
}
// NB: we can't use dst.exists(), as if dst is a broken symlink,
// dst.exists() will return false. This is problematic, as we still need to
// unlink dst in this case. symlink_metadata(dst).is_ok() will tell us
// whether dst exists *without* following symlinks, which is what we want.
if fs::symlink_metadata(dst).is_ok() {
remove_file(&dst)?;
}
let link_result = if src.is_dir() {
#[cfg(target_os = "redox")]
use std::os::redox::fs::symlink;
#[cfg(unix)]
use std::os::unix::fs::symlink;
#[cfg(windows)]
// FIXME: This should probably panic or have a copy fallback. Symlinks
// are not supported in all windows environments. Currently symlinking
// is only used for .dSYM directories on macos, but this shouldn't be
// accidentally relied upon.
use std::os::windows::fs::symlink_dir as symlink;
let dst_dir = dst.parent().unwrap();
let src = if src.starts_with(dst_dir) {
src.strip_prefix(dst_dir).unwrap()
} else {
src
};
symlink(src, dst)
} else if env::var_os("__CARGO_COPY_DONT_LINK_DO_NOT_USE_THIS").is_some() {
// This is a work-around for a bug in macOS 10.15. When running on
// APFS, there seems to be a strange race condition with
// Gatekeeper where it will forcefully kill a process launched via
// `cargo run` with SIGKILL. Copying seems to avoid the problem.
// This shouldn't affect anyone except Cargo's test suite because
// it is very rare, and only seems to happen under heavy load and
// rapidly creating lots of executables and running them.
// See https://github.com/rust-lang/cargo/issues/7821 for the
// gory details.
fs::copy(src, dst).map(|_| ())
} else {
fs::hard_link(src, dst)
};
link_result
.or_else(|err| {
log::debug!("link failed {}. falling back to fs::copy", err);
fs::copy(src, dst).map(|_| ())
})
.chain_err(|| {
format!(
"failed to link or copy `{}` to `{}`",
src.display(),
dst.display()
)
})?;
Ok(())
}
| new | identifier_name |
paths.rs | use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::{self, File, OpenOptions};
use std::io;
use std::io::prelude::*;
use std::iter;
use std::path::{Component, Path, PathBuf};
use filetime::FileTime;
use crate::util::errors::{CargoResult, CargoResultExt};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CargoResult<OsString> {
env::join_paths(paths.iter())
.chain_err(|| {
let paths = paths.iter().map(Path::new).collect::<Vec<_>>();
format!("failed to join path array: {:?}", paths)
})
.chain_err(|| {
format!(
"failed to join search paths together\n\
Does ${} have an unterminated quote character?",
env
)
})
}
pub fn dylib_path_envvar() -> &'static str {
if cfg!(windows) {
"PATH"
} else if cfg!(target_os = "macos") {
// When loading and linking a dynamic library or bundle, dlopen
// searches in LD_LIBRARY_PATH, DYLD_LIBRARY_PATH, PWD, and
// DYLD_FALLBACK_LIBRARY_PATH.
// In the Mach-O format, a dynamic library has an "install path."
// Clients linking against the library record this path, and the
// dynamic linker, dyld, uses it to locate the library.
// dyld searches DYLD_LIBRARY_PATH *before* the install path.
// dyld searches DYLD_FALLBACK_LIBRARY_PATH only if it cannot
// find the library in the install path.
// Setting DYLD_LIBRARY_PATH can easily have unintended
// consequences.
//
// Also, DYLD_LIBRARY_PATH appears to have significant performance
// penalty starting in 10.13. Cargo's testsuite ran more than twice as
// slow with it on CI.
"DYLD_FALLBACK_LIBRARY_PATH"
} else {
"LD_LIBRARY_PATH"
}
}
pub fn dylib_path() -> Vec<PathBuf> {
match env::var_os(dylib_path_envvar()) {
Some(var) => env::split_paths(&var).collect(),
None => Vec::new(),
}
}
pub fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => {
ret.push(component.as_os_str());
}
Component::CurDir => {}
Component::ParentDir => {
ret.pop();
}
Component::Normal(c) => {
ret.push(c);
}
}
}
ret
}
pub fn resolve_executable(exec: &Path) -> CargoResult<PathBuf> {
if exec.components().count() == 1 {
let paths = env::var_os("PATH").ok_or_else(|| anyhow::format_err!("no PATH"))?;
let candidates = env::split_paths(&paths).flat_map(|path| {
let candidate = path.join(&exec);
let with_exe = if env::consts::EXE_EXTENSION == "" {
None
} else {
Some(candidate.with_extension(env::consts::EXE_EXTENSION))
};
iter::once(candidate).chain(with_exe)
});
for candidate in candidates {
if candidate.is_file() {
// PATH may have a component like "." in it, so we still need to
// canonicalize.
return Ok(candidate.canonicalize()?);
}
}
anyhow::bail!("no executable for `{}` found in PATH", exec.display())
} else {
Ok(exec.canonicalize()?)
}
}
pub fn read(path: &Path) -> CargoResult<String> {
match String::from_utf8(read_bytes(path)?) {
Ok(s) => Ok(s),
Err(_) => anyhow::bail!("path at `{}` was not valid utf-8", path.display()),
}
}
pub fn read_bytes(path: &Path) -> CargoResult<Vec<u8>> {
let res = (|| -> CargoResult<_> {
let mut ret = Vec::new();
let mut f = File::open(path)?;
if let Ok(m) = f.metadata() {
ret.reserve(m.len() as usize + 1);
}
f.read_to_end(&mut ret)?;
Ok(ret)
})()
.chain_err(|| format!("failed to read `{}`", path.display()))?;
Ok(res)
}
pub fn write(path: &Path, contents: &[u8]) -> CargoResult<()> {
(|| -> CargoResult<()> {
let mut f = File::create(path)?;
f.write_all(contents)?;
Ok(())
})()
.chain_err(|| format!("failed to write `{}`", path.display()))?;
Ok(())
}
pub fn write_if_changed<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> CargoResult<()> {
(|| -> CargoResult<()> {
let contents = contents.as_ref();
let mut f = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)?;
let mut orig = Vec::new();
f.read_to_end(&mut orig)?;
if orig != contents {
f.set_len(0)?;
f.seek(io::SeekFrom::Start(0))?;
f.write_all(contents)?;
}
Ok(())
})()
.chain_err(|| format!("failed to write `{}`", path.as_ref().display()))?;
Ok(())
}
pub fn append(path: &Path, contents: &[u8]) -> CargoResult<()> {
(|| -> CargoResult<()> {
let mut f = OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(path)?;
f.write_all(contents)?;
Ok(())
})()
.chain_err(|| format!("failed to write `{}`", path.display()))?;
Ok(())
}
pub fn mtime(path: &Path) -> CargoResult<FileTime> {
let meta = fs::metadata(path).chain_err(|| format!("failed to stat `{}`", path.display()))?;
Ok(FileTime::from_last_modification_time(&meta))
}
/// Record the current time on the filesystem (using the filesystem's clock)
/// using a file at the given directory. Returns the current time.
pub fn set_invocation_time(path: &Path) -> CargoResult<FileTime> |
#[cfg(unix)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
use std::os::unix::prelude::*;
Ok(path.as_os_str().as_bytes())
}
#[cfg(windows)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
match path.as_os_str().to_str() {
Some(s) => Ok(s.as_bytes()),
None => Err(anyhow::format_err!(
"invalid non-unicode path: {}",
path.display()
)),
}
}
#[cfg(unix)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
use std::os::unix::prelude::*;
Ok(PathBuf::from(OsStr::from_bytes(bytes)))
}
#[cfg(windows)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(bytes) {
Ok(s) => Ok(PathBuf::from(s)),
Err(..) => Err(anyhow::format_err!("invalid non-unicode path")),
}
}
pub fn ancestors(path: &Path) -> PathAncestors<'_> {
PathAncestors::new(path)
}
pub struct PathAncestors<'a> {
current: Option<&'a Path>,
stop_at: Option<PathBuf>,
}
impl<'a> PathAncestors<'a> {
fn new(path: &Path) -> PathAncestors<'_> {
PathAncestors {
current: Some(path),
//HACK: avoid reading `~/.cargo/config` when testing Cargo itself.
stop_at: env::var("__CARGO_TEST_ROOT").ok().map(PathBuf::from),
}
}
}
impl<'a> Iterator for PathAncestors<'a> {
type Item = &'a Path;
fn next(&mut self) -> Option<&'a Path> {
if let Some(path) = self.current {
self.current = path.parent();
if let Some(ref stop_at) = self.stop_at {
if path == stop_at {
self.current = None;
}
}
Some(path)
} else {
None
}
}
}
pub fn create_dir_all(p: impl AsRef<Path>) -> CargoResult<()> {
_create_dir_all(p.as_ref())
}
fn _create_dir_all(p: &Path) -> CargoResult<()> {
fs::create_dir_all(p).chain_err(|| format!("failed to create directory `{}`", p.display()))?;
Ok(())
}
pub fn remove_dir_all<P: AsRef<Path>>(p: P) -> CargoResult<()> {
_remove_dir_all(p.as_ref())
}
fn _remove_dir_all(p: &Path) -> CargoResult<()> {
if p.symlink_metadata()?.file_type().is_symlink() {
return remove_file(p);
}
let entries = p
.read_dir()
.chain_err(|| format!("failed to read directory `{}`", p.display()))?;
for entry in entries {
let entry = entry?;
let path = entry.path();
if entry.file_type()?.is_dir() {
remove_dir_all(&path)?;
} else {
remove_file(&path)?;
}
}
remove_dir(&p)
}
pub fn remove_dir<P: AsRef<Path>>(p: P) -> CargoResult<()> {
_remove_dir(p.as_ref())
}
fn _remove_dir(p: &Path) -> CargoResult<()> {
fs::remove_dir(p).chain_err(|| format!("failed to remove directory `{}`", p.display()))?;
Ok(())
}
pub fn remove_file<P: AsRef<Path>>(p: P) -> CargoResult<()> {
_remove_file(p.as_ref())
}
fn _remove_file(p: &Path) -> CargoResult<()> {
let mut err = match fs::remove_file(p) {
Ok(()) => return Ok(()),
Err(e) => e,
};
if err.kind() == io::ErrorKind::PermissionDenied && set_not_readonly(p).unwrap_or(false) {
match fs::remove_file(p) {
Ok(()) => return Ok(()),
Err(e) => err = e,
}
}
Err(err).chain_err(|| format!("failed to remove file `{}`", p.display()))?;
Ok(())
}
fn set_not_readonly(p: &Path) -> io::Result<bool> {
let mut perms = p.metadata()?.permissions();
if !perms.readonly() {
return Ok(false);
}
perms.set_readonly(false);
fs::set_permissions(p, perms)?;
Ok(true)
}
/// Hardlink (file) or symlink (dir) src to dst if possible, otherwise copy it.
///
/// If the destination already exists, it is removed before linking.
pub fn link_or_copy(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> CargoResult<()> {
let src = src.as_ref();
let dst = dst.as_ref();
_link_or_copy(src, dst)
}
fn _link_or_copy(src: &Path, dst: &Path) -> CargoResult<()> {
log::debug!("linking {} to {}", src.display(), dst.display());
if same_file::is_same_file(src, dst).unwrap_or(false) {
return Ok(());
}
// NB: we can't use dst.exists(), as if dst is a broken symlink,
// dst.exists() will return false. This is problematic, as we still need to
// unlink dst in this case. symlink_metadata(dst).is_ok() will tell us
// whether dst exists *without* following symlinks, which is what we want.
if fs::symlink_metadata(dst).is_ok() {
remove_file(&dst)?;
}
let link_result = if src.is_dir() {
#[cfg(target_os = "redox")]
use std::os::redox::fs::symlink;
#[cfg(unix)]
use std::os::unix::fs::symlink;
#[cfg(windows)]
// FIXME: This should probably panic or have a copy fallback. Symlinks
// are not supported in all windows environments. Currently symlinking
// is only used for .dSYM directories on macos, but this shouldn't be
// accidentally relied upon.
use std::os::windows::fs::symlink_dir as symlink;
let dst_dir = dst.parent().unwrap();
let src = if src.starts_with(dst_dir) {
src.strip_prefix(dst_dir).unwrap()
} else {
src
};
symlink(src, dst)
} else if env::var_os("__CARGO_COPY_DONT_LINK_DO_NOT_USE_THIS").is_some() {
// This is a work-around for a bug in macOS 10.15. When running on
// APFS, there seems to be a strange race condition with
// Gatekeeper where it will forcefully kill a process launched via
// `cargo run` with SIGKILL. Copying seems to avoid the problem.
// This shouldn't affect anyone except Cargo's test suite because
// it is very rare, and only seems to happen under heavy load and
// rapidly creating lots of executables and running them.
// See https://github.com/rust-lang/cargo/issues/7821 for the
// gory details.
fs::copy(src, dst).map(|_| ())
} else {
fs::hard_link(src, dst)
};
link_result
.or_else(|err| {
log::debug!("link failed {}. falling back to fs::copy", err);
fs::copy(src, dst).map(|_| ())
})
.chain_err(|| {
format!(
"failed to link or copy `{}` to `{}`",
src.display(),
dst.display()
)
})?;
Ok(())
}
| {
// note that if `FileTime::from_system_time(SystemTime::now());` is determined to be sufficient,
// then this can be removed.
let timestamp = path.join("invoked.timestamp");
write(
×tamp,
b"This file has an mtime of when this was started.",
)?;
let ft = mtime(×tamp)?;
log::debug!("invocation time for {:?} is {}", path, ft);
Ok(ft)
} | identifier_body |
paths.rs | use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::{self, File, OpenOptions};
use std::io;
use std::io::prelude::*;
use std::iter;
use std::path::{Component, Path, PathBuf};
use filetime::FileTime;
use crate::util::errors::{CargoResult, CargoResultExt};
pub fn join_paths<T: AsRef<OsStr>>(paths: &[T], env: &str) -> CargoResult<OsString> {
env::join_paths(paths.iter())
.chain_err(|| {
let paths = paths.iter().map(Path::new).collect::<Vec<_>>();
format!("failed to join path array: {:?}", paths)
})
.chain_err(|| {
format!(
"failed to join search paths together\n\
Does ${} have an unterminated quote character?",
env
)
})
}
pub fn dylib_path_envvar() -> &'static str {
if cfg!(windows) {
"PATH"
} else if cfg!(target_os = "macos") {
// When loading and linking a dynamic library or bundle, dlopen
// searches in LD_LIBRARY_PATH, DYLD_LIBRARY_PATH, PWD, and
// DYLD_FALLBACK_LIBRARY_PATH.
// In the Mach-O format, a dynamic library has an "install path."
// Clients linking against the library record this path, and the
// dynamic linker, dyld, uses it to locate the library.
// dyld searches DYLD_LIBRARY_PATH *before* the install path.
// dyld searches DYLD_FALLBACK_LIBRARY_PATH only if it cannot
// find the library in the install path.
// Setting DYLD_LIBRARY_PATH can easily have unintended
// consequences.
//
// Also, DYLD_LIBRARY_PATH appears to have significant performance
// penalty starting in 10.13. Cargo's testsuite ran more than twice as
// slow with it on CI.
"DYLD_FALLBACK_LIBRARY_PATH"
} else {
"LD_LIBRARY_PATH"
}
}
pub fn dylib_path() -> Vec<PathBuf> {
match env::var_os(dylib_path_envvar()) {
Some(var) => env::split_paths(&var).collect(),
None => Vec::new(),
}
}
pub fn normalize_path(path: &Path) -> PathBuf {
let mut components = path.components().peekable();
let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
components.next();
PathBuf::from(c.as_os_str())
} else {
PathBuf::new()
};
for component in components {
match component {
Component::Prefix(..) => unreachable!(),
Component::RootDir => {
ret.push(component.as_os_str());
}
Component::CurDir => {}
Component::ParentDir => {
ret.pop();
}
Component::Normal(c) => {
ret.push(c);
}
}
}
ret
}
pub fn resolve_executable(exec: &Path) -> CargoResult<PathBuf> {
if exec.components().count() == 1 {
let paths = env::var_os("PATH").ok_or_else(|| anyhow::format_err!("no PATH"))?;
let candidates = env::split_paths(&paths).flat_map(|path| {
let candidate = path.join(&exec);
let with_exe = if env::consts::EXE_EXTENSION == "" {
None
} else {
Some(candidate.with_extension(env::consts::EXE_EXTENSION))
};
iter::once(candidate).chain(with_exe)
});
for candidate in candidates {
if candidate.is_file() {
// PATH may have a component like "." in it, so we still need to
// canonicalize.
return Ok(candidate.canonicalize()?);
}
}
anyhow::bail!("no executable for `{}` found in PATH", exec.display())
} else {
Ok(exec.canonicalize()?)
}
}
pub fn read(path: &Path) -> CargoResult<String> {
match String::from_utf8(read_bytes(path)?) {
Ok(s) => Ok(s),
Err(_) => anyhow::bail!("path at `{}` was not valid utf-8", path.display()),
}
}
pub fn read_bytes(path: &Path) -> CargoResult<Vec<u8>> {
let res = (|| -> CargoResult<_> {
let mut ret = Vec::new();
let mut f = File::open(path)?;
if let Ok(m) = f.metadata() {
ret.reserve(m.len() as usize + 1);
}
f.read_to_end(&mut ret)?;
Ok(ret)
})()
.chain_err(|| format!("failed to read `{}`", path.display()))?;
Ok(res)
}
pub fn write(path: &Path, contents: &[u8]) -> CargoResult<()> {
(|| -> CargoResult<()> {
let mut f = File::create(path)?;
f.write_all(contents)?;
Ok(())
})()
.chain_err(|| format!("failed to write `{}`", path.display()))?;
Ok(())
}
pub fn write_if_changed<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> CargoResult<()> {
(|| -> CargoResult<()> {
let contents = contents.as_ref();
let mut f = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&path)?;
let mut orig = Vec::new();
f.read_to_end(&mut orig)?;
if orig != contents {
f.set_len(0)?; | .chain_err(|| format!("failed to write `{}`", path.as_ref().display()))?;
Ok(())
}
pub fn append(path: &Path, contents: &[u8]) -> CargoResult<()> {
(|| -> CargoResult<()> {
let mut f = OpenOptions::new()
.write(true)
.append(true)
.create(true)
.open(path)?;
f.write_all(contents)?;
Ok(())
})()
.chain_err(|| format!("failed to write `{}`", path.display()))?;
Ok(())
}
pub fn mtime(path: &Path) -> CargoResult<FileTime> {
let meta = fs::metadata(path).chain_err(|| format!("failed to stat `{}`", path.display()))?;
Ok(FileTime::from_last_modification_time(&meta))
}
/// Record the current time on the filesystem (using the filesystem's clock)
/// using a file at the given directory. Returns the current time.
pub fn set_invocation_time(path: &Path) -> CargoResult<FileTime> {
// note that if `FileTime::from_system_time(SystemTime::now());` is determined to be sufficient,
// then this can be removed.
let timestamp = path.join("invoked.timestamp");
write(
×tamp,
b"This file has an mtime of when this was started.",
)?;
let ft = mtime(×tamp)?;
log::debug!("invocation time for {:?} is {}", path, ft);
Ok(ft)
}
#[cfg(unix)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
use std::os::unix::prelude::*;
Ok(path.as_os_str().as_bytes())
}
#[cfg(windows)]
pub fn path2bytes(path: &Path) -> CargoResult<&[u8]> {
match path.as_os_str().to_str() {
Some(s) => Ok(s.as_bytes()),
None => Err(anyhow::format_err!(
"invalid non-unicode path: {}",
path.display()
)),
}
}
#[cfg(unix)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
use std::os::unix::prelude::*;
Ok(PathBuf::from(OsStr::from_bytes(bytes)))
}
#[cfg(windows)]
pub fn bytes2path(bytes: &[u8]) -> CargoResult<PathBuf> {
use std::str;
match str::from_utf8(bytes) {
Ok(s) => Ok(PathBuf::from(s)),
Err(..) => Err(anyhow::format_err!("invalid non-unicode path")),
}
}
pub fn ancestors(path: &Path) -> PathAncestors<'_> {
PathAncestors::new(path)
}
pub struct PathAncestors<'a> {
current: Option<&'a Path>,
stop_at: Option<PathBuf>,
}
impl<'a> PathAncestors<'a> {
fn new(path: &Path) -> PathAncestors<'_> {
PathAncestors {
current: Some(path),
//HACK: avoid reading `~/.cargo/config` when testing Cargo itself.
stop_at: env::var("__CARGO_TEST_ROOT").ok().map(PathBuf::from),
}
}
}
impl<'a> Iterator for PathAncestors<'a> {
type Item = &'a Path;
fn next(&mut self) -> Option<&'a Path> {
if let Some(path) = self.current {
self.current = path.parent();
if let Some(ref stop_at) = self.stop_at {
if path == stop_at {
self.current = None;
}
}
Some(path)
} else {
None
}
}
}
pub fn create_dir_all(p: impl AsRef<Path>) -> CargoResult<()> {
_create_dir_all(p.as_ref())
}
fn _create_dir_all(p: &Path) -> CargoResult<()> {
fs::create_dir_all(p).chain_err(|| format!("failed to create directory `{}`", p.display()))?;
Ok(())
}
pub fn remove_dir_all<P: AsRef<Path>>(p: P) -> CargoResult<()> {
_remove_dir_all(p.as_ref())
}
fn _remove_dir_all(p: &Path) -> CargoResult<()> {
if p.symlink_metadata()?.file_type().is_symlink() {
return remove_file(p);
}
let entries = p
.read_dir()
.chain_err(|| format!("failed to read directory `{}`", p.display()))?;
for entry in entries {
let entry = entry?;
let path = entry.path();
if entry.file_type()?.is_dir() {
remove_dir_all(&path)?;
} else {
remove_file(&path)?;
}
}
remove_dir(&p)
}
pub fn remove_dir<P: AsRef<Path>>(p: P) -> CargoResult<()> {
_remove_dir(p.as_ref())
}
fn _remove_dir(p: &Path) -> CargoResult<()> {
fs::remove_dir(p).chain_err(|| format!("failed to remove directory `{}`", p.display()))?;
Ok(())
}
pub fn remove_file<P: AsRef<Path>>(p: P) -> CargoResult<()> {
_remove_file(p.as_ref())
}
fn _remove_file(p: &Path) -> CargoResult<()> {
let mut err = match fs::remove_file(p) {
Ok(()) => return Ok(()),
Err(e) => e,
};
if err.kind() == io::ErrorKind::PermissionDenied && set_not_readonly(p).unwrap_or(false) {
match fs::remove_file(p) {
Ok(()) => return Ok(()),
Err(e) => err = e,
}
}
Err(err).chain_err(|| format!("failed to remove file `{}`", p.display()))?;
Ok(())
}
fn set_not_readonly(p: &Path) -> io::Result<bool> {
let mut perms = p.metadata()?.permissions();
if !perms.readonly() {
return Ok(false);
}
perms.set_readonly(false);
fs::set_permissions(p, perms)?;
Ok(true)
}
/// Hardlink (file) or symlink (dir) src to dst if possible, otherwise copy it.
///
/// If the destination already exists, it is removed before linking.
pub fn link_or_copy(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> CargoResult<()> {
let src = src.as_ref();
let dst = dst.as_ref();
_link_or_copy(src, dst)
}
fn _link_or_copy(src: &Path, dst: &Path) -> CargoResult<()> {
log::debug!("linking {} to {}", src.display(), dst.display());
if same_file::is_same_file(src, dst).unwrap_or(false) {
return Ok(());
}
// NB: we can't use dst.exists(), as if dst is a broken symlink,
// dst.exists() will return false. This is problematic, as we still need to
// unlink dst in this case. symlink_metadata(dst).is_ok() will tell us
// whether dst exists *without* following symlinks, which is what we want.
if fs::symlink_metadata(dst).is_ok() {
remove_file(&dst)?;
}
let link_result = if src.is_dir() {
#[cfg(target_os = "redox")]
use std::os::redox::fs::symlink;
#[cfg(unix)]
use std::os::unix::fs::symlink;
#[cfg(windows)]
// FIXME: This should probably panic or have a copy fallback. Symlinks
// are not supported in all windows environments. Currently symlinking
// is only used for .dSYM directories on macos, but this shouldn't be
// accidentally relied upon.
use std::os::windows::fs::symlink_dir as symlink;
let dst_dir = dst.parent().unwrap();
let src = if src.starts_with(dst_dir) {
src.strip_prefix(dst_dir).unwrap()
} else {
src
};
symlink(src, dst)
} else if env::var_os("__CARGO_COPY_DONT_LINK_DO_NOT_USE_THIS").is_some() {
// This is a work-around for a bug in macOS 10.15. When running on
// APFS, there seems to be a strange race condition with
// Gatekeeper where it will forcefully kill a process launched via
// `cargo run` with SIGKILL. Copying seems to avoid the problem.
// This shouldn't affect anyone except Cargo's test suite because
// it is very rare, and only seems to happen under heavy load and
// rapidly creating lots of executables and running them.
// See https://github.com/rust-lang/cargo/issues/7821 for the
// gory details.
fs::copy(src, dst).map(|_| ())
} else {
fs::hard_link(src, dst)
};
link_result
.or_else(|err| {
log::debug!("link failed {}. falling back to fs::copy", err);
fs::copy(src, dst).map(|_| ())
})
.chain_err(|| {
format!(
"failed to link or copy `{}` to `{}`",
src.display(),
dst.display()
)
})?;
Ok(())
} | f.seek(io::SeekFrom::Start(0))?;
f.write_all(contents)?;
}
Ok(())
})() | random_line_split |
pt_pt.js | /*!
* froala_editor v3.2.5 (https://www.froala.com/wysiwyg-editor)
* License https://froala.com/wysiwyg-editor/terms/
* Copyright 2014-2020 Froala Labs
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) :
typeof define === 'function' && define.amd ? define(['froala-editor'], factory) :
(factory(global.FroalaEditor));
}(this, (function (FE) { 'use strict';
FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE;
/**
* Portuguese spoken in Portugal
*/
FE.LANGUAGE['pt_pt'] = {
translation: {
// Place holder
'Type something': 'Digite algo',
// Basic formatting
'Bold': 'Negrito',
'Italic': "It\xE1lico",
'Underline': 'Sublinhado',
'Strikethrough': 'Rasurado',
// Main buttons
'Insert': 'Inserir',
'Delete': 'Apagar',
'Cancel': 'Cancelar',
'OK': 'Ok',
'Back': 'Voltar',
'Remove': 'Remover',
'More': 'Mais',
'Update': 'Atualizar',
'Style': 'Estilo',
// Font
'Font Family': 'Fonte',
'Font Size': 'Tamanho da fonte',
// Colors
'Colors': 'Cores',
'Background': 'Fundo',
'Text': 'Texto',
'HEX Color': 'Cor hexadecimal',
// Paragraphs
'Paragraph Format': 'Formatos',
'Normal': 'Normal',
'Code': "C\xF3digo",
'Heading 1': "Cabe\xE7alho 1",
'Heading 2': "Cabe\xE7alho 2",
'Heading 3': "Cabe\xE7alho 3",
'Heading 4': "Cabe\xE7alho 4",
// Style
'Paragraph Style': "Estilo de par\xE1grafo",
'Inline Style': 'Estilo embutido',
// Alignment
'Align': 'Alinhar',
'Align Left': "Alinhar \xE0 esquerda",
'Align Center': 'Alinhar ao centro',
'Align Right': "Alinhar \xE0 direita",
'Align Justify': 'Justificado',
'None': 'Nenhum',
// Lists
'Ordered List': 'Lista ordenada',
'Unordered List': "Lista n\xE3o ordenada",
// Indent
'Decrease Indent': "Diminuir avan\xE7o",
'Increase Indent': "Aumentar avan\xE7o",
// Links
'Insert Link': 'Inserir link',
'Open in new tab': 'Abrir em uma nova aba',
'Open Link': 'Abrir link',
'Edit Link': 'Editar link',
'Unlink': 'Remover link',
'Choose Link': 'Escolha o link',
// Images
'Insert Image': 'Inserir imagem',
'Upload Image': 'Carregar imagem',
'By URL': 'Por URL',
'Browse': 'Procurar',
'Drop image': 'Largue imagem',
'or click': 'ou clique em',
'Manage Images': 'Gerenciar as imagens',
'Loading': 'Carregando',
'Deleting': 'Excluindo',
'Tags': 'Etiquetas',
'Are you sure? Image will be deleted.': "Voc\xEA tem certeza? Imagem ser\xE1 apagada.",
'Replace': 'Substituir',
'Uploading': 'Carregando',
'Loading image': 'Carregando imagem',
'Display': 'Exibir',
'Inline': 'Em linha',
'Break Text': 'Texto de quebra',
'Alternative Text': 'Texto alternativo',
'Change Size': 'Alterar tamanho',
'Width': 'Largura',
'Height': 'Altura',
'Something went wrong. Please try again.': 'Algo deu errado. Por favor, tente novamente.',
'Image Caption': 'Legenda da imagem',
'Advanced Edit': 'Edição avançada',
// Video
'Insert Video': "Inserir v\xEDdeo",
'Embedded Code': "C\xF3digo embutido",
'Paste in a video URL': 'Colar em um URL de vídeo',
'Drop video': 'Solte o video',
'Your browser does not support HTML5 video.': 'Seu navegador não suporta o vídeo html5.',
'Upload Video': 'Envio vídeo',
// Tables
'Insert Table': 'Inserir tabela',
'Table Header': "Cabe\xE7alho da tabela",
'Remove Table': 'Remover tabela',
'Table Style': 'estilo de tabela',
'Horizontal Align': 'Alinhamento horizontal',
'Row': 'Linha',
'Insert row above': 'Inserir linha antes',
'Insert row below': 'Inserir linha depois',
'Delete row': 'Eliminar linha',
'Column': 'Coluna',
'Insert column before': 'Inserir coluna antes',
'Insert column after': 'Inserir coluna depois',
'Delete column': 'Eliminar coluna',
'Cell': "C\xE9lula",
'Merge cells': "Unir c\xE9lulas",
'Horizontal split': "Divis\xE3o horizontal",
'Vertical split': "Divis\xE3o vertical",
'Cell Background': "Fundo da c\xE9lula",
'Vertical Align': 'Alinhar vertical',
'Top': 'Topo',
'Middle': 'Meio',
'Bottom': 'Fundo',
'Align Top': 'Alinhar topo',
'Align Middle': 'Alinhar meio',
'Align Bottom': 'Alinhar fundo',
'Cell Style': "Estilo de c\xE9lula",
// Files
'Upload File': 'Upload de arquivo',
'Drop file': 'Largar arquivo',
// Emoticons
'Emoticons': 'Emoticons',
'Grinning face': 'Sorrindo a cara',
'Grinning face with smiling eyes': 'Sorrindo rosto com olhos sorridentes',
'Face with tears of joy': "Rosto com l\xE1grimas de alegria",
'Smiling face with open mouth': 'Rosto de sorriso com a boca aberta',
'Smiling face with open mouth and smiling eyes': 'Rosto de sorriso com a boca aberta e olhos sorridentes',
'Smiling face with open mouth and cold sweat': 'Rosto de sorriso com a boca aberta e suor frio',
'Smiling face with open mouth and tightly-closed eyes': 'Rosto de sorriso com a boca aberta e os olhos bem fechados',
'Smiling face with halo': 'Rosto de sorriso com halo',
'Smiling face with horns': 'Rosto de sorriso com chifres',
'Winking face': 'Pisc a rosto',
'Smiling face with smiling eyes': 'Rosto de sorriso com olhos sorridentes',
'Face savoring delicious food': 'Rosto saboreando uma deliciosa comida',
'Relieved face': 'Rosto aliviado',
'Smiling face with heart-shaped eyes': "Rosto de sorriso com os olhos em forma de cora\xE7\xE3o",
'Smiling face with sunglasses': "Rosto de sorriso com \xF3culos de sol",
'Smirking face': 'Rosto sorridente',
'Neutral face': 'Rosto neutra',
'Expressionless face': 'Rosto inexpressivo',
'Unamused face': "O rosto n\xE3o divertido",
'Face with cold sweat': 'Rosto com suor frio',
'Pensive face': 'O rosto pensativo',
'Confused face': 'Cara confusa',
'Confounded face': "Rosto at\xF4nito",
'Kissing face': 'Beijar Rosto',
'Face throwing a kiss': 'Rosto jogando um beijo',
'Kissing face with smiling eyes': 'Beijar rosto com olhos sorridentes',
'Kissing face with closed eyes': 'Beijando a cara com os olhos fechados',
'Face with stuck out tongue': "Preso de cara com a l\xEDngua para fora",
'Face with stuck out tongue and winking eye': "Rosto com estendeu a l\xEDngua e olho piscando",
'Face with stuck out tongue and tightly-closed eyes': 'Rosto com estendeu a língua e os olhos bem fechados', | 'Angry face': 'Rosto irritado',
'Pouting face': 'Beicinho Rosto',
'Crying face': 'Cara de choro',
'Persevering face': 'Perseverar Rosto',
'Face with look of triumph': 'Rosto com olhar de triunfo',
'Disappointed but relieved face': 'Fiquei Desapontado mas aliviado Rosto',
'Frowning face with open mouth': 'Sobrancelhas franzidas rosto com a boca aberta',
'Anguished face': 'O rosto angustiado',
'Fearful face': 'Cara com medo',
'Weary face': 'Rosto cansado',
'Sleepy face': 'Cara de sono',
'Tired face': 'Rosto cansado',
'Grimacing face': 'Fazendo caretas face',
'Loudly crying face': 'Alto chorando rosto',
'Face with open mouth': 'Enfrentar com a boca aberta',
'Hushed face': 'Flagrantes de rosto',
'Face with open mouth and cold sweat': 'Enfrentar com a boca aberta e suor frio',
'Face screaming in fear': 'Cara gritando de medo',
'Astonished face': 'Cara de surpresa',
'Flushed face': 'Rosto vermelho',
'Sleeping face': 'O rosto de sono',
'Dizzy face': 'Cara tonto',
'Face without mouth': 'Rosto sem boca',
'Face with medical mask': "Rosto com m\xE1scara m\xE9dica",
// Line breaker
'Break': 'Partir',
// Math
'Subscript': 'Subscrito',
'Superscript': 'Sobrescrito',
// Full screen
'Fullscreen': 'Tela cheia',
// Horizontal line
'Insert Horizontal Line': 'Inserir linha horizontal',
// Clear formatting
'Clear Formatting': "Remover formata\xE7\xE3o",
// Save
'Save': "Salve",
// Undo, redo
'Undo': 'Anular',
'Redo': 'Restaurar',
// Select all
'Select All': 'Seleccionar tudo',
// Code view
'Code View': "Exibi\xE7\xE3o de c\xF3digo",
// Quote
'Quote': "Cita\xE7\xE3o",
'Increase': 'Aumentar',
'Decrease': 'Diminuir',
// Quick Insert
'Quick Insert': "Inser\xE7\xE3o r\xE1pida",
// Spcial Characters
'Special Characters': 'Caracteres especiais',
'Latin': 'Latino',
'Greek': 'Grego',
'Cyrillic': 'Cirílico',
'Punctuation': 'Pontuação',
'Currency': 'Moeda',
'Arrows': 'Setas; flechas',
'Math': 'Matemática',
'Misc': 'Misc',
// Print.
'Print': 'Impressão',
// Spell Checker.
'Spell Checker': 'Verificador ortográfico',
// Help
'Help': 'Socorro',
'Shortcuts': 'Atalhos',
'Inline Editor': 'Editor em linha',
'Show the editor': 'Mostre o editor',
'Common actions': 'Ações comuns',
'Copy': 'Cópia de',
'Cut': 'Cortar',
'Paste': 'Colar',
'Basic Formatting': 'Formatação básica',
'Increase quote level': 'Aumentar o nível de cotação',
'Decrease quote level': 'Diminuir o nível de cotação',
'Image / Video': 'Imagem / video',
'Resize larger': 'Redimensionar maior',
'Resize smaller': 'Redimensionar menor',
'Table': 'Tabela',
'Select table cell': 'Selecione a célula da tabela',
'Extend selection one cell': 'Ampliar a seleção de uma célula',
'Extend selection one row': 'Ampliar a seleção uma linha',
'Navigation': 'Navegação',
'Focus popup / toolbar': 'Foco popup / barra de ferramentas',
'Return focus to previous position': 'Retornar o foco para a posição anterior',
// Embed.ly
'Embed URL': 'URL de inserção',
'Paste in a URL to embed': 'Colar em url para incorporar',
// Word Paste.
'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': 'O conteúdo colado vem de um documento Microsoft Word. Você quer manter o formato ou limpá-lo?',
'Keep': 'Guarda',
'Clean': 'Limpar limpo',
'Word Paste Detected': 'Pasta de palavras detectada',
// Character Counter
'Characters': 'Caracteres',
// More Buttons
'More Text': 'Mais Texto',
'More Paragraph': 'Mais Parágrafo',
'More Rich': 'Mais Rico',
'More Misc': 'Mais Misc'
},
direction: 'ltr'
};
})));
//# sourceMappingURL=pt_pt.js.map | 'Disappointed face': 'Rosto decepcionado',
'Worried face': 'O rosto preocupado', | random_line_split |
consoleLogger.js | /*jshint unused:false */
"use strict";
var _verbosity = 0;
var _prefix = "[videojs-vast-vpaid] ";
function setVerbosity (v)
{
_verbosity = v;
}
function handleMsg (method, args)
{
if ((args.length) > 0 && (typeof args[0] === 'string'))
{
args[0] = _prefix + args[0];
}
if (method.apply)
{
method.apply (console, Array.prototype.slice.call(args));
}
else
{
method (Array.prototype.slice.call(args));
}
}
function debug ()
{
if (_verbosity < 4)
{
return;
}
if (typeof console.debug === 'undefined')
{
// IE 10 doesn't have a console.debug() function
handleMsg (console.log, arguments);
}
else
{
handleMsg (console.debug, arguments);
}
}
function log ()
{
if (_verbosity < 3)
{
return;
}
handleMsg (console.log, arguments);
}
function info ()
{
if (_verbosity < 2)
{
return;
}
handleMsg (console.info, arguments);
}
function warn ()
{
if (_verbosity < 1)
|
handleMsg (console.warn, arguments);
}
function error ()
{
handleMsg (console.error, arguments);
}
var consoleLogger = {
setVerbosity: setVerbosity,
debug: debug,
log: log,
info: info,
warn: warn,
error: error
};
if ((typeof (console) === 'undefined') || !console.log)
{
// no console available; make functions no-op
consoleLogger.debug = function () {};
consoleLogger.log = function () {};
consoleLogger.info = function () {};
consoleLogger.warn = function () {};
consoleLogger.error = function () {};
}
module.exports = consoleLogger; | {
return;
} | conditional_block |
consoleLogger.js | /*jshint unused:false */
"use strict";
var _verbosity = 0;
var _prefix = "[videojs-vast-vpaid] ";
function setVerbosity (v)
{
_verbosity = v;
}
function handleMsg (method, args)
{
if ((args.length) > 0 && (typeof args[0] === 'string'))
{
args[0] = _prefix + args[0];
}
if (method.apply)
{
method.apply (console, Array.prototype.slice.call(args));
}
else
{
method (Array.prototype.slice.call(args));
}
}
function debug ()
{
if (_verbosity < 4)
{
return;
}
if (typeof console.debug === 'undefined')
{
// IE 10 doesn't have a console.debug() function
handleMsg (console.log, arguments);
}
else
{
handleMsg (console.debug, arguments);
}
}
function log ()
{
if (_verbosity < 3)
{
return;
}
handleMsg (console.log, arguments);
}
function info ()
{
if (_verbosity < 2)
{
return;
}
handleMsg (console.info, arguments);
}
function warn ()
{
if (_verbosity < 1)
{
return;
}
handleMsg (console.warn, arguments);
}
function | ()
{
handleMsg (console.error, arguments);
}
var consoleLogger = {
setVerbosity: setVerbosity,
debug: debug,
log: log,
info: info,
warn: warn,
error: error
};
if ((typeof (console) === 'undefined') || !console.log)
{
// no console available; make functions no-op
consoleLogger.debug = function () {};
consoleLogger.log = function () {};
consoleLogger.info = function () {};
consoleLogger.warn = function () {};
consoleLogger.error = function () {};
}
module.exports = consoleLogger; | error | identifier_name |
consoleLogger.js | /*jshint unused:false */
"use strict";
var _verbosity = 0;
var _prefix = "[videojs-vast-vpaid] ";
function setVerbosity (v)
{
_verbosity = v;
}
function handleMsg (method, args)
{
if ((args.length) > 0 && (typeof args[0] === 'string'))
{
args[0] = _prefix + args[0];
}
if (method.apply)
{
method.apply (console, Array.prototype.slice.call(args));
}
else
{
method (Array.prototype.slice.call(args));
}
}
function debug ()
{
if (_verbosity < 4)
{
return;
}
if (typeof console.debug === 'undefined')
{
// IE 10 doesn't have a console.debug() function
handleMsg (console.log, arguments);
}
else
{
handleMsg (console.debug, arguments);
}
}
function log ()
{
if (_verbosity < 3)
{
return;
}
handleMsg (console.log, arguments);
}
function info ()
{
if (_verbosity < 2)
{
return;
}
handleMsg (console.info, arguments);
}
function warn ()
{
if (_verbosity < 1)
{
return;
}
handleMsg (console.warn, arguments);
} | {
handleMsg (console.error, arguments);
}
var consoleLogger = {
setVerbosity: setVerbosity,
debug: debug,
log: log,
info: info,
warn: warn,
error: error
};
if ((typeof (console) === 'undefined') || !console.log)
{
// no console available; make functions no-op
consoleLogger.debug = function () {};
consoleLogger.log = function () {};
consoleLogger.info = function () {};
consoleLogger.warn = function () {};
consoleLogger.error = function () {};
}
module.exports = consoleLogger; |
function error () | random_line_split |
consoleLogger.js | /*jshint unused:false */
"use strict";
var _verbosity = 0;
var _prefix = "[videojs-vast-vpaid] ";
function setVerbosity (v)
{
_verbosity = v;
}
function handleMsg (method, args)
{
if ((args.length) > 0 && (typeof args[0] === 'string'))
{
args[0] = _prefix + args[0];
}
if (method.apply)
{
method.apply (console, Array.prototype.slice.call(args));
}
else
{
method (Array.prototype.slice.call(args));
}
}
function debug ()
{
if (_verbosity < 4)
{
return;
}
if (typeof console.debug === 'undefined')
{
// IE 10 doesn't have a console.debug() function
handleMsg (console.log, arguments);
}
else
{
handleMsg (console.debug, arguments);
}
}
function log ()
{
if (_verbosity < 3)
{
return;
}
handleMsg (console.log, arguments);
}
function info ()
|
function warn ()
{
if (_verbosity < 1)
{
return;
}
handleMsg (console.warn, arguments);
}
function error ()
{
handleMsg (console.error, arguments);
}
var consoleLogger = {
setVerbosity: setVerbosity,
debug: debug,
log: log,
info: info,
warn: warn,
error: error
};
if ((typeof (console) === 'undefined') || !console.log)
{
// no console available; make functions no-op
consoleLogger.debug = function () {};
consoleLogger.log = function () {};
consoleLogger.info = function () {};
consoleLogger.warn = function () {};
consoleLogger.error = function () {};
}
module.exports = consoleLogger; | {
if (_verbosity < 2)
{
return;
}
handleMsg (console.info, arguments);
} | identifier_body |
trait-implementations.rs | // compile-flags:-Zprint-mono-items=eager
#![deny(dead_code)]
#![feature(start)]
pub trait SomeTrait {
fn foo(&self);
fn bar<T>(&self, x: T);
}
impl SomeTrait for i64 {
//~ MONO_ITEM fn <i64 as SomeTrait>::foo
fn foo(&self) {}
fn bar<T>(&self, _: T) {}
} |
fn bar<T>(&self, _: T) {}
}
pub trait SomeGenericTrait<T> {
fn foo(&self, x: T);
fn bar<T2>(&self, x: T, y: T2);
}
// Concrete impl of generic trait
impl SomeGenericTrait<u32> for f64 {
//~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::foo
fn foo(&self, _: u32) {}
fn bar<T2>(&self, _: u32, _: T2) {}
}
// Generic impl of generic trait
impl<T> SomeGenericTrait<T> for f32 {
fn foo(&self, _: T) {}
fn bar<T2>(&self, _: T, _: T2) {}
}
//~ MONO_ITEM fn start
#[start]
fn start(_: isize, _: *const *const u8) -> isize {
//~ MONO_ITEM fn <i32 as SomeTrait>::bar::<char>
0i32.bar('x');
//~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::bar::<&str>
0f64.bar(0u32, "&str");
//~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::bar::<()>
0f64.bar(0u32, ());
//~ MONO_ITEM fn <f32 as SomeGenericTrait<char>>::foo
0f32.foo('x');
//~ MONO_ITEM fn <f32 as SomeGenericTrait<i64>>::foo
0f32.foo(-1i64);
//~ MONO_ITEM fn <f32 as SomeGenericTrait<u32>>::bar::<()>
0f32.bar(0u32, ());
//~ MONO_ITEM fn <f32 as SomeGenericTrait<&str>>::bar::<&str>
0f32.bar("&str", "&str");
0
} |
impl SomeTrait for i32 {
//~ MONO_ITEM fn <i32 as SomeTrait>::foo
fn foo(&self) {} | random_line_split |
trait-implementations.rs | // compile-flags:-Zprint-mono-items=eager
#![deny(dead_code)]
#![feature(start)]
pub trait SomeTrait {
fn foo(&self);
fn bar<T>(&self, x: T);
}
impl SomeTrait for i64 {
//~ MONO_ITEM fn <i64 as SomeTrait>::foo
fn foo(&self) {}
fn bar<T>(&self, _: T) {}
}
impl SomeTrait for i32 {
//~ MONO_ITEM fn <i32 as SomeTrait>::foo
fn foo(&self) {}
fn | <T>(&self, _: T) {}
}
pub trait SomeGenericTrait<T> {
fn foo(&self, x: T);
fn bar<T2>(&self, x: T, y: T2);
}
// Concrete impl of generic trait
impl SomeGenericTrait<u32> for f64 {
//~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::foo
fn foo(&self, _: u32) {}
fn bar<T2>(&self, _: u32, _: T2) {}
}
// Generic impl of generic trait
impl<T> SomeGenericTrait<T> for f32 {
fn foo(&self, _: T) {}
fn bar<T2>(&self, _: T, _: T2) {}
}
//~ MONO_ITEM fn start
#[start]
fn start(_: isize, _: *const *const u8) -> isize {
//~ MONO_ITEM fn <i32 as SomeTrait>::bar::<char>
0i32.bar('x');
//~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::bar::<&str>
0f64.bar(0u32, "&str");
//~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::bar::<()>
0f64.bar(0u32, ());
//~ MONO_ITEM fn <f32 as SomeGenericTrait<char>>::foo
0f32.foo('x');
//~ MONO_ITEM fn <f32 as SomeGenericTrait<i64>>::foo
0f32.foo(-1i64);
//~ MONO_ITEM fn <f32 as SomeGenericTrait<u32>>::bar::<()>
0f32.bar(0u32, ());
//~ MONO_ITEM fn <f32 as SomeGenericTrait<&str>>::bar::<&str>
0f32.bar("&str", "&str");
0
}
| bar | identifier_name |
trait-implementations.rs | // compile-flags:-Zprint-mono-items=eager
#![deny(dead_code)]
#![feature(start)]
pub trait SomeTrait {
fn foo(&self);
fn bar<T>(&self, x: T);
}
impl SomeTrait for i64 {
//~ MONO_ITEM fn <i64 as SomeTrait>::foo
fn foo(&self) |
fn bar<T>(&self, _: T) {}
}
impl SomeTrait for i32 {
//~ MONO_ITEM fn <i32 as SomeTrait>::foo
fn foo(&self) {}
fn bar<T>(&self, _: T) {}
}
pub trait SomeGenericTrait<T> {
fn foo(&self, x: T);
fn bar<T2>(&self, x: T, y: T2);
}
// Concrete impl of generic trait
impl SomeGenericTrait<u32> for f64 {
//~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::foo
fn foo(&self, _: u32) {}
fn bar<T2>(&self, _: u32, _: T2) {}
}
// Generic impl of generic trait
impl<T> SomeGenericTrait<T> for f32 {
fn foo(&self, _: T) {}
fn bar<T2>(&self, _: T, _: T2) {}
}
//~ MONO_ITEM fn start
#[start]
fn start(_: isize, _: *const *const u8) -> isize {
//~ MONO_ITEM fn <i32 as SomeTrait>::bar::<char>
0i32.bar('x');
//~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::bar::<&str>
0f64.bar(0u32, "&str");
//~ MONO_ITEM fn <f64 as SomeGenericTrait<u32>>::bar::<()>
0f64.bar(0u32, ());
//~ MONO_ITEM fn <f32 as SomeGenericTrait<char>>::foo
0f32.foo('x');
//~ MONO_ITEM fn <f32 as SomeGenericTrait<i64>>::foo
0f32.foo(-1i64);
//~ MONO_ITEM fn <f32 as SomeGenericTrait<u32>>::bar::<()>
0f32.bar(0u32, ());
//~ MONO_ITEM fn <f32 as SomeGenericTrait<&str>>::bar::<&str>
0f32.bar("&str", "&str");
0
}
| {} | identifier_body |
t_output.py | #!/usr/local/bin/python2.6 -tt
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
class Output:
'Output interface'
def __init__(self, output):
self._on_blank_line = True
self._output = output
self._flag = False
def write(self, lines):
'Writes lines (a string) '
# assume we are not on a blank line
self._write(lines)
def _write(self, lines):
raise NotImplementedError
def _write_line_contents(self, line):
# if anything was written
if self._write_line_contents_impl(line):
self._flag = False
self._on_blank_line = False
def _write_line_contents_impl(self, line):
'Returns whether anything was written or not'
raise NotImplementedError
def indent(self):
pass
def unindent(self):
|
def force_newline(self):
'Force a newline'
print >>self._output
self._on_blank_line = True
self._flag = False
def line_feed(self):
'''Enforce that the cursor is placed on an empty line, returns whether
a newline was printed or not'''
if not self._on_blank_line:
self.force_newline()
return True
return False
def double_space(self):
'''Unless current position is already on an empty line, insert a blank
line before the next statement, as long as it's not the beginning of
a statement'''
ofl = self.on_flagged_line
if self.line_feed() and not ofl:
self.force_newline()
def flag_this_line(self, flag=True):
'''Mark the current line as flagged. This is used to apply specific
logic to certain lines, such as those that represent the start of a
scope.'''
# TODO(dsanduleac): deprecate this and use a num_lines_printed
# abstraction instead. Then modify t_cpp_generator to always print
# newlines after statements. Should modify the behaviour of
# double_space as well.
self._flag = flag
@property
def on_flagged_line(self):
'Returns whether the line we are currently on has been flagged'
return self._flag
class IndentedOutput(Output):
def __init__(self, output, indent_char=' '):
Output.__init__(self, output)
self._indent = 0
# configurable values
self._indent_char = indent_char
def indent(self, amount):
assert self._indent + amount >= 0
self._indent += amount
def unindent(self, amount):
assert self._indent - amount >= 0
self._indent -= amount
def _write_line_contents_impl(self, line):
# strip trailing characters
line = line.rstrip()
# handle case where _write is being passed a \n-terminated string
if line == '':
# don't flag the current line as non-empty, we didn't write
# anything
return False
if self._on_blank_line:
# write indent
self._output.write(self._indent * self._indent_char)
# write content
self._output.write(line)
return True
def _write(self, lines):
lines = lines.split('\n')
self._write_line_contents(lines[0])
for line in lines[1:]:
# ensure newlines between input lines
self.force_newline()
self._write_line_contents(line)
class CompositeOutput(Output):
def __init__(self, *outputs):
self._outputs = outputs
def indent(self):
for output in self._outputs:
output.indent()
def unindent(self):
for output in self._outputs:
output.unindent()
def _write(self, lines):
for output in self._outputs:
output.write(lines)
def _write_line_contents_impl(self, line):
# this is never used internally in this output
pass
def line_feed(self):
for output in self._outputs:
output.line_feed()
def force_newline(self):
for output in self._outputs:
output.force_newline()
# These two don't make sense to be implemented here
def flag_this_line(self):
raise NotImplementedError
def on_flagged_line(self):
raise NotImplementedError
def double_space(self):
for output in self._outputs:
output.double_space()
class DummyOutput(Output):
def __init__(self):
pass
def _write(self, lines):
pass
def _write_line_contents_impl(self, line):
pass
def force_newline(self):
pass
def line_feed(self):
pass
def double_space(self):
pass
def flag_this_line(self, flag=True):
pass
@property
def on_flagged_line(self):
return False
| pass | identifier_body |
t_output.py | #!/usr/local/bin/python2.6 -tt
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
class Output:
'Output interface'
def __init__(self, output):
self._on_blank_line = True
self._output = output
self._flag = False
def write(self, lines):
'Writes lines (a string) '
# assume we are not on a blank line
self._write(lines)
def _write(self, lines):
raise NotImplementedError
def _write_line_contents(self, line):
# if anything was written
if self._write_line_contents_impl(line):
self._flag = False
self._on_blank_line = False
def _write_line_contents_impl(self, line):
'Returns whether anything was written or not'
raise NotImplementedError
def indent(self):
pass
def unindent(self):
pass
def force_newline(self):
'Force a newline'
print >>self._output
self._on_blank_line = True
self._flag = False
def line_feed(self):
'''Enforce that the cursor is placed on an empty line, returns whether
a newline was printed or not'''
if not self._on_blank_line:
self.force_newline()
return True
return False
def double_space(self):
'''Unless current position is already on an empty line, insert a blank
line before the next statement, as long as it's not the beginning of
a statement'''
ofl = self.on_flagged_line
if self.line_feed() and not ofl:
self.force_newline()
def flag_this_line(self, flag=True):
'''Mark the current line as flagged. This is used to apply specific
logic to certain lines, such as those that represent the start of a
scope.'''
# TODO(dsanduleac): deprecate this and use a num_lines_printed
# abstraction instead. Then modify t_cpp_generator to always print
# newlines after statements. Should modify the behaviour of
# double_space as well.
self._flag = flag
@property
def on_flagged_line(self):
'Returns whether the line we are currently on has been flagged'
return self._flag
class IndentedOutput(Output):
def __init__(self, output, indent_char=' '):
Output.__init__(self, output)
self._indent = 0
# configurable values
self._indent_char = indent_char
def indent(self, amount):
assert self._indent + amount >= 0
self._indent += amount
def | (self, amount):
assert self._indent - amount >= 0
self._indent -= amount
def _write_line_contents_impl(self, line):
# strip trailing characters
line = line.rstrip()
# handle case where _write is being passed a \n-terminated string
if line == '':
# don't flag the current line as non-empty, we didn't write
# anything
return False
if self._on_blank_line:
# write indent
self._output.write(self._indent * self._indent_char)
# write content
self._output.write(line)
return True
def _write(self, lines):
lines = lines.split('\n')
self._write_line_contents(lines[0])
for line in lines[1:]:
# ensure newlines between input lines
self.force_newline()
self._write_line_contents(line)
class CompositeOutput(Output):
def __init__(self, *outputs):
self._outputs = outputs
def indent(self):
for output in self._outputs:
output.indent()
def unindent(self):
for output in self._outputs:
output.unindent()
def _write(self, lines):
for output in self._outputs:
output.write(lines)
def _write_line_contents_impl(self, line):
# this is never used internally in this output
pass
def line_feed(self):
for output in self._outputs:
output.line_feed()
def force_newline(self):
for output in self._outputs:
output.force_newline()
# These two don't make sense to be implemented here
def flag_this_line(self):
raise NotImplementedError
def on_flagged_line(self):
raise NotImplementedError
def double_space(self):
for output in self._outputs:
output.double_space()
class DummyOutput(Output):
def __init__(self):
pass
def _write(self, lines):
pass
def _write_line_contents_impl(self, line):
pass
def force_newline(self):
pass
def line_feed(self):
pass
def double_space(self):
pass
def flag_this_line(self, flag=True):
pass
@property
def on_flagged_line(self):
return False
| unindent | identifier_name |
t_output.py | #!/usr/local/bin/python2.6 -tt
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
class Output:
'Output interface'
def __init__(self, output):
self._on_blank_line = True
self._output = output
self._flag = False
def write(self, lines):
'Writes lines (a string) '
# assume we are not on a blank line
self._write(lines)
def _write(self, lines):
raise NotImplementedError
def _write_line_contents(self, line):
# if anything was written
if self._write_line_contents_impl(line):
self._flag = False
self._on_blank_line = False
def _write_line_contents_impl(self, line):
'Returns whether anything was written or not'
raise NotImplementedError
def indent(self):
pass
def unindent(self):
pass
def force_newline(self):
'Force a newline'
print >>self._output
self._on_blank_line = True
self._flag = False
def line_feed(self):
'''Enforce that the cursor is placed on an empty line, returns whether
a newline was printed or not'''
if not self._on_blank_line:
self.force_newline()
return True
return False
def double_space(self):
'''Unless current position is already on an empty line, insert a blank
line before the next statement, as long as it's not the beginning of
a statement'''
ofl = self.on_flagged_line
if self.line_feed() and not ofl:
self.force_newline()
def flag_this_line(self, flag=True):
'''Mark the current line as flagged. This is used to apply specific
logic to certain lines, such as those that represent the start of a
scope.'''
# TODO(dsanduleac): deprecate this and use a num_lines_printed
# abstraction instead. Then modify t_cpp_generator to always print
# newlines after statements. Should modify the behaviour of
# double_space as well.
self._flag = flag
@property
def on_flagged_line(self):
'Returns whether the line we are currently on has been flagged'
return self._flag
class IndentedOutput(Output):
def __init__(self, output, indent_char=' '):
Output.__init__(self, output)
self._indent = 0
# configurable values
self._indent_char = indent_char
def indent(self, amount):
assert self._indent + amount >= 0
self._indent += amount
def unindent(self, amount):
assert self._indent - amount >= 0
self._indent -= amount
def _write_line_contents_impl(self, line):
# strip trailing characters
line = line.rstrip()
# handle case where _write is being passed a \n-terminated string
if line == '':
# don't flag the current line as non-empty, we didn't write
# anything
return False
if self._on_blank_line:
# write indent
self._output.write(self._indent * self._indent_char)
# write content
self._output.write(line)
return True
def _write(self, lines):
lines = lines.split('\n')
self._write_line_contents(lines[0])
for line in lines[1:]:
# ensure newlines between input lines
|
class CompositeOutput(Output):
def __init__(self, *outputs):
self._outputs = outputs
def indent(self):
for output in self._outputs:
output.indent()
def unindent(self):
for output in self._outputs:
output.unindent()
def _write(self, lines):
for output in self._outputs:
output.write(lines)
def _write_line_contents_impl(self, line):
# this is never used internally in this output
pass
def line_feed(self):
for output in self._outputs:
output.line_feed()
def force_newline(self):
for output in self._outputs:
output.force_newline()
# These two don't make sense to be implemented here
def flag_this_line(self):
raise NotImplementedError
def on_flagged_line(self):
raise NotImplementedError
def double_space(self):
for output in self._outputs:
output.double_space()
class DummyOutput(Output):
def __init__(self):
pass
def _write(self, lines):
pass
def _write_line_contents_impl(self, line):
pass
def force_newline(self):
pass
def line_feed(self):
pass
def double_space(self):
pass
def flag_this_line(self, flag=True):
pass
@property
def on_flagged_line(self):
return False
| self.force_newline()
self._write_line_contents(line) | conditional_block |
t_output.py | #!/usr/local/bin/python2.6 -tt
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
class Output:
'Output interface'
def __init__(self, output):
self._on_blank_line = True
self._output = output
self._flag = False
def write(self, lines):
'Writes lines (a string) '
# assume we are not on a blank line
self._write(lines)
def _write(self, lines):
raise NotImplementedError
def _write_line_contents(self, line):
# if anything was written
if self._write_line_contents_impl(line):
self._flag = False
self._on_blank_line = False
def _write_line_contents_impl(self, line):
'Returns whether anything was written or not'
raise NotImplementedError
def indent(self):
pass
def unindent(self):
pass
def force_newline(self):
'Force a newline'
print >>self._output
self._on_blank_line = True
self._flag = False
def line_feed(self):
'''Enforce that the cursor is placed on an empty line, returns whether
a newline was printed or not'''
if not self._on_blank_line:
self.force_newline()
return True
return False
def double_space(self):
'''Unless current position is already on an empty line, insert a blank
line before the next statement, as long as it's not the beginning of
a statement'''
ofl = self.on_flagged_line
if self.line_feed() and not ofl:
self.force_newline()
def flag_this_line(self, flag=True):
'''Mark the current line as flagged. This is used to apply specific
logic to certain lines, such as those that represent the start of a
scope.'''
# TODO(dsanduleac): deprecate this and use a num_lines_printed
# abstraction instead. Then modify t_cpp_generator to always print
# newlines after statements. Should modify the behaviour of
# double_space as well.
self._flag = flag
@property
def on_flagged_line(self):
'Returns whether the line we are currently on has been flagged'
return self._flag
class IndentedOutput(Output):
def __init__(self, output, indent_char=' '):
Output.__init__(self, output)
self._indent = 0
# configurable values
self._indent_char = indent_char
def indent(self, amount):
assert self._indent + amount >= 0
self._indent += amount
def unindent(self, amount):
assert self._indent - amount >= 0
self._indent -= amount
def _write_line_contents_impl(self, line):
# strip trailing characters
line = line.rstrip()
# handle case where _write is being passed a \n-terminated string
if line == '':
# don't flag the current line as non-empty, we didn't write
# anything
return False
if self._on_blank_line:
# write indent
self._output.write(self._indent * self._indent_char)
# write content
self._output.write(line)
return True
def _write(self, lines):
lines = lines.split('\n')
self._write_line_contents(lines[0])
for line in lines[1:]:
# ensure newlines between input lines
self.force_newline()
self._write_line_contents(line) |
def indent(self):
for output in self._outputs:
output.indent()
def unindent(self):
for output in self._outputs:
output.unindent()
def _write(self, lines):
for output in self._outputs:
output.write(lines)
def _write_line_contents_impl(self, line):
# this is never used internally in this output
pass
def line_feed(self):
for output in self._outputs:
output.line_feed()
def force_newline(self):
for output in self._outputs:
output.force_newline()
# These two don't make sense to be implemented here
def flag_this_line(self):
raise NotImplementedError
def on_flagged_line(self):
raise NotImplementedError
def double_space(self):
for output in self._outputs:
output.double_space()
class DummyOutput(Output):
def __init__(self):
pass
def _write(self, lines):
pass
def _write_line_contents_impl(self, line):
pass
def force_newline(self):
pass
def line_feed(self):
pass
def double_space(self):
pass
def flag_this_line(self, flag=True):
pass
@property
def on_flagged_line(self):
return False |
class CompositeOutput(Output):
def __init__(self, *outputs):
self._outputs = outputs | random_line_split |
drop_flag_effects.rs | // Copyright 2012-2017 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 rustc::mir::{self, Mir, Location};
use rustc::ty::{self, TyCtxt};
use util::elaborate_drops::DropFlagState;
use super::{MoveDataParamEnv};
use super::indexes::MovePathIndex;
use super::move_paths::{MoveData, LookupResult, InitKind};
pub fn move_path_children_matching<'tcx, F>(move_data: &MoveData<'tcx>,
path: MovePathIndex,
mut cond: F)
-> Option<MovePathIndex>
where F: FnMut(&mir::PlaceProjection<'tcx>) -> bool
{
let mut next_child = move_data.move_paths[path].first_child;
while let Some(child_index) = next_child {
match move_data.move_paths[child_index].place {
mir::Place::Projection(ref proj) => {
if cond(proj) {
return Some(child_index)
}
}
_ => {}
}
next_child = move_data.move_paths[child_index].next_sibling;
}
None
}
/// When enumerating the child fragments of a path, don't recurse into
/// paths (1.) past arrays, slices, and pointers, nor (2.) into a type
/// that implements `Drop`.
///
/// Places behind references or arrays are not tracked by elaboration
/// and are always assumed to be initialized when accessible. As
/// references and indexes can be reseated, trying to track them can
/// only lead to trouble.
///
/// Places behind ADT's with a Drop impl are not tracked by
/// elaboration since they can never have a drop-flag state that
/// differs from that of the parent with the Drop impl.
///
/// In both cases, the contents can only be accessed if and only if
/// their parents are initialized. This implies for example that there
/// is no need to maintain separate drop flags to track such state.
///
/// FIXME: we have to do something for moving slice patterns.
fn place_contents_drop_state_cannot_differ<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
place: &mir::Place<'tcx>) -> bool {
let ty = place.ty(mir, tcx).to_ty(tcx);
match ty.sty {
ty::Array(..) => {
debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false",
place, ty);
false
}
ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => {
debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} refd => true",
place, ty);
true
}
ty::Adt(def, _) if (def.has_dtor(tcx) && !def.is_box()) || def.is_union() => {
debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} Drop => true",
place, ty);
true
}
_ => {
false
}
}
}
pub(crate) fn on_lookup_result_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
lookup_result: LookupResult,
each_child: F)
where F: FnMut(MovePathIndex)
{
match lookup_result {
LookupResult::Parent(..) => {
// access to untracked value - do not touch children
}
LookupResult::Exact(e) => {
on_all_children_bits(tcx, mir, move_data, e, each_child)
}
}
}
pub(crate) fn on_all_children_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
move_path_index: MovePathIndex,
mut each_child: F)
where F: FnMut(MovePathIndex)
{
fn | <'a, 'gcx, 'tcx>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
path: MovePathIndex) -> bool
{
place_contents_drop_state_cannot_differ(
tcx, mir, &move_data.move_paths[path].place)
}
fn on_all_children_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
move_path_index: MovePathIndex,
each_child: &mut F)
where F: FnMut(MovePathIndex)
{
each_child(move_path_index);
if is_terminal_path(tcx, mir, move_data, move_path_index) {
return
}
let mut next_child_index = move_data.move_paths[move_path_index].first_child;
while let Some(child_index) = next_child_index {
on_all_children_bits(tcx, mir, move_data, child_index, each_child);
next_child_index = move_data.move_paths[child_index].next_sibling;
}
}
on_all_children_bits(tcx, mir, move_data, move_path_index, &mut each_child);
}
pub(crate) fn on_all_drop_children_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
ctxt: &MoveDataParamEnv<'gcx, 'tcx>,
path: MovePathIndex,
mut each_child: F)
where F: FnMut(MovePathIndex)
{
on_all_children_bits(tcx, mir, &ctxt.move_data, path, |child| {
let place = &ctxt.move_data.move_paths[path].place;
let ty = place.ty(mir, tcx).to_ty(tcx);
debug!("on_all_drop_children_bits({:?}, {:?} : {:?})", path, place, ty);
let gcx = tcx.global_tcx();
let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
if erased_ty.needs_drop(gcx, ctxt.param_env) {
each_child(child);
} else {
debug!("on_all_drop_children_bits - skipping")
}
})
}
pub(crate) fn drop_flag_effects_for_function_entry<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
ctxt: &MoveDataParamEnv<'gcx, 'tcx>,
mut callback: F)
where F: FnMut(MovePathIndex, DropFlagState)
{
let move_data = &ctxt.move_data;
for arg in mir.args_iter() {
let place = mir::Place::Local(arg);
let lookup_result = move_data.rev_lookup.find(&place);
on_lookup_result_bits(tcx, mir, move_data,
lookup_result,
|mpi| callback(mpi, DropFlagState::Present));
}
}
pub(crate) fn drop_flag_effects_for_location<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
ctxt: &MoveDataParamEnv<'gcx, 'tcx>,
loc: Location,
mut callback: F)
where F: FnMut(MovePathIndex, DropFlagState)
{
let move_data = &ctxt.move_data;
debug!("drop_flag_effects_for_location({:?})", loc);
// first, move out of the RHS
for mi in &move_data.loc_map[loc] {
let path = mi.move_path_index(move_data);
debug!("moving out of path {:?}", move_data.move_paths[path]);
on_all_children_bits(tcx, mir, move_data,
path,
|mpi| callback(mpi, DropFlagState::Absent))
}
debug!("drop_flag_effects: assignment for location({:?})", loc);
for_location_inits(
tcx,
mir,
move_data,
loc,
|mpi| callback(mpi, DropFlagState::Present)
);
}
pub(crate) fn for_location_inits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
loc: Location,
mut callback: F)
where F: FnMut(MovePathIndex)
{
for ii in &move_data.init_loc_map[loc] {
let init = move_data.inits[*ii];
match init.kind {
InitKind::Deep => {
let path = init.path;
on_all_children_bits(tcx, mir, move_data,
path,
&mut callback)
},
InitKind::Shallow => {
let mpi = init.path;
callback(mpi);
}
InitKind::NonPanicPathOnly => (),
}
}
}
| is_terminal_path | identifier_name |
drop_flag_effects.rs | // Copyright 2012-2017 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 rustc::mir::{self, Mir, Location};
use rustc::ty::{self, TyCtxt};
use util::elaborate_drops::DropFlagState;
use super::{MoveDataParamEnv};
use super::indexes::MovePathIndex;
use super::move_paths::{MoveData, LookupResult, InitKind};
pub fn move_path_children_matching<'tcx, F>(move_data: &MoveData<'tcx>,
path: MovePathIndex,
mut cond: F)
-> Option<MovePathIndex>
where F: FnMut(&mir::PlaceProjection<'tcx>) -> bool
{
let mut next_child = move_data.move_paths[path].first_child;
while let Some(child_index) = next_child {
match move_data.move_paths[child_index].place {
mir::Place::Projection(ref proj) => {
if cond(proj) {
return Some(child_index)
}
}
_ => {}
}
next_child = move_data.move_paths[child_index].next_sibling;
}
None
}
/// When enumerating the child fragments of a path, don't recurse into
/// paths (1.) past arrays, slices, and pointers, nor (2.) into a type
/// that implements `Drop`.
///
/// Places behind references or arrays are not tracked by elaboration
/// and are always assumed to be initialized when accessible. As
/// references and indexes can be reseated, trying to track them can
/// only lead to trouble.
///
/// Places behind ADT's with a Drop impl are not tracked by
/// elaboration since they can never have a drop-flag state that
/// differs from that of the parent with the Drop impl.
///
/// In both cases, the contents can only be accessed if and only if
/// their parents are initialized. This implies for example that there
/// is no need to maintain separate drop flags to track such state.
///
/// FIXME: we have to do something for moving slice patterns.
fn place_contents_drop_state_cannot_differ<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
place: &mir::Place<'tcx>) -> bool {
let ty = place.ty(mir, tcx).to_ty(tcx);
match ty.sty {
ty::Array(..) => |
ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => {
debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} refd => true",
place, ty);
true
}
ty::Adt(def, _) if (def.has_dtor(tcx) && !def.is_box()) || def.is_union() => {
debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} Drop => true",
place, ty);
true
}
_ => {
false
}
}
}
pub(crate) fn on_lookup_result_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
lookup_result: LookupResult,
each_child: F)
where F: FnMut(MovePathIndex)
{
match lookup_result {
LookupResult::Parent(..) => {
// access to untracked value - do not touch children
}
LookupResult::Exact(e) => {
on_all_children_bits(tcx, mir, move_data, e, each_child)
}
}
}
pub(crate) fn on_all_children_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
move_path_index: MovePathIndex,
mut each_child: F)
where F: FnMut(MovePathIndex)
{
fn is_terminal_path<'a, 'gcx, 'tcx>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
path: MovePathIndex) -> bool
{
place_contents_drop_state_cannot_differ(
tcx, mir, &move_data.move_paths[path].place)
}
fn on_all_children_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
move_path_index: MovePathIndex,
each_child: &mut F)
where F: FnMut(MovePathIndex)
{
each_child(move_path_index);
if is_terminal_path(tcx, mir, move_data, move_path_index) {
return
}
let mut next_child_index = move_data.move_paths[move_path_index].first_child;
while let Some(child_index) = next_child_index {
on_all_children_bits(tcx, mir, move_data, child_index, each_child);
next_child_index = move_data.move_paths[child_index].next_sibling;
}
}
on_all_children_bits(tcx, mir, move_data, move_path_index, &mut each_child);
}
pub(crate) fn on_all_drop_children_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
ctxt: &MoveDataParamEnv<'gcx, 'tcx>,
path: MovePathIndex,
mut each_child: F)
where F: FnMut(MovePathIndex)
{
on_all_children_bits(tcx, mir, &ctxt.move_data, path, |child| {
let place = &ctxt.move_data.move_paths[path].place;
let ty = place.ty(mir, tcx).to_ty(tcx);
debug!("on_all_drop_children_bits({:?}, {:?} : {:?})", path, place, ty);
let gcx = tcx.global_tcx();
let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
if erased_ty.needs_drop(gcx, ctxt.param_env) {
each_child(child);
} else {
debug!("on_all_drop_children_bits - skipping")
}
})
}
pub(crate) fn drop_flag_effects_for_function_entry<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
ctxt: &MoveDataParamEnv<'gcx, 'tcx>,
mut callback: F)
where F: FnMut(MovePathIndex, DropFlagState)
{
let move_data = &ctxt.move_data;
for arg in mir.args_iter() {
let place = mir::Place::Local(arg);
let lookup_result = move_data.rev_lookup.find(&place);
on_lookup_result_bits(tcx, mir, move_data,
lookup_result,
|mpi| callback(mpi, DropFlagState::Present));
}
}
pub(crate) fn drop_flag_effects_for_location<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
ctxt: &MoveDataParamEnv<'gcx, 'tcx>,
loc: Location,
mut callback: F)
where F: FnMut(MovePathIndex, DropFlagState)
{
let move_data = &ctxt.move_data;
debug!("drop_flag_effects_for_location({:?})", loc);
// first, move out of the RHS
for mi in &move_data.loc_map[loc] {
let path = mi.move_path_index(move_data);
debug!("moving out of path {:?}", move_data.move_paths[path]);
on_all_children_bits(tcx, mir, move_data,
path,
|mpi| callback(mpi, DropFlagState::Absent))
}
debug!("drop_flag_effects: assignment for location({:?})", loc);
for_location_inits(
tcx,
mir,
move_data,
loc,
|mpi| callback(mpi, DropFlagState::Present)
);
}
pub(crate) fn for_location_inits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
loc: Location,
mut callback: F)
where F: FnMut(MovePathIndex)
{
for ii in &move_data.init_loc_map[loc] {
let init = move_data.inits[*ii];
match init.kind {
InitKind::Deep => {
let path = init.path;
on_all_children_bits(tcx, mir, move_data,
path,
&mut callback)
},
InitKind::Shallow => {
let mpi = init.path;
callback(mpi);
}
InitKind::NonPanicPathOnly => (),
}
}
}
| {
debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false",
place, ty);
false
} | conditional_block |
drop_flag_effects.rs | // Copyright 2012-2017 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 rustc::mir::{self, Mir, Location};
use rustc::ty::{self, TyCtxt};
use util::elaborate_drops::DropFlagState;
use super::{MoveDataParamEnv};
use super::indexes::MovePathIndex;
use super::move_paths::{MoveData, LookupResult, InitKind};
pub fn move_path_children_matching<'tcx, F>(move_data: &MoveData<'tcx>,
path: MovePathIndex,
mut cond: F)
-> Option<MovePathIndex>
where F: FnMut(&mir::PlaceProjection<'tcx>) -> bool
{
let mut next_child = move_data.move_paths[path].first_child;
while let Some(child_index) = next_child {
match move_data.move_paths[child_index].place {
mir::Place::Projection(ref proj) => {
if cond(proj) {
return Some(child_index)
}
}
_ => {}
}
next_child = move_data.move_paths[child_index].next_sibling;
}
None
}
/// When enumerating the child fragments of a path, don't recurse into
/// paths (1.) past arrays, slices, and pointers, nor (2.) into a type
/// that implements `Drop`.
///
/// Places behind references or arrays are not tracked by elaboration
/// and are always assumed to be initialized when accessible. As
/// references and indexes can be reseated, trying to track them can
/// only lead to trouble.
///
/// Places behind ADT's with a Drop impl are not tracked by
/// elaboration since they can never have a drop-flag state that
/// differs from that of the parent with the Drop impl.
///
/// In both cases, the contents can only be accessed if and only if
/// their parents are initialized. This implies for example that there
/// is no need to maintain separate drop flags to track such state.
///
/// FIXME: we have to do something for moving slice patterns.
fn place_contents_drop_state_cannot_differ<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
place: &mir::Place<'tcx>) -> bool |
pub(crate) fn on_lookup_result_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
lookup_result: LookupResult,
each_child: F)
where F: FnMut(MovePathIndex)
{
match lookup_result {
LookupResult::Parent(..) => {
// access to untracked value - do not touch children
}
LookupResult::Exact(e) => {
on_all_children_bits(tcx, mir, move_data, e, each_child)
}
}
}
pub(crate) fn on_all_children_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
move_path_index: MovePathIndex,
mut each_child: F)
where F: FnMut(MovePathIndex)
{
fn is_terminal_path<'a, 'gcx, 'tcx>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
path: MovePathIndex) -> bool
{
place_contents_drop_state_cannot_differ(
tcx, mir, &move_data.move_paths[path].place)
}
fn on_all_children_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
move_path_index: MovePathIndex,
each_child: &mut F)
where F: FnMut(MovePathIndex)
{
each_child(move_path_index);
if is_terminal_path(tcx, mir, move_data, move_path_index) {
return
}
let mut next_child_index = move_data.move_paths[move_path_index].first_child;
while let Some(child_index) = next_child_index {
on_all_children_bits(tcx, mir, move_data, child_index, each_child);
next_child_index = move_data.move_paths[child_index].next_sibling;
}
}
on_all_children_bits(tcx, mir, move_data, move_path_index, &mut each_child);
}
pub(crate) fn on_all_drop_children_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
ctxt: &MoveDataParamEnv<'gcx, 'tcx>,
path: MovePathIndex,
mut each_child: F)
where F: FnMut(MovePathIndex)
{
on_all_children_bits(tcx, mir, &ctxt.move_data, path, |child| {
let place = &ctxt.move_data.move_paths[path].place;
let ty = place.ty(mir, tcx).to_ty(tcx);
debug!("on_all_drop_children_bits({:?}, {:?} : {:?})", path, place, ty);
let gcx = tcx.global_tcx();
let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
if erased_ty.needs_drop(gcx, ctxt.param_env) {
each_child(child);
} else {
debug!("on_all_drop_children_bits - skipping")
}
})
}
pub(crate) fn drop_flag_effects_for_function_entry<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
ctxt: &MoveDataParamEnv<'gcx, 'tcx>,
mut callback: F)
where F: FnMut(MovePathIndex, DropFlagState)
{
let move_data = &ctxt.move_data;
for arg in mir.args_iter() {
let place = mir::Place::Local(arg);
let lookup_result = move_data.rev_lookup.find(&place);
on_lookup_result_bits(tcx, mir, move_data,
lookup_result,
|mpi| callback(mpi, DropFlagState::Present));
}
}
pub(crate) fn drop_flag_effects_for_location<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
ctxt: &MoveDataParamEnv<'gcx, 'tcx>,
loc: Location,
mut callback: F)
where F: FnMut(MovePathIndex, DropFlagState)
{
let move_data = &ctxt.move_data;
debug!("drop_flag_effects_for_location({:?})", loc);
// first, move out of the RHS
for mi in &move_data.loc_map[loc] {
let path = mi.move_path_index(move_data);
debug!("moving out of path {:?}", move_data.move_paths[path]);
on_all_children_bits(tcx, mir, move_data,
path,
|mpi| callback(mpi, DropFlagState::Absent))
}
debug!("drop_flag_effects: assignment for location({:?})", loc);
for_location_inits(
tcx,
mir,
move_data,
loc,
|mpi| callback(mpi, DropFlagState::Present)
);
}
pub(crate) fn for_location_inits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
loc: Location,
mut callback: F)
where F: FnMut(MovePathIndex)
{
for ii in &move_data.init_loc_map[loc] {
let init = move_data.inits[*ii];
match init.kind {
InitKind::Deep => {
let path = init.path;
on_all_children_bits(tcx, mir, move_data,
path,
&mut callback)
},
InitKind::Shallow => {
let mpi = init.path;
callback(mpi);
}
InitKind::NonPanicPathOnly => (),
}
}
}
| {
let ty = place.ty(mir, tcx).to_ty(tcx);
match ty.sty {
ty::Array(..) => {
debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false",
place, ty);
false
}
ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => {
debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} refd => true",
place, ty);
true
}
ty::Adt(def, _) if (def.has_dtor(tcx) && !def.is_box()) || def.is_union() => {
debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} Drop => true",
place, ty);
true
}
_ => {
false
}
}
} | identifier_body |
drop_flag_effects.rs | // Copyright 2012-2017 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 rustc::mir::{self, Mir, Location};
use rustc::ty::{self, TyCtxt};
use util::elaborate_drops::DropFlagState;
use super::{MoveDataParamEnv};
use super::indexes::MovePathIndex; | use super::move_paths::{MoveData, LookupResult, InitKind};
pub fn move_path_children_matching<'tcx, F>(move_data: &MoveData<'tcx>,
path: MovePathIndex,
mut cond: F)
-> Option<MovePathIndex>
where F: FnMut(&mir::PlaceProjection<'tcx>) -> bool
{
let mut next_child = move_data.move_paths[path].first_child;
while let Some(child_index) = next_child {
match move_data.move_paths[child_index].place {
mir::Place::Projection(ref proj) => {
if cond(proj) {
return Some(child_index)
}
}
_ => {}
}
next_child = move_data.move_paths[child_index].next_sibling;
}
None
}
/// When enumerating the child fragments of a path, don't recurse into
/// paths (1.) past arrays, slices, and pointers, nor (2.) into a type
/// that implements `Drop`.
///
/// Places behind references or arrays are not tracked by elaboration
/// and are always assumed to be initialized when accessible. As
/// references and indexes can be reseated, trying to track them can
/// only lead to trouble.
///
/// Places behind ADT's with a Drop impl are not tracked by
/// elaboration since they can never have a drop-flag state that
/// differs from that of the parent with the Drop impl.
///
/// In both cases, the contents can only be accessed if and only if
/// their parents are initialized. This implies for example that there
/// is no need to maintain separate drop flags to track such state.
///
/// FIXME: we have to do something for moving slice patterns.
fn place_contents_drop_state_cannot_differ<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
place: &mir::Place<'tcx>) -> bool {
let ty = place.ty(mir, tcx).to_ty(tcx);
match ty.sty {
ty::Array(..) => {
debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false",
place, ty);
false
}
ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => {
debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} refd => true",
place, ty);
true
}
ty::Adt(def, _) if (def.has_dtor(tcx) && !def.is_box()) || def.is_union() => {
debug!("place_contents_drop_state_cannot_differ place: {:?} ty: {:?} Drop => true",
place, ty);
true
}
_ => {
false
}
}
}
pub(crate) fn on_lookup_result_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
lookup_result: LookupResult,
each_child: F)
where F: FnMut(MovePathIndex)
{
match lookup_result {
LookupResult::Parent(..) => {
// access to untracked value - do not touch children
}
LookupResult::Exact(e) => {
on_all_children_bits(tcx, mir, move_data, e, each_child)
}
}
}
pub(crate) fn on_all_children_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
move_path_index: MovePathIndex,
mut each_child: F)
where F: FnMut(MovePathIndex)
{
fn is_terminal_path<'a, 'gcx, 'tcx>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
path: MovePathIndex) -> bool
{
place_contents_drop_state_cannot_differ(
tcx, mir, &move_data.move_paths[path].place)
}
fn on_all_children_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
move_path_index: MovePathIndex,
each_child: &mut F)
where F: FnMut(MovePathIndex)
{
each_child(move_path_index);
if is_terminal_path(tcx, mir, move_data, move_path_index) {
return
}
let mut next_child_index = move_data.move_paths[move_path_index].first_child;
while let Some(child_index) = next_child_index {
on_all_children_bits(tcx, mir, move_data, child_index, each_child);
next_child_index = move_data.move_paths[child_index].next_sibling;
}
}
on_all_children_bits(tcx, mir, move_data, move_path_index, &mut each_child);
}
pub(crate) fn on_all_drop_children_bits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
ctxt: &MoveDataParamEnv<'gcx, 'tcx>,
path: MovePathIndex,
mut each_child: F)
where F: FnMut(MovePathIndex)
{
on_all_children_bits(tcx, mir, &ctxt.move_data, path, |child| {
let place = &ctxt.move_data.move_paths[path].place;
let ty = place.ty(mir, tcx).to_ty(tcx);
debug!("on_all_drop_children_bits({:?}, {:?} : {:?})", path, place, ty);
let gcx = tcx.global_tcx();
let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
if erased_ty.needs_drop(gcx, ctxt.param_env) {
each_child(child);
} else {
debug!("on_all_drop_children_bits - skipping")
}
})
}
pub(crate) fn drop_flag_effects_for_function_entry<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
ctxt: &MoveDataParamEnv<'gcx, 'tcx>,
mut callback: F)
where F: FnMut(MovePathIndex, DropFlagState)
{
let move_data = &ctxt.move_data;
for arg in mir.args_iter() {
let place = mir::Place::Local(arg);
let lookup_result = move_data.rev_lookup.find(&place);
on_lookup_result_bits(tcx, mir, move_data,
lookup_result,
|mpi| callback(mpi, DropFlagState::Present));
}
}
pub(crate) fn drop_flag_effects_for_location<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
ctxt: &MoveDataParamEnv<'gcx, 'tcx>,
loc: Location,
mut callback: F)
where F: FnMut(MovePathIndex, DropFlagState)
{
let move_data = &ctxt.move_data;
debug!("drop_flag_effects_for_location({:?})", loc);
// first, move out of the RHS
for mi in &move_data.loc_map[loc] {
let path = mi.move_path_index(move_data);
debug!("moving out of path {:?}", move_data.move_paths[path]);
on_all_children_bits(tcx, mir, move_data,
path,
|mpi| callback(mpi, DropFlagState::Absent))
}
debug!("drop_flag_effects: assignment for location({:?})", loc);
for_location_inits(
tcx,
mir,
move_data,
loc,
|mpi| callback(mpi, DropFlagState::Present)
);
}
pub(crate) fn for_location_inits<'a, 'gcx, 'tcx, F>(
tcx: TyCtxt<'a, 'gcx, 'tcx>,
mir: &Mir<'tcx>,
move_data: &MoveData<'tcx>,
loc: Location,
mut callback: F)
where F: FnMut(MovePathIndex)
{
for ii in &move_data.init_loc_map[loc] {
let init = move_data.inits[*ii];
match init.kind {
InitKind::Deep => {
let path = init.path;
on_all_children_bits(tcx, mir, move_data,
path,
&mut callback)
},
InitKind::Shallow => {
let mpi = init.path;
callback(mpi);
}
InitKind::NonPanicPathOnly => (),
}
}
} | random_line_split |
|
test-bi-promise-constructor-all-iterable.js | /*---
{
"skip": true
}
---*/
/*===
next called, done: false
next called, done: false
next called, done: false
next called, done: true
done
all fulfill: foo,bar,quux
===*/
var iterable = {};
var index = 0;
var values = [
// Plain values, Promise, a Promise returning a generic thenable.
'foo',
Promise.resolve('bar'),
Promise.resolve('dummy').then(function () {
return {
then: function (resolve, reject) {
resolve('quux');
}
}
})
];
iterable[Symbol.iterator] = function () {
return {
next: function () {
var done = index >= values.length;
var value = values[index++];
print('next called, done:', done);
return { value: value, done: done }; | }
};
};
var P = Promise.all(iterable);
P.then(function (v) {
print('all fulfill:', String(v));
}, function (e) {
print('all reject:', String(e));
});
print('done'); | random_line_split |
|
elfinder.es.js | /*
* Spanish translation
* @author Alex Vavilin <[email protected]>
* @version 2010-09-22
*/
(function($) {
if (elFinder && elFinder.prototype.options && elFinder.prototype.options.i18n)
elFinder.prototype.options.i18n.es = {
/* errors */
'Root directory does not exists' : 'El directorio raíz no existe',
'Unable to connect to backend' : 'No se ha podido establecer la conexión con el servidor',
'Access denied' : 'Acceso denegado',
'Invalid backend configuration' : 'La respuesta del servidor es incorrecta',
'Unknown command' : 'Comando desconocido',
'Command not allowed' : 'No puede ejecutar este comando',
'Invalid parameters' : 'Parámetros incorrectos',
'File not found' : 'Fichero no encontrado',
'Invalid name' : 'Nombre incorrecto',
'File or folder with the same name already exists' : 'Ya existe un fichero o un directorio con este nombre',
'Unable to rename file' : 'No se ha podido cambiar el nombre al directorio',
'Unable to create folder' : 'No se ha podido crear el directorio',
'Unable to create file' : 'No se ha podido crear el fichero',
'No file to upload' : 'No hay ficheros para subir',
'Select at least one file to upload' : 'Seleccione, como mínimo un fichero, para subir',
'File exceeds the maximum allowed filesize' : 'El tamaño del fichero es más grande que el tamaño máximo autorizado',
'Data exceeds the maximum allowed size' : 'Los datos exceden el tamaño máximo permitido',
'Not allowed file type' : 'Tipo de fichero no permitido',
'Unable to upload file' : 'No se ha podido subir el fichero',
'Unable to upload files' : 'No se han podido subir los ficheros',
'Unable to remove file' : 'No se ha podido eliminar el fichero',
'Unable to save uploaded file' : 'No se ha podido guardar el fichero subido',
'Some files was not uploaded' : 'Algunos ficheros no han podido ser subidos',
'Unable to copy into itself' : 'No se puede copiar dentro de sí mismo',
'Unable to move files' : 'No se ha podido mover los ficheros',
'Unable to copy files' : 'No se ha podido copiar los ficheros',
'Unable to create file copy' : 'No se ha podido crear copia del fichero',
'File is not an image' : 'Este fichero no es una imagen',
'Unable to resize image' : 'No se han podido cambiar las dimensiones de la imagen',
'Unable to write to file' : 'No se ha podido escribir el fichero',
'Unable to create archive' : 'No se ha podido crear el archivo',
'Unable to extract files from archive' : 'No se ha podido extraer fichero desde archivo',
'Unable to open broken link' : 'No se puede abrir un enlace roto',
'File URL disabled by connector config' : 'El acceso a las rutas de los ficheros está prohibido en la configuración del conector',
/* statusbar */
'items' : 'objetos',
'selected items' : 'objetos seleccionados',
/* commands/buttons */
'Back' : 'Atrás',
'Reload' : 'Refrescar',
'Open' : 'Abrir',
'Preview with Quick Look' : 'Vista previa',
'Select file' : 'Seleccionar fichero',
'New folder' : 'Nueva carpeta',
'New text file' : 'Nuevo fichero',
'Upload files' : 'Subir ficheros',
'Copy' : 'Copiar',
'Cut' : 'Cortar',
'Paste' : 'Pegar',
'Duplicate' : 'Duplicar',
'Remove' : 'Eliminar',
'Rename' : 'Cambiar nombre',
'Edit text file' : 'Editar fichero',
'View as icons' : 'Iconos',
'View as list' : 'Lista',
| 'Create archive' : 'Nuevo archivo',
'Uncompress archive' : 'Extraer archivo',
'Get info' : 'Propiedades',
'Help' : 'Ayuda',
'Dock/undock filemanager window' : 'Despegar/pegar el gestor de ficheros a la página',
/* upload/get info dialogs */
'Maximum allowed files size' : 'Tamaño máximo del fichero',
'Add field' : 'Añadir campo',
'File info' : 'Propiedades de fichero',
'Folder info' : 'Propiedades de carpeta',
'Name' : 'Nombre',
'Kind' : 'Tipo',
'Size' : 'Tamaño',
'Modified' : 'Modificado',
'Permissions' : 'Acceso',
'Link to' : 'Enlaza con',
'Dimensions' : 'Dimensiones',
'Confirmation required' : 'Se requiere confirmación',
'Are you sure you want to remove files?<br /> This cannot be undone!' : '¿Está seguir que desea eliminar el fichero? <br />Esta acción es irreversible.',
/* permissions */
'read' : 'lectura',
'write' : 'escritura',
'remove' : 'eliminación',
/* dates */
'Jan' : 'Ene',
'Feb' : 'Feb',
'Mar' : 'Mar',
'Apr' : 'Abr',
'May' : 'May',
'Jun' : 'Jun',
'Jul' : 'Jul',
'Aug' : 'Ago',
'Sep' : 'Sep',
'Oct' : 'Oct',
'Nov' : 'Nov',
'Dec' : 'Dec',
'Today' : 'Hoy',
'Yesterday' : 'Ayer',
/* mimetypes */
'Unknown' : 'Desconocido',
'Folder' : 'Carpeta',
'Alias' : 'Enlace',
'Broken alias' : 'Enlace roto',
'Plain text' : 'Texto',
'Postscript document' : 'Documento postscript',
'Application' : 'Aplicación',
'Microsoft Office document' : 'Documento Microsoft Office',
'Microsoft Word document' : 'Documento Microsoft Word',
'Microsoft Excel document' : 'Documento Microsoft Excel',
'Microsoft Powerpoint presentation' : 'Documento Microsoft Powerpoint',
'Open Office document' : 'Documento Open Office',
'Flash application' : 'Aplicación Flash',
'XML document' : 'Documento XML',
'Bittorrent file' : 'Fichero bittorrent',
'7z archive' : 'Archivo 7z',
'TAR archive' : 'Archivo TAR',
'GZIP archive' : 'Archivo GZIP',
'BZIP archive' : 'Archivo BZIP',
'ZIP archive' : 'Archivo ZIP',
'RAR archive' : 'Archivo RAR',
'Javascript application' : 'Aplicación Javascript',
'PHP source' : 'Documento PHP',
'HTML document' : 'Documento HTML',
'Javascript source' : 'Documento Javascript',
'CSS style sheet' : 'Documento CSS',
'C source' : 'Documento C',
'C++ source' : 'Documento C++',
'Unix shell script' : 'Script Unix shell',
'Python source' : 'Documento Python',
'Java source' : 'Documento Java',
'Ruby source' : 'Documento Ruby',
'Perl script' : 'Script Perl',
'BMP image' : 'Imagen BMP',
'JPEG image' : 'Imagen JPEG',
'GIF Image' : 'Imagen GIF',
'PNG Image' : 'Imagen PNG',
'TIFF image' : 'Imagen TIFF',
'TGA image' : 'Imagen TGA',
'Adobe Photoshop image' : 'Imagen Adobe Photoshop',
'MPEG audio' : 'Audio MPEG',
'MIDI audio' : 'Audio MIDI',
'Ogg Vorbis audio' : 'Audio Ogg Vorbis',
'MP4 audio' : 'Audio MP4',
'WAV audio' : 'Audio WAV',
'DV video' : 'Video DV',
'MP4 video' : 'Video MP4',
'MPEG video' : 'Video MPEG',
'AVI video' : 'Video AVI',
'Quicktime video' : 'Video Quicktime',
'WM video' : 'Video WM',
'Flash video' : 'Video Flash',
'Matroska video' : 'Video Matroska',
// 'Shortcuts' : 'Клавиши',
'Select all files' : 'Seleccionar todos ficheros',
'Copy/Cut/Paste files' : 'Copiar/Cortar/Pegar ficheros',
'Open selected file/folder' : 'Abrir carpeta/fichero',
'Open/close QuickLook window' : 'Abrir/Cerrar la ventana de vista previa',
'Remove selected files' : 'Eliminar ficheros seleccionados',
'Selected files or current directory info' : 'Información sobre los ficheros seleccionados en la carpeta actual',
'Create new directory' : 'Nueva carpeta',
'Open upload files form' : 'Abrir ventana para subir ficheros',
'Select previous file' : 'Seleccionar el fichero anterior',
'Select next file' : 'Seleccionar el fichero siguiente',
'Return into previous folder' : 'Volver a la carpeta anterior',
'Increase/decrease files selection' : 'Aumentar/disminuir la selección de ficheros',
'Authors' : 'Autores',
'Sponsors' : 'Colaboradores',
'elFinder: Web file manager' : 'elFinder: Gestor de ficheros para la web',
'Version' : 'Versión',
'Copyright: Studio 42 LTD' : 'Copyright: Studio 42',
'Donate to support project development' : 'Ayuda al desarrollo',
'Javascripts/PHP programming: Dmitry (dio) Levashov, [email protected]' : 'Programación Javascripts/php: Dmitry (dio) Levashov, [email protected]',
'Python programming, techsupport: Troex Nevelin, [email protected]' : 'Programación Python, soporte técnico: Troex Nevelin, [email protected]',
'Design: Valentin Razumnih' : 'Diseño: Valentin Razumnyh',
'Spanish localization' : 'Traducción al español',
'Icons' : 'Iconos',
'License: BSD License' : 'Licencia: BSD License',
'elFinder documentation' : 'Documentación elFinder',
'Simple and usefull Content Management System' : 'Un CMS sencillo y cómodo',
'Support project development and we will place here info about you' : 'Ayude al desarrollo del producto y la información sobre usted aparecerá aqui.',
'Contacts us if you need help integrating elFinder in you products' : 'Pregúntenos si quiere integrar elFinder en su producto.',
'elFinder support following shortcuts' : 'elFinder soporta los siguientes atajos de teclado',
'helpText' : 'elFinder funciona igual que el gestor de ficheros de su PC. <br />Puede manipular los ficheros con la ayuda del panel superior, el menu o bien con atajos de teclado. Para mover fichero/carpetas simplemente arrastrelos a la carpeta deseada. Si simultáneamente presiona la tecla Shift los ficheros se copiarán.'
};
})(jQuery); | 'Resize image' : 'Tamaño de imagen',
| random_line_split |
register.component.ts | import { Component, OnInit} from '@angular/core';
import { Router } from '@angular/router';
import { Registration } from '../../core/domain/registration';
import { OperationResult } from '../../core/domain/operationResult';
import { MembershipService } from '../../core/services/membership.service';
import { NotificationService } from '../../core/services/notification.service';
@Component({
selector: 'register',
providers: [MembershipService, NotificationService],
templateUrl: './app/components/account/register.component.html'
})
export class RegisterComponent implements OnInit {
private _newUser: Registration;
constructor(public membershipService: MembershipService,
public notificationService: NotificationService,
public router: Router) { }
ngOnInit() {
| register(): void {
var _registrationResult: OperationResult = new OperationResult(false, '');
this.membershipService.register(this._newUser)
.subscribe(res => {
_registrationResult.Succeeded = res.Succeeded;
_registrationResult.Message = res.Message;
},
error => console.error('Error: ' + error),
() => {
if (_registrationResult.Succeeded) {
this.notificationService.printSuccessMessage('Dear ' + this._newUser.Username + ', please login with your credentials');
this.router.navigate(['account/login']);
}
else {
this.notificationService.printErrorMessage(_registrationResult.Message);
}
});
};
} | this._newUser = new Registration('', '', '');
}
| identifier_body |
register.component.ts | import { Component, OnInit} from '@angular/core';
import { Router } from '@angular/router';
import { Registration } from '../../core/domain/registration';
import { OperationResult } from '../../core/domain/operationResult'; | import { MembershipService } from '../../core/services/membership.service';
import { NotificationService } from '../../core/services/notification.service';
@Component({
selector: 'register',
providers: [MembershipService, NotificationService],
templateUrl: './app/components/account/register.component.html'
})
export class RegisterComponent implements OnInit {
private _newUser: Registration;
constructor(public membershipService: MembershipService,
public notificationService: NotificationService,
public router: Router) { }
ngOnInit() {
this._newUser = new Registration('', '', '');
}
register(): void {
var _registrationResult: OperationResult = new OperationResult(false, '');
this.membershipService.register(this._newUser)
.subscribe(res => {
_registrationResult.Succeeded = res.Succeeded;
_registrationResult.Message = res.Message;
},
error => console.error('Error: ' + error),
() => {
if (_registrationResult.Succeeded) {
this.notificationService.printSuccessMessage('Dear ' + this._newUser.Username + ', please login with your credentials');
this.router.navigate(['account/login']);
}
else {
this.notificationService.printErrorMessage(_registrationResult.Message);
}
});
};
} | random_line_split |
|
register.component.ts | import { Component, OnInit} from '@angular/core';
import { Router } from '@angular/router';
import { Registration } from '../../core/domain/registration';
import { OperationResult } from '../../core/domain/operationResult';
import { MembershipService } from '../../core/services/membership.service';
import { NotificationService } from '../../core/services/notification.service';
@Component({
selector: 'register',
providers: [MembershipService, NotificationService],
templateUrl: './app/components/account/register.component.html'
})
export class RegisterComponent implements OnInit {
private _newUser: Registration;
constructor(public membershipService: MembershipService,
public notificationService: NotificationService,
public router: Router) { }
ngOnInit() {
this._newUser = new Registration('', '', '');
}
register(): void {
var _registrationResult: OperationResult = new OperationResult(false, '');
this.membershipService.register(this._newUser)
.subscribe(res => {
_registrationResult.Succeeded = res.Succeeded;
_registrationResult.Message = res.Message;
},
error => console.error('Error: ' + error),
() => {
if (_registrationResult.Succeeded) {
this.notificationService.printSuccessMessage('Dear ' + this._newUser.Username + ', please login with your credentials');
this.router.navigate(['account/login']);
}
else {
| });
};
} | this.notificationService.printErrorMessage(_registrationResult.Message);
}
| conditional_block |
register.component.ts | import { Component, OnInit} from '@angular/core';
import { Router } from '@angular/router';
import { Registration } from '../../core/domain/registration';
import { OperationResult } from '../../core/domain/operationResult';
import { MembershipService } from '../../core/services/membership.service';
import { NotificationService } from '../../core/services/notification.service';
@Component({
selector: 'register',
providers: [MembershipService, NotificationService],
templateUrl: './app/components/account/register.component.html'
})
export class RegisterComponent implements OnInit {
private _newUser: Registration;
constructor(public membershipService: MembershipService,
public notificationService: NotificationService,
public router: Router) { }
ngOnInit() {
this._newUser = new Registration('', '', '');
}
re | : void {
var _registrationResult: OperationResult = new OperationResult(false, '');
this.membershipService.register(this._newUser)
.subscribe(res => {
_registrationResult.Succeeded = res.Succeeded;
_registrationResult.Message = res.Message;
},
error => console.error('Error: ' + error),
() => {
if (_registrationResult.Succeeded) {
this.notificationService.printSuccessMessage('Dear ' + this._newUser.Username + ', please login with your credentials');
this.router.navigate(['account/login']);
}
else {
this.notificationService.printErrorMessage(_registrationResult.Message);
}
});
};
} | gister() | identifier_name |
views.py | #!/usr/bin/python
from django.http import HttpResponse
from django.template import RequestContext, loader
from django.views.decorators.csrf import csrf_exempt
import django.shortcuts
from wlokalu.api import presence
#-----------------------------------------------------------------------------
from wlokalu.logging import getLogger, message as log
logger = getLogger(__name__)
#-----------------------------------------------------------------------------
@csrf_exempt
def list(request, nick = None):
|
#-----------------------------------------------------------------------------
# vim:ft=python:foldmethod=marker
| template = loader.get_template("list.html")
from django.core.urlresolvers import reverse
from forms import PresenceForm
form = PresenceForm()
if nick is not None:
form.initial['nick'] = nick
form_target = reverse(list, kwargs = {'nick': nick})
else:
form_target = reverse(list)
if request.POST.get('nick', '') != '':
context = {
'address': request.META['REMOTE_ADDR'],
'uri': request.META['REQUEST_URI'],
}
if 'enter' in request.POST:
presence.person_entered(request.POST['nick'], context)
else: # 'leave' in request.POST
presence.person_left(request.POST['nick'], context)
# tell the browser to reload the page, but with GET request
return django.shortcuts.redirect(request.path)
context = RequestContext(request, {
'form_target': form_target,
'form': form,
'present': presence.list_people(),
'sensors': presence.list_simple_sensors(),
'complex_sensors': presence.list_complex_sensors(),
})
return HttpResponse(template.render(context)) | identifier_body |
views.py | #!/usr/bin/python
from django.http import HttpResponse
from django.template import RequestContext, loader
from django.views.decorators.csrf import csrf_exempt
import django.shortcuts
from wlokalu.api import presence
#-----------------------------------------------------------------------------
from wlokalu.logging import getLogger, message as log
logger = getLogger(__name__)
#-----------------------------------------------------------------------------
@csrf_exempt
def list(request, nick = None):
template = loader.get_template("list.html")
from django.core.urlresolvers import reverse
from forms import PresenceForm
form = PresenceForm()
if nick is not None:
form.initial['nick'] = nick
form_target = reverse(list, kwargs = {'nick': nick})
else:
form_target = reverse(list)
if request.POST.get('nick', '') != '':
context = {
'address': request.META['REMOTE_ADDR'],
'uri': request.META['REQUEST_URI'],
}
if 'enter' in request.POST:
presence.person_entered(request.POST['nick'], context)
else: # 'leave' in request.POST
presence.person_left(request.POST['nick'], context) | 'form': form,
'present': presence.list_people(),
'sensors': presence.list_simple_sensors(),
'complex_sensors': presence.list_complex_sensors(),
})
return HttpResponse(template.render(context))
#-----------------------------------------------------------------------------
# vim:ft=python:foldmethod=marker | # tell the browser to reload the page, but with GET request
return django.shortcuts.redirect(request.path)
context = RequestContext(request, {
'form_target': form_target, | random_line_split |
views.py | #!/usr/bin/python
from django.http import HttpResponse
from django.template import RequestContext, loader
from django.views.decorators.csrf import csrf_exempt
import django.shortcuts
from wlokalu.api import presence
#-----------------------------------------------------------------------------
from wlokalu.logging import getLogger, message as log
logger = getLogger(__name__)
#-----------------------------------------------------------------------------
@csrf_exempt
def | (request, nick = None):
template = loader.get_template("list.html")
from django.core.urlresolvers import reverse
from forms import PresenceForm
form = PresenceForm()
if nick is not None:
form.initial['nick'] = nick
form_target = reverse(list, kwargs = {'nick': nick})
else:
form_target = reverse(list)
if request.POST.get('nick', '') != '':
context = {
'address': request.META['REMOTE_ADDR'],
'uri': request.META['REQUEST_URI'],
}
if 'enter' in request.POST:
presence.person_entered(request.POST['nick'], context)
else: # 'leave' in request.POST
presence.person_left(request.POST['nick'], context)
# tell the browser to reload the page, but with GET request
return django.shortcuts.redirect(request.path)
context = RequestContext(request, {
'form_target': form_target,
'form': form,
'present': presence.list_people(),
'sensors': presence.list_simple_sensors(),
'complex_sensors': presence.list_complex_sensors(),
})
return HttpResponse(template.render(context))
#-----------------------------------------------------------------------------
# vim:ft=python:foldmethod=marker
| list | identifier_name |
views.py | #!/usr/bin/python
from django.http import HttpResponse
from django.template import RequestContext, loader
from django.views.decorators.csrf import csrf_exempt
import django.shortcuts
from wlokalu.api import presence
#-----------------------------------------------------------------------------
from wlokalu.logging import getLogger, message as log
logger = getLogger(__name__)
#-----------------------------------------------------------------------------
@csrf_exempt
def list(request, nick = None):
template = loader.get_template("list.html")
from django.core.urlresolvers import reverse
from forms import PresenceForm
form = PresenceForm()
if nick is not None:
form.initial['nick'] = nick
form_target = reverse(list, kwargs = {'nick': nick})
else:
form_target = reverse(list)
if request.POST.get('nick', '') != '':
context = {
'address': request.META['REMOTE_ADDR'],
'uri': request.META['REQUEST_URI'],
}
if 'enter' in request.POST:
presence.person_entered(request.POST['nick'], context)
else: # 'leave' in request.POST
|
# tell the browser to reload the page, but with GET request
return django.shortcuts.redirect(request.path)
context = RequestContext(request, {
'form_target': form_target,
'form': form,
'present': presence.list_people(),
'sensors': presence.list_simple_sensors(),
'complex_sensors': presence.list_complex_sensors(),
})
return HttpResponse(template.render(context))
#-----------------------------------------------------------------------------
# vim:ft=python:foldmethod=marker
| presence.person_left(request.POST['nick'], context) | conditional_block |
webpack.horizon.config.js | const path = require('path')
const BannerPlugin = require('webpack/lib/BannerPlugin')
const DedupePlugin = require('webpack/lib/optimize/DedupePlugin')
const DefinePlugin = require('webpack/lib/DefinePlugin')
const OccurrenceOrderPlugin = require(
'webpack/lib/optimize/OccurrenceOrderPlugin')
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin')
const ProvidePlugin = require('webpack/lib/ProvidePlugin')
module.exports = function(buildTarget) {
const FILENAME = buildTarget.FILENAME
const DEV_BUILD = buildTarget.DEV_BUILD
const POLYFILL = buildTarget.POLYFILL
const SOURCEMAPS = !process.env.NO_SOURCEMAPS
return {
entry: {
horizon: POLYFILL ?
'./src/index-polyfill.js' :
'./src/index.js',
},
target: 'web',
output: {
path: path.resolve(__dirname, 'dist'),
filename: FILENAME,
library: 'Horizon', // window.Horizon if loaded by a script tag
libraryTarget: 'umd',
pathinfo: DEV_BUILD, // Add module filenames as comments in the bundle
devtoolModuleFilenameTemplate: DEV_BUILD ?
function(file) {
if (file.resourcePath.indexOf('webpack') >= 0) {
return `webpack:///${file.resourcePath}`
} else {
// Show correct paths in stack traces
return path.join('..', file.resourcePath)
.replace(/~/g, 'node_modules')
}
} :
null,
},
externals: [
function(context, request, callback) {
// Selected modules are not packaged into horizon.js. Webpack
// allows them to be required natively at runtime, either from
// filesystem (node) or window global.
if (!POLYFILL && /^rxjs\/?/.test(request)) {
callback(null, {
// If loaded via script tag, has to be at window.Rx when
// library loads
root: 'Rx', | commonjs2: 'rxjs',
amd: 'rxjs'
})
} else {
callback()
}
},
{ ws: 'commonjs ws' }
],
debug: DEV_BUILD,
devtool: SOURCEMAPS ? (DEV_BUILD ? 'source-map' : 'source-map') : false,
module: {
noParse: [
],
preLoaders: [],
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
cacheDirectory: true,
extends: path.resolve(__dirname, 'package.json'),
},
},
],
},
plugins: [
new BannerPlugin('__LICENSE__'),
// Possibility to replace constants such as `if (__DEV__)`
// and thus strip helpful warnings from production build:
new DefinePlugin({
'process.env.NODE_ENV': (DEV_BUILD ? 'development' : 'production'),
}),
new ProvidePlugin({
Promise: 'es6-promise',
}),
].concat(DEV_BUILD ? [] : [
new DedupePlugin(),
new OccurrenceOrderPlugin(),
new UglifyJsPlugin({
compress: {
screw_ie8: false,
warnings: false,
},
mangle: {
except: [],
},
}),
]),
node: {
// Don't include unneeded node libs in package
process: false,
fs: false,
__dirname: false,
__filename: false,
},
}
} | // Otherwise imported via `require('rx')`
commonjs: 'rxjs', | random_line_split |
webpack.horizon.config.js | const path = require('path')
const BannerPlugin = require('webpack/lib/BannerPlugin')
const DedupePlugin = require('webpack/lib/optimize/DedupePlugin')
const DefinePlugin = require('webpack/lib/DefinePlugin')
const OccurrenceOrderPlugin = require(
'webpack/lib/optimize/OccurrenceOrderPlugin')
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin')
const ProvidePlugin = require('webpack/lib/ProvidePlugin')
module.exports = function(buildTarget) {
const FILENAME = buildTarget.FILENAME
const DEV_BUILD = buildTarget.DEV_BUILD
const POLYFILL = buildTarget.POLYFILL
const SOURCEMAPS = !process.env.NO_SOURCEMAPS
return {
entry: {
horizon: POLYFILL ?
'./src/index-polyfill.js' :
'./src/index.js',
},
target: 'web',
output: {
path: path.resolve(__dirname, 'dist'),
filename: FILENAME,
library: 'Horizon', // window.Horizon if loaded by a script tag
libraryTarget: 'umd',
pathinfo: DEV_BUILD, // Add module filenames as comments in the bundle
devtoolModuleFilenameTemplate: DEV_BUILD ?
function(file) {
if (file.resourcePath.indexOf('webpack') >= 0) | else {
// Show correct paths in stack traces
return path.join('..', file.resourcePath)
.replace(/~/g, 'node_modules')
}
} :
null,
},
externals: [
function(context, request, callback) {
// Selected modules are not packaged into horizon.js. Webpack
// allows them to be required natively at runtime, either from
// filesystem (node) or window global.
if (!POLYFILL && /^rxjs\/?/.test(request)) {
callback(null, {
// If loaded via script tag, has to be at window.Rx when
// library loads
root: 'Rx',
// Otherwise imported via `require('rx')`
commonjs: 'rxjs',
commonjs2: 'rxjs',
amd: 'rxjs'
})
} else {
callback()
}
},
{ ws: 'commonjs ws' }
],
debug: DEV_BUILD,
devtool: SOURCEMAPS ? (DEV_BUILD ? 'source-map' : 'source-map') : false,
module: {
noParse: [
],
preLoaders: [],
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
cacheDirectory: true,
extends: path.resolve(__dirname, 'package.json'),
},
},
],
},
plugins: [
new BannerPlugin('__LICENSE__'),
// Possibility to replace constants such as `if (__DEV__)`
// and thus strip helpful warnings from production build:
new DefinePlugin({
'process.env.NODE_ENV': (DEV_BUILD ? 'development' : 'production'),
}),
new ProvidePlugin({
Promise: 'es6-promise',
}),
].concat(DEV_BUILD ? [] : [
new DedupePlugin(),
new OccurrenceOrderPlugin(),
new UglifyJsPlugin({
compress: {
screw_ie8: false,
warnings: false,
},
mangle: {
except: [],
},
}),
]),
node: {
// Don't include unneeded node libs in package
process: false,
fs: false,
__dirname: false,
__filename: false,
},
}
}
| {
return `webpack:///${file.resourcePath}`
} | conditional_block |
context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public |
//! Data needed by the layout thread.
use fnv::FnvHasher;
use gfx::display_list::{WebRenderImageInfo, OpaqueNode};
use gfx::font_cache_thread::FontCacheThread;
use gfx::font_context::FontContext;
use heapsize::HeapSizeOf;
use msg::constellation_msg::PipelineId;
use net_traits::image_cache::{CanRequestImages, ImageCache, ImageState};
use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder};
use opaque_node::OpaqueNodeMethods;
use parking_lot::RwLock;
use script_layout_interface::{PendingImage, PendingImageState};
use script_traits::Painter;
use script_traits::UntrustedNodeAddress;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::cell::{RefCell, RefMut};
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use std::sync::{Arc, Mutex};
use std::thread;
use style::context::RegisteredSpeculativePainter;
use style::context::SharedStyleContext;
thread_local!(static FONT_CONTEXT_KEY: RefCell<Option<FontContext>> = RefCell::new(None));
pub fn with_thread_local_font_context<F, R>(layout_context: &LayoutContext, f: F) -> R
where F: FnOnce(&mut FontContext) -> R
{
FONT_CONTEXT_KEY.with(|k| {
let mut font_context = k.borrow_mut();
if font_context.is_none() {
let font_cache_thread = layout_context.font_cache_thread.lock().unwrap().clone();
*font_context = Some(FontContext::new(font_cache_thread));
}
f(&mut RefMut::map(font_context, |x| x.as_mut().unwrap()))
})
}
pub fn heap_size_of_persistent_local_context() -> usize {
FONT_CONTEXT_KEY.with(|r| {
if let Some(ref context) = *r.borrow() {
context.heap_size_of_children()
} else {
0
}
})
}
/// Layout information shared among all workers. This must be thread-safe.
pub struct LayoutContext<'a> {
/// The pipeline id of this LayoutContext.
pub id: PipelineId,
/// Bits shared by the layout and style system.
pub style_context: SharedStyleContext<'a>,
/// Reference to the script thread image cache.
pub image_cache: Arc<ImageCache>,
/// Interface to the font cache thread.
pub font_cache_thread: Mutex<FontCacheThread>,
/// A cache of WebRender image info.
pub webrender_image_cache: Arc<RwLock<HashMap<(ServoUrl, UsePlaceholder),
WebRenderImageInfo,
BuildHasherDefault<FnvHasher>>>>,
/// Paint worklets
pub registered_painters: &'a RegisteredPainters,
/// A list of in-progress image loads to be shared with the script thread.
/// A None value means that this layout was not initiated by the script thread.
pub pending_images: Option<Mutex<Vec<PendingImage>>>,
/// A list of nodes that have just initiated a CSS transition.
/// A None value means that this layout was not initiated by the script thread.
pub newly_transitioning_nodes: Option<Mutex<Vec<UntrustedNodeAddress>>>,
}
impl<'a> Drop for LayoutContext<'a> {
fn drop(&mut self) {
if !thread::panicking() {
if let Some(ref pending_images) = self.pending_images {
assert!(pending_images.lock().unwrap().is_empty());
}
}
}
}
impl<'a> LayoutContext<'a> {
#[inline(always)]
pub fn shared_context(&self) -> &SharedStyleContext {
&self.style_context
}
pub fn get_or_request_image_or_meta(&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<ImageOrMetadataAvailable> {
//XXXjdm For cases where we do not request an image, we still need to
// ensure the node gets another script-initiated reflow or it
// won't be requested at all.
let can_request = if self.pending_images.is_some() {
CanRequestImages::Yes
} else {
CanRequestImages::No
};
// See if the image is already available
let result = self.image_cache.find_image_or_metadata(url.clone(),
use_placeholder,
can_request);
match result {
Ok(image_or_metadata) => Some(image_or_metadata),
// Image failed to load, so just return nothing
Err(ImageState::LoadError) => None,
// Not yet requested - request image or metadata from the cache
Err(ImageState::NotRequested(id)) => {
let image = PendingImage {
state: PendingImageState::Unrequested(url),
node: node.to_untrusted_node_address(),
id: id,
};
self.pending_images.as_ref().unwrap().lock().unwrap().push(image);
None
}
// Image has been requested, is still pending. Return no image for this paint loop.
// When the image loads it will trigger a reflow and/or repaint.
Err(ImageState::Pending(id)) => {
//XXXjdm if self.pending_images is not available, we should make sure that
// this node gets marked dirty again so it gets a script-initiated
// reflow that deals with this properly.
if let Some(ref pending_images) = self.pending_images {
let image = PendingImage {
state: PendingImageState::PendingResponse,
node: node.to_untrusted_node_address(),
id: id,
};
pending_images.lock().unwrap().push(image);
}
None
}
}
}
pub fn get_webrender_image_for_url(&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<WebRenderImageInfo> {
if let Some(existing_webrender_image) = self.webrender_image_cache
.read()
.get(&(url.clone(), use_placeholder)) {
return Some((*existing_webrender_image).clone())
}
match self.get_or_request_image_or_meta(node, url.clone(), use_placeholder) {
Some(ImageOrMetadataAvailable::ImageAvailable(image, _)) => {
let image_info = WebRenderImageInfo::from_image(&*image);
if image_info.key.is_none() {
Some(image_info)
} else {
let mut webrender_image_cache = self.webrender_image_cache.write();
webrender_image_cache.insert((url, use_placeholder),
image_info);
Some(image_info)
}
}
None | Some(ImageOrMetadataAvailable::MetadataAvailable(_)) => None,
}
}
}
/// A registered painter
pub trait RegisteredPainter: RegisteredSpeculativePainter + Painter {}
/// A set of registered painters
pub trait RegisteredPainters: Sync {
/// Look up a painter
fn get(&self, name: &Atom) -> Option<&RegisteredPainter>;
} | * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | random_line_split |
context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Data needed by the layout thread.
use fnv::FnvHasher;
use gfx::display_list::{WebRenderImageInfo, OpaqueNode};
use gfx::font_cache_thread::FontCacheThread;
use gfx::font_context::FontContext;
use heapsize::HeapSizeOf;
use msg::constellation_msg::PipelineId;
use net_traits::image_cache::{CanRequestImages, ImageCache, ImageState};
use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder};
use opaque_node::OpaqueNodeMethods;
use parking_lot::RwLock;
use script_layout_interface::{PendingImage, PendingImageState};
use script_traits::Painter;
use script_traits::UntrustedNodeAddress;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::cell::{RefCell, RefMut};
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use std::sync::{Arc, Mutex};
use std::thread;
use style::context::RegisteredSpeculativePainter;
use style::context::SharedStyleContext;
thread_local!(static FONT_CONTEXT_KEY: RefCell<Option<FontContext>> = RefCell::new(None));
pub fn with_thread_local_font_context<F, R>(layout_context: &LayoutContext, f: F) -> R
where F: FnOnce(&mut FontContext) -> R
{
FONT_CONTEXT_KEY.with(|k| {
let mut font_context = k.borrow_mut();
if font_context.is_none() {
let font_cache_thread = layout_context.font_cache_thread.lock().unwrap().clone();
*font_context = Some(FontContext::new(font_cache_thread));
}
f(&mut RefMut::map(font_context, |x| x.as_mut().unwrap()))
})
}
pub fn heap_size_of_persistent_local_context() -> usize {
FONT_CONTEXT_KEY.with(|r| {
if let Some(ref context) = *r.borrow() {
context.heap_size_of_children()
} else {
0
}
})
}
/// Layout information shared among all workers. This must be thread-safe.
pub struct LayoutContext<'a> {
/// The pipeline id of this LayoutContext.
pub id: PipelineId,
/// Bits shared by the layout and style system.
pub style_context: SharedStyleContext<'a>,
/// Reference to the script thread image cache.
pub image_cache: Arc<ImageCache>,
/// Interface to the font cache thread.
pub font_cache_thread: Mutex<FontCacheThread>,
/// A cache of WebRender image info.
pub webrender_image_cache: Arc<RwLock<HashMap<(ServoUrl, UsePlaceholder),
WebRenderImageInfo,
BuildHasherDefault<FnvHasher>>>>,
/// Paint worklets
pub registered_painters: &'a RegisteredPainters,
/// A list of in-progress image loads to be shared with the script thread.
/// A None value means that this layout was not initiated by the script thread.
pub pending_images: Option<Mutex<Vec<PendingImage>>>,
/// A list of nodes that have just initiated a CSS transition.
/// A None value means that this layout was not initiated by the script thread.
pub newly_transitioning_nodes: Option<Mutex<Vec<UntrustedNodeAddress>>>,
}
impl<'a> Drop for LayoutContext<'a> {
fn drop(&mut self) {
if !thread::panicking() {
if let Some(ref pending_images) = self.pending_images |
}
}
}
impl<'a> LayoutContext<'a> {
#[inline(always)]
pub fn shared_context(&self) -> &SharedStyleContext {
&self.style_context
}
pub fn get_or_request_image_or_meta(&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<ImageOrMetadataAvailable> {
//XXXjdm For cases where we do not request an image, we still need to
// ensure the node gets another script-initiated reflow or it
// won't be requested at all.
let can_request = if self.pending_images.is_some() {
CanRequestImages::Yes
} else {
CanRequestImages::No
};
// See if the image is already available
let result = self.image_cache.find_image_or_metadata(url.clone(),
use_placeholder,
can_request);
match result {
Ok(image_or_metadata) => Some(image_or_metadata),
// Image failed to load, so just return nothing
Err(ImageState::LoadError) => None,
// Not yet requested - request image or metadata from the cache
Err(ImageState::NotRequested(id)) => {
let image = PendingImage {
state: PendingImageState::Unrequested(url),
node: node.to_untrusted_node_address(),
id: id,
};
self.pending_images.as_ref().unwrap().lock().unwrap().push(image);
None
}
// Image has been requested, is still pending. Return no image for this paint loop.
// When the image loads it will trigger a reflow and/or repaint.
Err(ImageState::Pending(id)) => {
//XXXjdm if self.pending_images is not available, we should make sure that
// this node gets marked dirty again so it gets a script-initiated
// reflow that deals with this properly.
if let Some(ref pending_images) = self.pending_images {
let image = PendingImage {
state: PendingImageState::PendingResponse,
node: node.to_untrusted_node_address(),
id: id,
};
pending_images.lock().unwrap().push(image);
}
None
}
}
}
pub fn get_webrender_image_for_url(&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<WebRenderImageInfo> {
if let Some(existing_webrender_image) = self.webrender_image_cache
.read()
.get(&(url.clone(), use_placeholder)) {
return Some((*existing_webrender_image).clone())
}
match self.get_or_request_image_or_meta(node, url.clone(), use_placeholder) {
Some(ImageOrMetadataAvailable::ImageAvailable(image, _)) => {
let image_info = WebRenderImageInfo::from_image(&*image);
if image_info.key.is_none() {
Some(image_info)
} else {
let mut webrender_image_cache = self.webrender_image_cache.write();
webrender_image_cache.insert((url, use_placeholder),
image_info);
Some(image_info)
}
}
None | Some(ImageOrMetadataAvailable::MetadataAvailable(_)) => None,
}
}
}
/// A registered painter
pub trait RegisteredPainter: RegisteredSpeculativePainter + Painter {}
/// A set of registered painters
pub trait RegisteredPainters: Sync {
/// Look up a painter
fn get(&self, name: &Atom) -> Option<&RegisteredPainter>;
}
| {
assert!(pending_images.lock().unwrap().is_empty());
} | conditional_block |
context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Data needed by the layout thread.
use fnv::FnvHasher;
use gfx::display_list::{WebRenderImageInfo, OpaqueNode};
use gfx::font_cache_thread::FontCacheThread;
use gfx::font_context::FontContext;
use heapsize::HeapSizeOf;
use msg::constellation_msg::PipelineId;
use net_traits::image_cache::{CanRequestImages, ImageCache, ImageState};
use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder};
use opaque_node::OpaqueNodeMethods;
use parking_lot::RwLock;
use script_layout_interface::{PendingImage, PendingImageState};
use script_traits::Painter;
use script_traits::UntrustedNodeAddress;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::cell::{RefCell, RefMut};
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use std::sync::{Arc, Mutex};
use std::thread;
use style::context::RegisteredSpeculativePainter;
use style::context::SharedStyleContext;
thread_local!(static FONT_CONTEXT_KEY: RefCell<Option<FontContext>> = RefCell::new(None));
pub fn with_thread_local_font_context<F, R>(layout_context: &LayoutContext, f: F) -> R
where F: FnOnce(&mut FontContext) -> R
{
FONT_CONTEXT_KEY.with(|k| {
let mut font_context = k.borrow_mut();
if font_context.is_none() {
let font_cache_thread = layout_context.font_cache_thread.lock().unwrap().clone();
*font_context = Some(FontContext::new(font_cache_thread));
}
f(&mut RefMut::map(font_context, |x| x.as_mut().unwrap()))
})
}
pub fn heap_size_of_persistent_local_context() -> usize {
FONT_CONTEXT_KEY.with(|r| {
if let Some(ref context) = *r.borrow() {
context.heap_size_of_children()
} else {
0
}
})
}
/// Layout information shared among all workers. This must be thread-safe.
pub struct LayoutContext<'a> {
/// The pipeline id of this LayoutContext.
pub id: PipelineId,
/// Bits shared by the layout and style system.
pub style_context: SharedStyleContext<'a>,
/// Reference to the script thread image cache.
pub image_cache: Arc<ImageCache>,
/// Interface to the font cache thread.
pub font_cache_thread: Mutex<FontCacheThread>,
/// A cache of WebRender image info.
pub webrender_image_cache: Arc<RwLock<HashMap<(ServoUrl, UsePlaceholder),
WebRenderImageInfo,
BuildHasherDefault<FnvHasher>>>>,
/// Paint worklets
pub registered_painters: &'a RegisteredPainters,
/// A list of in-progress image loads to be shared with the script thread.
/// A None value means that this layout was not initiated by the script thread.
pub pending_images: Option<Mutex<Vec<PendingImage>>>,
/// A list of nodes that have just initiated a CSS transition.
/// A None value means that this layout was not initiated by the script thread.
pub newly_transitioning_nodes: Option<Mutex<Vec<UntrustedNodeAddress>>>,
}
impl<'a> Drop for LayoutContext<'a> {
fn drop(&mut self) {
if !thread::panicking() {
if let Some(ref pending_images) = self.pending_images {
assert!(pending_images.lock().unwrap().is_empty());
}
}
}
}
impl<'a> LayoutContext<'a> {
#[inline(always)]
pub fn shared_context(&self) -> &SharedStyleContext {
&self.style_context
}
pub fn get_or_request_image_or_meta(&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<ImageOrMetadataAvailable> {
//XXXjdm For cases where we do not request an image, we still need to
// ensure the node gets another script-initiated reflow or it
// won't be requested at all.
let can_request = if self.pending_images.is_some() {
CanRequestImages::Yes
} else {
CanRequestImages::No
};
// See if the image is already available
let result = self.image_cache.find_image_or_metadata(url.clone(),
use_placeholder,
can_request);
match result {
Ok(image_or_metadata) => Some(image_or_metadata),
// Image failed to load, so just return nothing
Err(ImageState::LoadError) => None,
// Not yet requested - request image or metadata from the cache
Err(ImageState::NotRequested(id)) => {
let image = PendingImage {
state: PendingImageState::Unrequested(url),
node: node.to_untrusted_node_address(),
id: id,
};
self.pending_images.as_ref().unwrap().lock().unwrap().push(image);
None
}
// Image has been requested, is still pending. Return no image for this paint loop.
// When the image loads it will trigger a reflow and/or repaint.
Err(ImageState::Pending(id)) => {
//XXXjdm if self.pending_images is not available, we should make sure that
// this node gets marked dirty again so it gets a script-initiated
// reflow that deals with this properly.
if let Some(ref pending_images) = self.pending_images {
let image = PendingImage {
state: PendingImageState::PendingResponse,
node: node.to_untrusted_node_address(),
id: id,
};
pending_images.lock().unwrap().push(image);
}
None
}
}
}
pub fn | (&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<WebRenderImageInfo> {
if let Some(existing_webrender_image) = self.webrender_image_cache
.read()
.get(&(url.clone(), use_placeholder)) {
return Some((*existing_webrender_image).clone())
}
match self.get_or_request_image_or_meta(node, url.clone(), use_placeholder) {
Some(ImageOrMetadataAvailable::ImageAvailable(image, _)) => {
let image_info = WebRenderImageInfo::from_image(&*image);
if image_info.key.is_none() {
Some(image_info)
} else {
let mut webrender_image_cache = self.webrender_image_cache.write();
webrender_image_cache.insert((url, use_placeholder),
image_info);
Some(image_info)
}
}
None | Some(ImageOrMetadataAvailable::MetadataAvailable(_)) => None,
}
}
}
/// A registered painter
pub trait RegisteredPainter: RegisteredSpeculativePainter + Painter {}
/// A set of registered painters
pub trait RegisteredPainters: Sync {
/// Look up a painter
fn get(&self, name: &Atom) -> Option<&RegisteredPainter>;
}
| get_webrender_image_for_url | identifier_name |
context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Data needed by the layout thread.
use fnv::FnvHasher;
use gfx::display_list::{WebRenderImageInfo, OpaqueNode};
use gfx::font_cache_thread::FontCacheThread;
use gfx::font_context::FontContext;
use heapsize::HeapSizeOf;
use msg::constellation_msg::PipelineId;
use net_traits::image_cache::{CanRequestImages, ImageCache, ImageState};
use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder};
use opaque_node::OpaqueNodeMethods;
use parking_lot::RwLock;
use script_layout_interface::{PendingImage, PendingImageState};
use script_traits::Painter;
use script_traits::UntrustedNodeAddress;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use std::cell::{RefCell, RefMut};
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use std::sync::{Arc, Mutex};
use std::thread;
use style::context::RegisteredSpeculativePainter;
use style::context::SharedStyleContext;
thread_local!(static FONT_CONTEXT_KEY: RefCell<Option<FontContext>> = RefCell::new(None));
pub fn with_thread_local_font_context<F, R>(layout_context: &LayoutContext, f: F) -> R
where F: FnOnce(&mut FontContext) -> R
|
pub fn heap_size_of_persistent_local_context() -> usize {
FONT_CONTEXT_KEY.with(|r| {
if let Some(ref context) = *r.borrow() {
context.heap_size_of_children()
} else {
0
}
})
}
/// Layout information shared among all workers. This must be thread-safe.
pub struct LayoutContext<'a> {
/// The pipeline id of this LayoutContext.
pub id: PipelineId,
/// Bits shared by the layout and style system.
pub style_context: SharedStyleContext<'a>,
/// Reference to the script thread image cache.
pub image_cache: Arc<ImageCache>,
/// Interface to the font cache thread.
pub font_cache_thread: Mutex<FontCacheThread>,
/// A cache of WebRender image info.
pub webrender_image_cache: Arc<RwLock<HashMap<(ServoUrl, UsePlaceholder),
WebRenderImageInfo,
BuildHasherDefault<FnvHasher>>>>,
/// Paint worklets
pub registered_painters: &'a RegisteredPainters,
/// A list of in-progress image loads to be shared with the script thread.
/// A None value means that this layout was not initiated by the script thread.
pub pending_images: Option<Mutex<Vec<PendingImage>>>,
/// A list of nodes that have just initiated a CSS transition.
/// A None value means that this layout was not initiated by the script thread.
pub newly_transitioning_nodes: Option<Mutex<Vec<UntrustedNodeAddress>>>,
}
impl<'a> Drop for LayoutContext<'a> {
fn drop(&mut self) {
if !thread::panicking() {
if let Some(ref pending_images) = self.pending_images {
assert!(pending_images.lock().unwrap().is_empty());
}
}
}
}
impl<'a> LayoutContext<'a> {
#[inline(always)]
pub fn shared_context(&self) -> &SharedStyleContext {
&self.style_context
}
pub fn get_or_request_image_or_meta(&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<ImageOrMetadataAvailable> {
//XXXjdm For cases where we do not request an image, we still need to
// ensure the node gets another script-initiated reflow or it
// won't be requested at all.
let can_request = if self.pending_images.is_some() {
CanRequestImages::Yes
} else {
CanRequestImages::No
};
// See if the image is already available
let result = self.image_cache.find_image_or_metadata(url.clone(),
use_placeholder,
can_request);
match result {
Ok(image_or_metadata) => Some(image_or_metadata),
// Image failed to load, so just return nothing
Err(ImageState::LoadError) => None,
// Not yet requested - request image or metadata from the cache
Err(ImageState::NotRequested(id)) => {
let image = PendingImage {
state: PendingImageState::Unrequested(url),
node: node.to_untrusted_node_address(),
id: id,
};
self.pending_images.as_ref().unwrap().lock().unwrap().push(image);
None
}
// Image has been requested, is still pending. Return no image for this paint loop.
// When the image loads it will trigger a reflow and/or repaint.
Err(ImageState::Pending(id)) => {
//XXXjdm if self.pending_images is not available, we should make sure that
// this node gets marked dirty again so it gets a script-initiated
// reflow that deals with this properly.
if let Some(ref pending_images) = self.pending_images {
let image = PendingImage {
state: PendingImageState::PendingResponse,
node: node.to_untrusted_node_address(),
id: id,
};
pending_images.lock().unwrap().push(image);
}
None
}
}
}
pub fn get_webrender_image_for_url(&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder)
-> Option<WebRenderImageInfo> {
if let Some(existing_webrender_image) = self.webrender_image_cache
.read()
.get(&(url.clone(), use_placeholder)) {
return Some((*existing_webrender_image).clone())
}
match self.get_or_request_image_or_meta(node, url.clone(), use_placeholder) {
Some(ImageOrMetadataAvailable::ImageAvailable(image, _)) => {
let image_info = WebRenderImageInfo::from_image(&*image);
if image_info.key.is_none() {
Some(image_info)
} else {
let mut webrender_image_cache = self.webrender_image_cache.write();
webrender_image_cache.insert((url, use_placeholder),
image_info);
Some(image_info)
}
}
None | Some(ImageOrMetadataAvailable::MetadataAvailable(_)) => None,
}
}
}
/// A registered painter
pub trait RegisteredPainter: RegisteredSpeculativePainter + Painter {}
/// A set of registered painters
pub trait RegisteredPainters: Sync {
/// Look up a painter
fn get(&self, name: &Atom) -> Option<&RegisteredPainter>;
}
| {
FONT_CONTEXT_KEY.with(|k| {
let mut font_context = k.borrow_mut();
if font_context.is_none() {
let font_cache_thread = layout_context.font_cache_thread.lock().unwrap().clone();
*font_context = Some(FontContext::new(font_cache_thread));
}
f(&mut RefMut::map(font_context, |x| x.as_mut().unwrap()))
})
} | identifier_body |
xibalba.js | var game = new Phaser.Game(
300,
600,
Phaser.CANVAS,
'gameDiv',
{
preload: preload,
create: create,
update: update,
render: render
}
);
function preload() {
game.load.image('background', 'assets/background.png');
game.load.image('playerBody', 'assets/playerBody.png');
game.load.image('leftForearm', 'assets/leftForearm.png');
game.load.image('rightForearm', 'assets/rightForearm.png');
}
function create() |
function update() {
}
function render() {
}
| {
bg = game.add.tileSprite(0, 0, 400, 800, 'background');
bg.scale.setTo(.75);
player = game.add.group();
player.scale.setTo(.75);
playerBody = game.add.sprite(200, 777, 'playerBody');
playerBody.anchor.setTo(0.5, 0.5);
leftForearm = game.add.sprite(170, 763, 'leftForearm');
leftForearm.anchor.setTo(0.5, 1.0);
leftForearm.angle = -45;
rightForearm = game.add.sprite(239, 755, 'rightForearm');
rightForearm.anchor.setTo(0.5, 0);
rightForearm.angle = 45;
player.add(playerBody);
player.add(leftForearm);
player.add(rightForearm);
} | identifier_body |
xibalba.js | var game = new Phaser.Game(
300,
600,
Phaser.CANVAS,
'gameDiv',
{
preload: preload,
create: create,
update: update,
render: render
}
);
function preload() {
game.load.image('background', 'assets/background.png');
game.load.image('playerBody', 'assets/playerBody.png');
game.load.image('leftForearm', 'assets/leftForearm.png');
game.load.image('rightForearm', 'assets/rightForearm.png');
}
function | () {
bg = game.add.tileSprite(0, 0, 400, 800, 'background');
bg.scale.setTo(.75);
player = game.add.group();
player.scale.setTo(.75);
playerBody = game.add.sprite(200, 777, 'playerBody');
playerBody.anchor.setTo(0.5, 0.5);
leftForearm = game.add.sprite(170, 763, 'leftForearm');
leftForearm.anchor.setTo(0.5, 1.0);
leftForearm.angle = -45;
rightForearm = game.add.sprite(239, 755, 'rightForearm');
rightForearm.anchor.setTo(0.5, 0);
rightForearm.angle = 45;
player.add(playerBody);
player.add(leftForearm);
player.add(rightForearm);
}
function update() {
}
function render() {
}
| create | identifier_name |
mixins.py | #!/bin/env python2
# -*- coding: utf-8 -*-
#
# This file is part of the VecNet Zika modeling interface.
# For copyright and licensing information about this package, see the
# NOTICE.txt and LICENSE.txt files in its top-level directory; they are
# available at https://github.com/vecnet/zika
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License (MPL), version 2.0. If a copy of the MPL was not distributed
# with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
import json
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
class LoginRequiredMixin(object):
""" This works: class InterviewListView(LoginRequiredMixin, ListView)
This DOES NOT work: class InterviewListView(ListView, LoginRequiredMixin)
I'm not 100% sure that wrapping as_view function using Mixin is a good idea though, but whatever
"""
@classmethod
def as_view(cls, **initkwargs):
# Ignore PyCharm warning below, this is a Mixin class after all
| view = super(LoginRequiredMixin, cls).as_view(**initkwargs)
return login_required(view) | identifier_body |
|
mixins.py | #!/bin/env python2
# -*- coding: utf-8 -*-
#
# This file is part of the VecNet Zika modeling interface.
# For copyright and licensing information about this package, see the
# NOTICE.txt and LICENSE.txt files in its top-level directory; they are
# available at https://github.com/vecnet/zika
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License (MPL), version 2.0. If a copy of the MPL was not distributed
# with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
import json
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
class LoginRequiredMixin(object):
""" This works: class InterviewListView(LoginRequiredMixin, ListView)
This DOES NOT work: class InterviewListView(ListView, LoginRequiredMixin)
I'm not 100% sure that wrapping as_view function using Mixin is a good idea though, but whatever
"""
@classmethod
def | (cls, **initkwargs):
# Ignore PyCharm warning below, this is a Mixin class after all
view = super(LoginRequiredMixin, cls).as_view(**initkwargs)
return login_required(view)
| as_view | identifier_name |
mixins.py | #!/bin/env python2
# -*- coding: utf-8 -*-
#
# This file is part of the VecNet Zika modeling interface.
# For copyright and licensing information about this package, see the | # available at https://github.com/vecnet/zika
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License (MPL), version 2.0. If a copy of the MPL was not distributed
# with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
import json
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
class LoginRequiredMixin(object):
""" This works: class InterviewListView(LoginRequiredMixin, ListView)
This DOES NOT work: class InterviewListView(ListView, LoginRequiredMixin)
I'm not 100% sure that wrapping as_view function using Mixin is a good idea though, but whatever
"""
@classmethod
def as_view(cls, **initkwargs):
# Ignore PyCharm warning below, this is a Mixin class after all
view = super(LoginRequiredMixin, cls).as_view(**initkwargs)
return login_required(view) | # NOTICE.txt and LICENSE.txt files in its top-level directory; they are | random_line_split |
mean_level_spacing_test.py | from __future__ import print_function, division
import sys,os
qspin_path = os.path.join(os.getcwd(),"../")
sys.path.insert(0,qspin_path)
#
from quspin.operators import hamiltonian # Hamiltonians and operators
from quspin.basis import spin_basis_1d # Hilbert space spin basis
from quspin.tools.measurements import mean_level_spacing
import numpy as np # generic math functions
#
L=12 # syste size
# coupling strenghts
J=1.0 # spin-spin coupling
h=0.8945 # x-field strength
g=0.945 # z-field strength
# create site-coupling lists
J_zz=[[J,i,(i+1)%L] for i in range(L)] # PBC
x_field=[[h,i] for i in range(L)]
z_field=[[g,i] for i in range(L)]
# create static and dynamic lists
static_2=[["zz",J_zz],["x",x_field],["z",z_field]]
dynamic=[]
# create spin-1/2 basis
basis=spin_basis_1d(L,kblock=0,pblock=1)
# set up Hamiltonian
H2=hamiltonian(static_2,dynamic,basis=basis,dtype=np.float64)
# compute eigensystem of H2
E2=H2.eigvalsh()
# calculate mean level spacing of spectrum E2
r=mean_level_spacing(E2)
print("mean level spacing is", r)
E2=np.insert(E2,-1,E2[-1])
r=mean_level_spacing(E2)
print("mean level spacing is", r)
E2=np.insert(E2,-1,E2[-1]) | print("mean level spacing is", r) | r=mean_level_spacing(E2,verbose=False) | random_line_split |
parseSysInfoStats.spec.ts | /* global it, describe, before, after */
import * as mock from '../__mocks__/mock-server-responses';
import * as misrcon from '../src/node-misrcon';
describe('parseSysInfoStats', () => {
it('sysinfo stats live', () => {
const sysInfo = misrcon.parseSysInfoStats(mock.sysInfoStats);
expect(sysInfo.upd).toBe('9.2ms (7.82..10.89)');
});
it('sysinfo stats dev', () => {
const sysInfo = misrcon.parseSysInfoStats(mock.sysInfoStatsDev);
expect(sysInfo.upd).toBe('2.5ms (2.37..3.28)');
});
| try {
misrcon.parseSysInfoStats('Some other random String');
} catch (e) {
expect(e instanceof misrcon.ParserError).toEqual(true);
}
});
}); | it('should throw ParserError', () => { | random_line_split |
lib.rs | //! # bittrex-api
//!
//! **bittrex-api** provides a wrapper for the [Bittrex API](https://bittrex.com/home/api).
//! This crate makes it easy to consume the **Bittrex API** in Rust.
//!
//! ##Example
//!
//! ```no_run
//! extern crate bittrex_api;
//!
//! use bittrex_api::BittrexClient;
//! # fn main() { | //! # }
//! ```
extern crate time;
extern crate hmac;
extern crate sha2;
extern crate generic_array;
extern crate reqwest;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
pub mod error;
pub mod values;
mod client;
pub use client::BittrexClient; | //! let bittrex_client = BittrexClient::new("KEY".to_string(), "SECRET".to_string()); // Initialize the Bittrex Client with your API Key and Secret
//! let markets = bittrex_client.get_markets().unwrap(); //Get all available markets of Bittrex | random_line_split |
facebook.js | var Purest = require('purest');
function Facebook(opts) {
this._opts = opts || {};
this._opts.provider = 'facebook';
this._purest = new Purest(this._opts);
this._group = 'LIB:SOCIAL:FACEBOOK';
return this;
}
Facebook.prototype.user = function (cb) {
var self = this;
this._purest.query()
.get('me')
.auth(this._opts.auth.token)
.request(function (err, res, body) {
if (err) {
console.log(err);
return cb(err);
}
cb(null, body);
});
};
| // form = {message: 'post message'}
this._purest.query()
.post(endpoint || 'me/feed')
.auth(this._opts.auth.token)
.form(form)
.request(function (err, res, body) {
if (err) {
console.log(err);
return cb(err);
}
cb(null, body);
});
};
module.exports = function(app) {
return Facebook;
}; | Facebook.prototype.post = function (endpoint, form, cb) { | random_line_split |
facebook.js | var Purest = require('purest');
function Facebook(opts) {
this._opts = opts || {};
this._opts.provider = 'facebook';
this._purest = new Purest(this._opts);
this._group = 'LIB:SOCIAL:FACEBOOK';
return this;
}
Facebook.prototype.user = function (cb) {
var self = this;
this._purest.query()
.get('me')
.auth(this._opts.auth.token)
.request(function (err, res, body) {
if (err) {
console.log(err);
return cb(err);
}
cb(null, body);
});
};
Facebook.prototype.post = function (endpoint, form, cb) {
// form = {message: 'post message'}
this._purest.query()
.post(endpoint || 'me/feed')
.auth(this._opts.auth.token)
.form(form)
.request(function (err, res, body) {
if (err) |
cb(null, body);
});
};
module.exports = function(app) {
return Facebook;
};
| {
console.log(err);
return cb(err);
} | conditional_block |
facebook.js | var Purest = require('purest');
function Facebook(opts) |
Facebook.prototype.user = function (cb) {
var self = this;
this._purest.query()
.get('me')
.auth(this._opts.auth.token)
.request(function (err, res, body) {
if (err) {
console.log(err);
return cb(err);
}
cb(null, body);
});
};
Facebook.prototype.post = function (endpoint, form, cb) {
// form = {message: 'post message'}
this._purest.query()
.post(endpoint || 'me/feed')
.auth(this._opts.auth.token)
.form(form)
.request(function (err, res, body) {
if (err) {
console.log(err);
return cb(err);
}
cb(null, body);
});
};
module.exports = function(app) {
return Facebook;
};
| {
this._opts = opts || {};
this._opts.provider = 'facebook';
this._purest = new Purest(this._opts);
this._group = 'LIB:SOCIAL:FACEBOOK';
return this;
} | identifier_body |
facebook.js | var Purest = require('purest');
function | (opts) {
this._opts = opts || {};
this._opts.provider = 'facebook';
this._purest = new Purest(this._opts);
this._group = 'LIB:SOCIAL:FACEBOOK';
return this;
}
Facebook.prototype.user = function (cb) {
var self = this;
this._purest.query()
.get('me')
.auth(this._opts.auth.token)
.request(function (err, res, body) {
if (err) {
console.log(err);
return cb(err);
}
cb(null, body);
});
};
Facebook.prototype.post = function (endpoint, form, cb) {
// form = {message: 'post message'}
this._purest.query()
.post(endpoint || 'me/feed')
.auth(this._opts.auth.token)
.form(form)
.request(function (err, res, body) {
if (err) {
console.log(err);
return cb(err);
}
cb(null, body);
});
};
module.exports = function(app) {
return Facebook;
};
| Facebook | identifier_name |
str.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use geometry::Au;
use cssparser::{self, RGBA, Color};
use libc::c_char;
use num_lib::ToPrimitive;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::ffi::CStr;
use std::iter::Filter;
use std::ops::Deref;
use std::str::{from_utf8, FromStr, Split};
pub type DOMString = String;
pub type StaticCharVec = &'static [char];
pub type StaticStringVec = &'static [&'static str];
/// Whitespace as defined by HTML5 § 2.4.1.
// TODO(SimonSapin) Maybe a custom Pattern can be more efficient?
const WHITESPACE: &'static [char] = &[' ', '\t', '\x0a', '\x0c', '\x0d'];
pub fn is_whitespace(s: &str) -> bool {
s.chars().all(char_is_whitespace)
}
#[inline]
pub fn char_is_whitespace(c: char) -> bool {
WHITESPACE.contains(&c)
}
/// A "space character" according to:
///
/// https://html.spec.whatwg.org/multipage/#space-character
pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[
'\u{0020}',
'\u{0009}',
'\u{000a}',
'\u{000c}',
'\u{000d}',
];
pub fn split_html_space_chars<'a>(s: &'a str) ->
Filter<Split<'a, StaticCharVec>, fn(&&str) -> bool> {
fn n | &split: &&str) -> bool { !split.is_empty() }
s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool)
}
/// Shared implementation to parse an integer according to
/// <https://html.spec.whatwg.org/#rules-for-parsing-integers> or
/// <https://html.spec.whatwg.org/#rules-for-parsing-non-negative-integers>
fn do_parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i64> {
fn is_ascii_digit(c: &char) -> bool {
match *c {
'0'...'9' => true,
_ => false,
}
}
let mut input = input.skip_while(|c| {
HTML_SPACE_CHARACTERS.iter().any(|s| s == c)
}).peekable();
let sign = match input.peek() {
None => return None,
Some(&'-') => {
input.next();
-1
},
Some(&'+') => {
input.next();
1
},
Some(_) => 1,
};
match input.peek() {
Some(c) if is_ascii_digit(c) => (),
_ => return None,
}
let value = input.take_while(is_ascii_digit).map(|d| {
d as i64 - '0' as i64
}).fold(Some(0i64), |accumulator, d| {
accumulator.and_then(|accumulator| {
accumulator.checked_mul(10)
}).and_then(|accumulator| {
accumulator.checked_add(d)
})
});
return value.and_then(|value| value.checked_mul(sign));
}
/// Parse an integer according to
/// <https://html.spec.whatwg.org/#rules-for-parsing-integers>.
pub fn parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i32> {
do_parse_integer(input).and_then(|result| {
result.to_i32()
})
}
/// Parse an integer according to
/// <https://html.spec.whatwg.org/#rules-for-parsing-non-negative-integers>
pub fn parse_unsigned_integer<T: Iterator<Item=char>>(input: T) -> Option<u32> {
do_parse_integer(input).and_then(|result| {
result.to_u32()
})
}
#[derive(Copy, Clone, Debug)]
pub enum LengthOrPercentageOrAuto {
Auto,
Percentage(f32),
Length(Au),
}
/// Parses a length per HTML5 § 2.4.4.4. If unparseable, `Auto` is returned.
pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto {
value = value.trim_left_matches(WHITESPACE);
if value.is_empty() {
return LengthOrPercentageOrAuto::Auto
}
if value.starts_with("+") {
value = &value[1..]
}
value = value.trim_left_matches('0');
if value.is_empty() {
return LengthOrPercentageOrAuto::Auto
}
let mut end_index = value.len();
let (mut found_full_stop, mut found_percent) = (false, false);
for (i, ch) in value.chars().enumerate() {
match ch {
'0'...'9' => continue,
'%' => {
found_percent = true;
end_index = i;
break
}
'.' if !found_full_stop => {
found_full_stop = true;
continue
}
_ => {
end_index = i;
break
}
}
}
value = &value[..end_index];
if found_percent {
let result: Result<f32, _> = FromStr::from_str(value);
match result {
Ok(number) => return LengthOrPercentageOrAuto::Percentage((number as f32) / 100.0),
Err(_) => return LengthOrPercentageOrAuto::Auto,
}
}
match FromStr::from_str(value) {
Ok(number) => LengthOrPercentageOrAuto::Length(Au::from_px(number)),
Err(_) => LengthOrPercentageOrAuto::Auto,
}
}
/// Parses a legacy color per HTML5 § 2.4.6. If unparseable, `Err` is returned.
pub fn parse_legacy_color(mut input: &str) -> Result<RGBA, ()> {
// Steps 1 and 2.
if input.is_empty() {
return Err(())
}
// Step 3.
input = input.trim_matches(WHITESPACE);
// Step 4.
if input.eq_ignore_ascii_case("transparent") {
return Err(())
}
// Step 5.
match cssparser::parse_color_keyword(input) {
Ok(Color::RGBA(rgba)) => return Ok(rgba),
_ => {}
}
// Step 6.
if input.len() == 4 {
match (input.as_bytes()[0],
hex(input.as_bytes()[1] as char),
hex(input.as_bytes()[2] as char),
hex(input.as_bytes()[3] as char)) {
(b'#', Ok(r), Ok(g), Ok(b)) => {
return Ok(RGBA {
red: (r as f32) * 17.0 / 255.0,
green: (g as f32) * 17.0 / 255.0,
blue: (b as f32) * 17.0 / 255.0,
alpha: 1.0,
})
}
_ => {}
}
}
// Step 7.
let mut new_input = String::new();
for ch in input.chars() {
if ch as u32 > 0xffff {
new_input.push_str("00")
} else {
new_input.push(ch)
}
}
let mut input = &*new_input;
// Step 8.
for (char_count, (index, _)) in input.char_indices().enumerate() {
if char_count == 128 {
input = &input[..index];
break
}
}
// Step 9.
if input.as_bytes()[0] == b'#' {
input = &input[1..]
}
// Step 10.
let mut new_input = Vec::new();
for ch in input.chars() {
if hex(ch).is_ok() {
new_input.push(ch as u8)
} else {
new_input.push(b'0')
}
}
let mut input = new_input;
// Step 11.
while input.is_empty() || (input.len() % 3) != 0 {
input.push(b'0')
}
// Step 12.
let mut length = input.len() / 3;
let (mut red, mut green, mut blue) = (&input[..length],
&input[length..length * 2],
&input[length * 2..]);
// Step 13.
if length > 8 {
red = &red[length - 8..];
green = &green[length - 8..];
blue = &blue[length - 8..];
length = 8
}
// Step 14.
while length > 2 && red[0] == b'0' && green[0] == b'0' && blue[0] == b'0' {
red = &red[1..];
green = &green[1..];
blue = &blue[1..];
length -= 1
}
// Steps 15-20.
return Ok(RGBA {
red: hex_string(red).unwrap() as f32 / 255.0,
green: hex_string(green).unwrap() as f32 / 255.0,
blue: hex_string(blue).unwrap() as f32 / 255.0,
alpha: 1.0,
});
fn hex(ch: char) -> Result<u8, ()> {
match ch {
'0'...'9' => Ok((ch as u8) - b'0'),
'a'...'f' => Ok((ch as u8) - b'a' + 10),
'A'...'F' => Ok((ch as u8) - b'A' + 10),
_ => Err(()),
}
}
fn hex_string(string: &[u8]) -> Result<u8, ()> {
match string.len() {
0 => Err(()),
1 => hex(string[0] as char),
_ => {
let upper = try!(hex(string[0] as char));
let lower = try!(hex(string[1] as char));
Ok((upper << 4) | lower)
}
}
}
}
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct LowercaseString {
inner: String,
}
impl LowercaseString {
pub fn new(s: &str) -> LowercaseString {
LowercaseString {
inner: s.to_lowercase(),
}
}
}
impl Deref for LowercaseString {
type Target = str;
#[inline]
fn deref(&self) -> &str {
&*self.inner
}
}
/// Creates a String from the given null-terminated buffer.
/// Panics if the buffer does not contain UTF-8.
pub unsafe fn c_str_to_string(s: *const c_char) -> String {
from_utf8(CStr::from_ptr(s).to_bytes()).unwrap().to_owned()
}
pub fn str_join<T: AsRef<str>>(strs: &[T], join: &str) -> String {
strs.iter().fold(String::new(), |mut acc, s| {
if !acc.is_empty() { acc.push_str(join); }
acc.push_str(s.as_ref());
acc
})
}
// Lifted from Rust's StrExt implementation, which is being removed.
pub fn slice_chars(s: &str, begin: usize, end: usize) -> &str {
assert!(begin <= end);
let mut count = 0;
let mut begin_byte = None;
let mut end_byte = None;
// This could be even more efficient by not decoding,
// only finding the char boundaries
for (idx, _) in s.char_indices() {
if count == begin { begin_byte = Some(idx); }
if count == end { end_byte = Some(idx); break; }
count += 1;
}
if begin_byte.is_none() && count == begin { begin_byte = Some(s.len()) }
if end_byte.is_none() && count == end { end_byte = Some(s.len()) }
match (begin_byte, end_byte) {
(None, _) => panic!("slice_chars: `begin` is beyond end of string"),
(_, None) => panic!("slice_chars: `end` is beyond end of string"),
(Some(a), Some(b)) => unsafe { s.slice_unchecked(a, b) }
}
}
| ot_empty( | identifier_name |
str.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use geometry::Au;
use cssparser::{self, RGBA, Color};
use libc::c_char;
use num_lib::ToPrimitive;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::ffi::CStr;
use std::iter::Filter;
use std::ops::Deref;
use std::str::{from_utf8, FromStr, Split};
pub type DOMString = String;
pub type StaticCharVec = &'static [char];
pub type StaticStringVec = &'static [&'static str];
/// Whitespace as defined by HTML5 § 2.4.1.
// TODO(SimonSapin) Maybe a custom Pattern can be more efficient?
const WHITESPACE: &'static [char] = &[' ', '\t', '\x0a', '\x0c', '\x0d'];
pub fn is_whitespace(s: &str) -> bool {
s.chars().all(char_is_whitespace)
}
#[inline]
pub fn char_is_whitespace(c: char) -> bool {
WHITESPACE.contains(&c)
}
/// A "space character" according to:
///
/// https://html.spec.whatwg.org/multipage/#space-character
pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[
'\u{0020}',
'\u{0009}',
'\u{000a}',
'\u{000c}',
'\u{000d}',
];
pub fn split_html_space_chars<'a>(s: &'a str) ->
Filter<Split<'a, StaticCharVec>, fn(&&str) -> bool> {
fn not_empty(&split: &&str) -> bool { !split.is_empty() }
s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool)
}
/// Shared implementation to parse an integer according to
/// <https://html.spec.whatwg.org/#rules-for-parsing-integers> or
/// <https://html.spec.whatwg.org/#rules-for-parsing-non-negative-integers>
fn do_parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i64> {
fn is_ascii_digit(c: &char) -> bool {
match *c {
'0'...'9' => true,
_ => false,
}
}
let mut input = input.skip_while(|c| {
HTML_SPACE_CHARACTERS.iter().any(|s| s == c)
}).peekable();
let sign = match input.peek() {
None => return None,
Some(&'-') => {
input.next();
-1
},
Some(&'+') => {
input.next();
1
},
Some(_) => 1,
};
match input.peek() {
Some(c) if is_ascii_digit(c) => (),
_ => return None,
}
let value = input.take_while(is_ascii_digit).map(|d| {
d as i64 - '0' as i64
}).fold(Some(0i64), |accumulator, d| {
accumulator.and_then(|accumulator| {
accumulator.checked_mul(10)
}).and_then(|accumulator| {
accumulator.checked_add(d)
})
});
return value.and_then(|value| value.checked_mul(sign));
}
/// Parse an integer according to
/// <https://html.spec.whatwg.org/#rules-for-parsing-integers>.
pub fn parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i32> {
do_parse_integer(input).and_then(|result| {
result.to_i32()
})
}
/// Parse an integer according to
/// <https://html.spec.whatwg.org/#rules-for-parsing-non-negative-integers>
pub fn parse_unsigned_integer<T: Iterator<Item=char>>(input: T) -> Option<u32> {
do_parse_integer(input).and_then(|result| {
result.to_u32()
})
}
#[derive(Copy, Clone, Debug)]
pub enum LengthOrPercentageOrAuto {
Auto,
Percentage(f32),
Length(Au),
}
/// Parses a length per HTML5 § 2.4.4.4. If unparseable, `Auto` is returned.
pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto {
value = value.trim_left_matches(WHITESPACE);
if value.is_empty() {
return LengthOrPercentageOrAuto::Auto
}
if value.starts_with("+") {
value = &value[1..]
}
value = value.trim_left_matches('0');
if value.is_empty() {
return LengthOrPercentageOrAuto::Auto
}
let mut end_index = value.len();
let (mut found_full_stop, mut found_percent) = (false, false);
for (i, ch) in value.chars().enumerate() {
match ch {
'0'...'9' => continue,
'%' => {
found_percent = true;
end_index = i;
break
}
'.' if !found_full_stop => {
found_full_stop = true;
continue
}
_ => {
end_index = i;
break
}
}
}
value = &value[..end_index];
if found_percent {
let result: Result<f32, _> = FromStr::from_str(value);
match result {
Ok(number) => return LengthOrPercentageOrAuto::Percentage((number as f32) / 100.0),
Err(_) => return LengthOrPercentageOrAuto::Auto,
}
}
match FromStr::from_str(value) {
Ok(number) => LengthOrPercentageOrAuto::Length(Au::from_px(number)),
Err(_) => LengthOrPercentageOrAuto::Auto,
}
}
/// Parses a legacy color per HTML5 § 2.4.6. If unparseable, `Err` is returned.
pub fn parse_legacy_color(mut input: &str) -> Result<RGBA, ()> {
// Steps 1 and 2.
if input.is_empty() {
return Err(())
}
// Step 3.
input = input.trim_matches(WHITESPACE);
// Step 4.
if input.eq_ignore_ascii_case("transparent") {
return Err(())
}
// Step 5.
match cssparser::parse_color_keyword(input) {
Ok(Color::RGBA(rgba)) => return Ok(rgba),
_ => {}
}
// Step 6.
if input.len() == 4 {
match (input.as_bytes()[0],
hex(input.as_bytes()[1] as char),
hex(input.as_bytes()[2] as char),
hex(input.as_bytes()[3] as char)) {
(b'#', Ok(r), Ok(g), Ok(b)) => {
return Ok(RGBA {
red: (r as f32) * 17.0 / 255.0,
green: (g as f32) * 17.0 / 255.0,
blue: (b as f32) * 17.0 / 255.0,
alpha: 1.0,
})
}
_ => {}
}
}
// Step 7.
let mut new_input = String::new();
for ch in input.chars() {
if ch as u32 > 0xffff {
new_input.push_str("00")
} else {
new_input.push(ch)
}
}
let mut input = &*new_input;
// Step 8.
for (char_count, (index, _)) in input.char_indices().enumerate() {
if char_count == 128 {
input = &input[..index];
break
}
}
// Step 9.
if input.as_bytes()[0] == b'#' {
input = &input[1..]
}
// Step 10.
let mut new_input = Vec::new();
for ch in input.chars() {
if hex(ch).is_ok() {
new_input.push(ch as u8)
} else {
new_input.push(b'0')
}
}
let mut input = new_input;
// Step 11.
while input.is_empty() || (input.len() % 3) != 0 {
input.push(b'0')
}
// Step 12.
let mut length = input.len() / 3;
let (mut red, mut green, mut blue) = (&input[..length],
&input[length..length * 2],
&input[length * 2..]);
// Step 13.
if length > 8 {
red = &red[length - 8..];
green = &green[length - 8..];
blue = &blue[length - 8..];
length = 8
}
// Step 14.
while length > 2 && red[0] == b'0' && green[0] == b'0' && blue[0] == b'0' {
red = &red[1..];
green = &green[1..];
blue = &blue[1..];
length -= 1
}
// Steps 15-20.
return Ok(RGBA {
red: hex_string(red).unwrap() as f32 / 255.0,
green: hex_string(green).unwrap() as f32 / 255.0,
blue: hex_string(blue).unwrap() as f32 / 255.0,
alpha: 1.0,
});
fn hex(ch: char) -> Result<u8, ()> {
| fn hex_string(string: &[u8]) -> Result<u8, ()> {
match string.len() {
0 => Err(()),
1 => hex(string[0] as char),
_ => {
let upper = try!(hex(string[0] as char));
let lower = try!(hex(string[1] as char));
Ok((upper << 4) | lower)
}
}
}
}
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct LowercaseString {
inner: String,
}
impl LowercaseString {
pub fn new(s: &str) -> LowercaseString {
LowercaseString {
inner: s.to_lowercase(),
}
}
}
impl Deref for LowercaseString {
type Target = str;
#[inline]
fn deref(&self) -> &str {
&*self.inner
}
}
/// Creates a String from the given null-terminated buffer.
/// Panics if the buffer does not contain UTF-8.
pub unsafe fn c_str_to_string(s: *const c_char) -> String {
from_utf8(CStr::from_ptr(s).to_bytes()).unwrap().to_owned()
}
pub fn str_join<T: AsRef<str>>(strs: &[T], join: &str) -> String {
strs.iter().fold(String::new(), |mut acc, s| {
if !acc.is_empty() { acc.push_str(join); }
acc.push_str(s.as_ref());
acc
})
}
// Lifted from Rust's StrExt implementation, which is being removed.
pub fn slice_chars(s: &str, begin: usize, end: usize) -> &str {
assert!(begin <= end);
let mut count = 0;
let mut begin_byte = None;
let mut end_byte = None;
// This could be even more efficient by not decoding,
// only finding the char boundaries
for (idx, _) in s.char_indices() {
if count == begin { begin_byte = Some(idx); }
if count == end { end_byte = Some(idx); break; }
count += 1;
}
if begin_byte.is_none() && count == begin { begin_byte = Some(s.len()) }
if end_byte.is_none() && count == end { end_byte = Some(s.len()) }
match (begin_byte, end_byte) {
(None, _) => panic!("slice_chars: `begin` is beyond end of string"),
(_, None) => panic!("slice_chars: `end` is beyond end of string"),
(Some(a), Some(b)) => unsafe { s.slice_unchecked(a, b) }
}
}
| match ch {
'0'...'9' => Ok((ch as u8) - b'0'),
'a'...'f' => Ok((ch as u8) - b'a' + 10),
'A'...'F' => Ok((ch as u8) - b'A' + 10),
_ => Err(()),
}
}
| identifier_body |
str.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use geometry::Au;
use cssparser::{self, RGBA, Color};
use libc::c_char;
use num_lib::ToPrimitive;
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::ffi::CStr;
use std::iter::Filter;
use std::ops::Deref;
use std::str::{from_utf8, FromStr, Split};
pub type DOMString = String;
pub type StaticCharVec = &'static [char];
pub type StaticStringVec = &'static [&'static str];
/// Whitespace as defined by HTML5 § 2.4.1.
// TODO(SimonSapin) Maybe a custom Pattern can be more efficient?
const WHITESPACE: &'static [char] = &[' ', '\t', '\x0a', '\x0c', '\x0d'];
pub fn is_whitespace(s: &str) -> bool {
s.chars().all(char_is_whitespace)
}
#[inline]
pub fn char_is_whitespace(c: char) -> bool {
WHITESPACE.contains(&c)
}
/// A "space character" according to:
///
/// https://html.spec.whatwg.org/multipage/#space-character
pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[ | '\u{000d}',
];
pub fn split_html_space_chars<'a>(s: &'a str) ->
Filter<Split<'a, StaticCharVec>, fn(&&str) -> bool> {
fn not_empty(&split: &&str) -> bool { !split.is_empty() }
s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool)
}
/// Shared implementation to parse an integer according to
/// <https://html.spec.whatwg.org/#rules-for-parsing-integers> or
/// <https://html.spec.whatwg.org/#rules-for-parsing-non-negative-integers>
fn do_parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i64> {
fn is_ascii_digit(c: &char) -> bool {
match *c {
'0'...'9' => true,
_ => false,
}
}
let mut input = input.skip_while(|c| {
HTML_SPACE_CHARACTERS.iter().any(|s| s == c)
}).peekable();
let sign = match input.peek() {
None => return None,
Some(&'-') => {
input.next();
-1
},
Some(&'+') => {
input.next();
1
},
Some(_) => 1,
};
match input.peek() {
Some(c) if is_ascii_digit(c) => (),
_ => return None,
}
let value = input.take_while(is_ascii_digit).map(|d| {
d as i64 - '0' as i64
}).fold(Some(0i64), |accumulator, d| {
accumulator.and_then(|accumulator| {
accumulator.checked_mul(10)
}).and_then(|accumulator| {
accumulator.checked_add(d)
})
});
return value.and_then(|value| value.checked_mul(sign));
}
/// Parse an integer according to
/// <https://html.spec.whatwg.org/#rules-for-parsing-integers>.
pub fn parse_integer<T: Iterator<Item=char>>(input: T) -> Option<i32> {
do_parse_integer(input).and_then(|result| {
result.to_i32()
})
}
/// Parse an integer according to
/// <https://html.spec.whatwg.org/#rules-for-parsing-non-negative-integers>
pub fn parse_unsigned_integer<T: Iterator<Item=char>>(input: T) -> Option<u32> {
do_parse_integer(input).and_then(|result| {
result.to_u32()
})
}
#[derive(Copy, Clone, Debug)]
pub enum LengthOrPercentageOrAuto {
Auto,
Percentage(f32),
Length(Au),
}
/// Parses a length per HTML5 § 2.4.4.4. If unparseable, `Auto` is returned.
pub fn parse_length(mut value: &str) -> LengthOrPercentageOrAuto {
value = value.trim_left_matches(WHITESPACE);
if value.is_empty() {
return LengthOrPercentageOrAuto::Auto
}
if value.starts_with("+") {
value = &value[1..]
}
value = value.trim_left_matches('0');
if value.is_empty() {
return LengthOrPercentageOrAuto::Auto
}
let mut end_index = value.len();
let (mut found_full_stop, mut found_percent) = (false, false);
for (i, ch) in value.chars().enumerate() {
match ch {
'0'...'9' => continue,
'%' => {
found_percent = true;
end_index = i;
break
}
'.' if !found_full_stop => {
found_full_stop = true;
continue
}
_ => {
end_index = i;
break
}
}
}
value = &value[..end_index];
if found_percent {
let result: Result<f32, _> = FromStr::from_str(value);
match result {
Ok(number) => return LengthOrPercentageOrAuto::Percentage((number as f32) / 100.0),
Err(_) => return LengthOrPercentageOrAuto::Auto,
}
}
match FromStr::from_str(value) {
Ok(number) => LengthOrPercentageOrAuto::Length(Au::from_px(number)),
Err(_) => LengthOrPercentageOrAuto::Auto,
}
}
/// Parses a legacy color per HTML5 § 2.4.6. If unparseable, `Err` is returned.
pub fn parse_legacy_color(mut input: &str) -> Result<RGBA, ()> {
// Steps 1 and 2.
if input.is_empty() {
return Err(())
}
// Step 3.
input = input.trim_matches(WHITESPACE);
// Step 4.
if input.eq_ignore_ascii_case("transparent") {
return Err(())
}
// Step 5.
match cssparser::parse_color_keyword(input) {
Ok(Color::RGBA(rgba)) => return Ok(rgba),
_ => {}
}
// Step 6.
if input.len() == 4 {
match (input.as_bytes()[0],
hex(input.as_bytes()[1] as char),
hex(input.as_bytes()[2] as char),
hex(input.as_bytes()[3] as char)) {
(b'#', Ok(r), Ok(g), Ok(b)) => {
return Ok(RGBA {
red: (r as f32) * 17.0 / 255.0,
green: (g as f32) * 17.0 / 255.0,
blue: (b as f32) * 17.0 / 255.0,
alpha: 1.0,
})
}
_ => {}
}
}
// Step 7.
let mut new_input = String::new();
for ch in input.chars() {
if ch as u32 > 0xffff {
new_input.push_str("00")
} else {
new_input.push(ch)
}
}
let mut input = &*new_input;
// Step 8.
for (char_count, (index, _)) in input.char_indices().enumerate() {
if char_count == 128 {
input = &input[..index];
break
}
}
// Step 9.
if input.as_bytes()[0] == b'#' {
input = &input[1..]
}
// Step 10.
let mut new_input = Vec::new();
for ch in input.chars() {
if hex(ch).is_ok() {
new_input.push(ch as u8)
} else {
new_input.push(b'0')
}
}
let mut input = new_input;
// Step 11.
while input.is_empty() || (input.len() % 3) != 0 {
input.push(b'0')
}
// Step 12.
let mut length = input.len() / 3;
let (mut red, mut green, mut blue) = (&input[..length],
&input[length..length * 2],
&input[length * 2..]);
// Step 13.
if length > 8 {
red = &red[length - 8..];
green = &green[length - 8..];
blue = &blue[length - 8..];
length = 8
}
// Step 14.
while length > 2 && red[0] == b'0' && green[0] == b'0' && blue[0] == b'0' {
red = &red[1..];
green = &green[1..];
blue = &blue[1..];
length -= 1
}
// Steps 15-20.
return Ok(RGBA {
red: hex_string(red).unwrap() as f32 / 255.0,
green: hex_string(green).unwrap() as f32 / 255.0,
blue: hex_string(blue).unwrap() as f32 / 255.0,
alpha: 1.0,
});
fn hex(ch: char) -> Result<u8, ()> {
match ch {
'0'...'9' => Ok((ch as u8) - b'0'),
'a'...'f' => Ok((ch as u8) - b'a' + 10),
'A'...'F' => Ok((ch as u8) - b'A' + 10),
_ => Err(()),
}
}
fn hex_string(string: &[u8]) -> Result<u8, ()> {
match string.len() {
0 => Err(()),
1 => hex(string[0] as char),
_ => {
let upper = try!(hex(string[0] as char));
let lower = try!(hex(string[1] as char));
Ok((upper << 4) | lower)
}
}
}
}
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct LowercaseString {
inner: String,
}
impl LowercaseString {
pub fn new(s: &str) -> LowercaseString {
LowercaseString {
inner: s.to_lowercase(),
}
}
}
impl Deref for LowercaseString {
type Target = str;
#[inline]
fn deref(&self) -> &str {
&*self.inner
}
}
/// Creates a String from the given null-terminated buffer.
/// Panics if the buffer does not contain UTF-8.
pub unsafe fn c_str_to_string(s: *const c_char) -> String {
from_utf8(CStr::from_ptr(s).to_bytes()).unwrap().to_owned()
}
pub fn str_join<T: AsRef<str>>(strs: &[T], join: &str) -> String {
strs.iter().fold(String::new(), |mut acc, s| {
if !acc.is_empty() { acc.push_str(join); }
acc.push_str(s.as_ref());
acc
})
}
// Lifted from Rust's StrExt implementation, which is being removed.
pub fn slice_chars(s: &str, begin: usize, end: usize) -> &str {
assert!(begin <= end);
let mut count = 0;
let mut begin_byte = None;
let mut end_byte = None;
// This could be even more efficient by not decoding,
// only finding the char boundaries
for (idx, _) in s.char_indices() {
if count == begin { begin_byte = Some(idx); }
if count == end { end_byte = Some(idx); break; }
count += 1;
}
if begin_byte.is_none() && count == begin { begin_byte = Some(s.len()) }
if end_byte.is_none() && count == end { end_byte = Some(s.len()) }
match (begin_byte, end_byte) {
(None, _) => panic!("slice_chars: `begin` is beyond end of string"),
(_, None) => panic!("slice_chars: `end` is beyond end of string"),
(Some(a), Some(b)) => unsafe { s.slice_unchecked(a, b) }
}
} | '\u{0020}',
'\u{0009}',
'\u{000a}',
'\u{000c}', | random_line_split |
issue-5554.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::default::Default;
pub struct X<T> {
a: T,
}
// reordering these bounds stops the ICE
//
// nmatsakis: This test used to have the bounds Default + PartialEq +
// Default, but having duplicate bounds became illegal.
impl<T: Default + PartialEq> Default for X<T> {
fn default() -> X<T> {
X { a: Default::default() }
}
}
macro_rules! constants {
() => {
let _ : X<int> = Default::default();
}
}
pub fn main() | {
constants!();
} | identifier_body |
|
issue-5554.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::default::Default;
pub struct | <T> {
a: T,
}
// reordering these bounds stops the ICE
//
// nmatsakis: This test used to have the bounds Default + PartialEq +
// Default, but having duplicate bounds became illegal.
impl<T: Default + PartialEq> Default for X<T> {
fn default() -> X<T> {
X { a: Default::default() }
}
}
macro_rules! constants {
() => {
let _ : X<int> = Default::default();
}
}
pub fn main() {
constants!();
}
| X | identifier_name |
issue-5554.rs | // Copyright 2013 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 |
pub struct X<T> {
a: T,
}
// reordering these bounds stops the ICE
//
// nmatsakis: This test used to have the bounds Default + PartialEq +
// Default, but having duplicate bounds became illegal.
impl<T: Default + PartialEq> Default for X<T> {
fn default() -> X<T> {
X { a: Default::default() }
}
}
macro_rules! constants {
() => {
let _ : X<int> = Default::default();
}
}
pub fn main() {
constants!();
} | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::default::Default; | random_line_split |
test_devstack.py | # Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import jsonschema
import mock
from rally.deployment.engines import devstack
from tests.unit import test
SAMPLE_CONFIG = {
"type": "DevstackEngine",
"provider": {
"name": "ExistingServers",
"credentials": [{"user": "root", "host": "example.com"}],
},
"localrc": {
"ADMIN_PASSWORD": "secret",
},
}
DEVSTACK_REPO = "https://git.openstack.org/openstack-dev/devstack"
class DevstackEngineTestCase(test.TestCase):
def | (self):
super(DevstackEngineTestCase, self).setUp()
self.deployment = {
"uuid": "de641026-dbe3-4abe-844a-ffef930a600a",
"config": SAMPLE_CONFIG,
}
self.engine = devstack.DevstackEngine(self.deployment)
def test_invalid_config(self):
self.deployment = SAMPLE_CONFIG.copy()
self.deployment["config"] = {"type": 42}
engine = devstack.DevstackEngine(self.deployment)
self.assertRaises(jsonschema.ValidationError,
engine.validate)
def test_construct(self):
self.assertEqual(self.engine.localrc["ADMIN_PASSWORD"], "secret")
@mock.patch("rally.deployment.engines.devstack.open", create=True)
def test_prepare_server(self, mock_open):
mock_open.return_value = "fake_file"
server = mock.Mock()
server.password = "secret"
self.engine.prepare_server(server)
calls = [
mock.call("/bin/sh -e", stdin="fake_file"),
mock.call("chpasswd", stdin="rally:secret"),
]
self.assertEqual(calls, server.ssh.run.mock_calls)
filename = mock_open.mock_calls[0][1][0]
self.assertTrue(filename.endswith("rally/deployment/engines/"
"devstack/install.sh"))
self.assertEqual([mock.call(filename, "rb")], mock_open.mock_calls)
@mock.patch("rally.deployment.engine.Engine.get_provider")
@mock.patch("rally.deployment.engines.devstack.get_updated_server")
@mock.patch("rally.deployment.engines.devstack.get_script")
@mock.patch("rally.deployment.serverprovider.provider.Server")
@mock.patch("rally.deployment.engines.devstack.objects.Endpoint")
def test_deploy(self, mock_endpoint, mock_server, mock_get_script,
mock_get_updated_server, mock_engine_get_provider):
mock_engine_get_provider.return_value = fake_provider = (
mock.Mock()
)
server = mock.Mock(host="host")
mock_endpoint.return_value = "fake_endpoint"
mock_get_updated_server.return_value = ds_server = mock.Mock()
mock_get_script.return_value = "fake_script"
server.get_credentials.return_value = "fake_credentials"
fake_provider.create_servers.return_value = [server]
with mock.patch.object(self.engine, "deployment") as mock_deployment:
endpoints = self.engine.deploy()
self.assertEqual({"admin": "fake_endpoint"}, endpoints)
mock_endpoint.assert_called_once_with(
"http://host:5000/v2.0/", "admin", "secret", "admin", "admin")
mock_deployment.add_resource.assert_called_once_with(
info="fake_credentials",
provider_name="DevstackEngine",
type="credentials")
repo = "https://git.openstack.org/openstack-dev/devstack"
cmd = "/bin/sh -e -s %s master" % repo
server.ssh.run.assert_called_once_with(cmd, stdin="fake_script")
ds_calls = [
mock.call.ssh.run("cat > ~/devstack/localrc", stdin=mock.ANY),
mock.call.ssh.run("~/devstack/stack.sh")
]
self.assertEqual(ds_calls, ds_server.mock_calls)
localrc = ds_server.mock_calls[0][2]["stdin"]
self.assertIn("ADMIN_PASSWORD=secret", localrc)
| setUp | identifier_name |
test_devstack.py | # Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import jsonschema
import mock
from rally.deployment.engines import devstack
from tests.unit import test
SAMPLE_CONFIG = {
"type": "DevstackEngine",
"provider": {
"name": "ExistingServers",
"credentials": [{"user": "root", "host": "example.com"}],
},
"localrc": {
"ADMIN_PASSWORD": "secret",
},
}
DEVSTACK_REPO = "https://git.openstack.org/openstack-dev/devstack"
class DevstackEngineTestCase(test.TestCase):
def setUp(self):
super(DevstackEngineTestCase, self).setUp()
self.deployment = {
"uuid": "de641026-dbe3-4abe-844a-ffef930a600a",
"config": SAMPLE_CONFIG,
}
self.engine = devstack.DevstackEngine(self.deployment)
def test_invalid_config(self):
self.deployment = SAMPLE_CONFIG.copy()
self.deployment["config"] = {"type": 42}
engine = devstack.DevstackEngine(self.deployment)
self.assertRaises(jsonschema.ValidationError,
engine.validate)
def test_construct(self):
self.assertEqual(self.engine.localrc["ADMIN_PASSWORD"], "secret")
@mock.patch("rally.deployment.engines.devstack.open", create=True)
def test_prepare_server(self, mock_open):
mock_open.return_value = "fake_file"
server = mock.Mock()
server.password = "secret"
self.engine.prepare_server(server)
calls = [
mock.call("/bin/sh -e", stdin="fake_file"),
mock.call("chpasswd", stdin="rally:secret"),
]
self.assertEqual(calls, server.ssh.run.mock_calls)
filename = mock_open.mock_calls[0][1][0]
self.assertTrue(filename.endswith("rally/deployment/engines/"
"devstack/install.sh"))
self.assertEqual([mock.call(filename, "rb")], mock_open.mock_calls)
@mock.patch("rally.deployment.engine.Engine.get_provider")
@mock.patch("rally.deployment.engines.devstack.get_updated_server")
@mock.patch("rally.deployment.engines.devstack.get_script")
@mock.patch("rally.deployment.serverprovider.provider.Server")
@mock.patch("rally.deployment.engines.devstack.objects.Endpoint")
def test_deploy(self, mock_endpoint, mock_server, mock_get_script,
mock_get_updated_server, mock_engine_get_provider):
mock_engine_get_provider.return_value = fake_provider = (
mock.Mock()
)
server = mock.Mock(host="host")
mock_endpoint.return_value = "fake_endpoint"
mock_get_updated_server.return_value = ds_server = mock.Mock()
mock_get_script.return_value = "fake_script"
server.get_credentials.return_value = "fake_credentials" | mock_endpoint.assert_called_once_with(
"http://host:5000/v2.0/", "admin", "secret", "admin", "admin")
mock_deployment.add_resource.assert_called_once_with(
info="fake_credentials",
provider_name="DevstackEngine",
type="credentials")
repo = "https://git.openstack.org/openstack-dev/devstack"
cmd = "/bin/sh -e -s %s master" % repo
server.ssh.run.assert_called_once_with(cmd, stdin="fake_script")
ds_calls = [
mock.call.ssh.run("cat > ~/devstack/localrc", stdin=mock.ANY),
mock.call.ssh.run("~/devstack/stack.sh")
]
self.assertEqual(ds_calls, ds_server.mock_calls)
localrc = ds_server.mock_calls[0][2]["stdin"]
self.assertIn("ADMIN_PASSWORD=secret", localrc) | fake_provider.create_servers.return_value = [server]
with mock.patch.object(self.engine, "deployment") as mock_deployment:
endpoints = self.engine.deploy()
self.assertEqual({"admin": "fake_endpoint"}, endpoints) | random_line_split |
test_devstack.py | # Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import jsonschema
import mock
from rally.deployment.engines import devstack
from tests.unit import test
SAMPLE_CONFIG = {
"type": "DevstackEngine",
"provider": {
"name": "ExistingServers",
"credentials": [{"user": "root", "host": "example.com"}],
},
"localrc": {
"ADMIN_PASSWORD": "secret",
},
}
DEVSTACK_REPO = "https://git.openstack.org/openstack-dev/devstack"
class DevstackEngineTestCase(test.TestCase):
| def setUp(self):
super(DevstackEngineTestCase, self).setUp()
self.deployment = {
"uuid": "de641026-dbe3-4abe-844a-ffef930a600a",
"config": SAMPLE_CONFIG,
}
self.engine = devstack.DevstackEngine(self.deployment)
def test_invalid_config(self):
self.deployment = SAMPLE_CONFIG.copy()
self.deployment["config"] = {"type": 42}
engine = devstack.DevstackEngine(self.deployment)
self.assertRaises(jsonschema.ValidationError,
engine.validate)
def test_construct(self):
self.assertEqual(self.engine.localrc["ADMIN_PASSWORD"], "secret")
@mock.patch("rally.deployment.engines.devstack.open", create=True)
def test_prepare_server(self, mock_open):
mock_open.return_value = "fake_file"
server = mock.Mock()
server.password = "secret"
self.engine.prepare_server(server)
calls = [
mock.call("/bin/sh -e", stdin="fake_file"),
mock.call("chpasswd", stdin="rally:secret"),
]
self.assertEqual(calls, server.ssh.run.mock_calls)
filename = mock_open.mock_calls[0][1][0]
self.assertTrue(filename.endswith("rally/deployment/engines/"
"devstack/install.sh"))
self.assertEqual([mock.call(filename, "rb")], mock_open.mock_calls)
@mock.patch("rally.deployment.engine.Engine.get_provider")
@mock.patch("rally.deployment.engines.devstack.get_updated_server")
@mock.patch("rally.deployment.engines.devstack.get_script")
@mock.patch("rally.deployment.serverprovider.provider.Server")
@mock.patch("rally.deployment.engines.devstack.objects.Endpoint")
def test_deploy(self, mock_endpoint, mock_server, mock_get_script,
mock_get_updated_server, mock_engine_get_provider):
mock_engine_get_provider.return_value = fake_provider = (
mock.Mock()
)
server = mock.Mock(host="host")
mock_endpoint.return_value = "fake_endpoint"
mock_get_updated_server.return_value = ds_server = mock.Mock()
mock_get_script.return_value = "fake_script"
server.get_credentials.return_value = "fake_credentials"
fake_provider.create_servers.return_value = [server]
with mock.patch.object(self.engine, "deployment") as mock_deployment:
endpoints = self.engine.deploy()
self.assertEqual({"admin": "fake_endpoint"}, endpoints)
mock_endpoint.assert_called_once_with(
"http://host:5000/v2.0/", "admin", "secret", "admin", "admin")
mock_deployment.add_resource.assert_called_once_with(
info="fake_credentials",
provider_name="DevstackEngine",
type="credentials")
repo = "https://git.openstack.org/openstack-dev/devstack"
cmd = "/bin/sh -e -s %s master" % repo
server.ssh.run.assert_called_once_with(cmd, stdin="fake_script")
ds_calls = [
mock.call.ssh.run("cat > ~/devstack/localrc", stdin=mock.ANY),
mock.call.ssh.run("~/devstack/stack.sh")
]
self.assertEqual(ds_calls, ds_server.mock_calls)
localrc = ds_server.mock_calls[0][2]["stdin"]
self.assertIn("ADMIN_PASSWORD=secret", localrc) | identifier_body |
|
server.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Author: sansna
# Date : 2020 Aug 01 17:42:43
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")))
import re
# App Config
# XXX: https://stackoverflow.com/questions/3536620/how-to-change-a-module-variable-from-another-module
if __name__ == "__main__":
import config.base
if not config.base.Configured:
config.base.Configured = True
config.base.App = "lib/web/server"
config.base.Env = config.base.ENV_PRODUCTION
#config.base.Env = config.base.ENV_TEST
import time
from lib3.decorator.safe_run import safe_run_wrap
import logging
from lib3.lg import logger
from flask import Flask
from flask import request
import socket
app = Flask(__name__)
# Enable UTF-8 support in resp of flask
app.config['JSON_AS_ASCII'] = False
now = int(time.time())
today = int(now+8*3600)/86400*86400-8*3600
dayts = 86400
hourts = 3600
mints = 60
yesterday = today - dayts
def YMD(ts):
return time.strftime("%Y%m%d", time.localtime(ts))
def YM(ts):
return time.strftime("%Y%m", time.localtime(ts))
def DAY(ts):
return time.strftime("%d", time.localtime(ts))
pathre = re.compile('[^a-zA-Z0-9]')
def AddPath(path, f, methods=["POST"]):
if len(path) == 0:
return
if path[0] != "/":
path = "/"+path
fun = path+str(methods)
fun = pathre.sub('_', fun)
"""
see https://stackoverflow.com/questions/17256602/assertionerror-view-function-mapping-is-overwriting-an-existing-endpoint-functi
for usage of @app.route
"""
@app.route(path, methods=methods, endpoint=fun)
def run(*args, **kwargs):
"""
TODO: 针对同参数频繁请求,增加缓存
"""
if request.method == 'POST':
ret = f(request.get_json(force=True), args, kwargs)
logger.info("path: %s, hostname: %s, host: %s, raddr: %s, methods: %s, params: %s"%(path, socket.gethostname(), request.host, request.remote_addr, methods, request.get_json(force=True)))
elif request.method == 'GET':
ret = f(None, args, kwargs)
logger.info("path: %s, hostname: %s, host: %s, raddr: %s, methods: %s"%(path, socket.gethostname(), request.host, request.remote_addr, methods))
return ret
@safe_run_wrap
def add_path(*args, **kwargs):
"""
decorator of adding path for a function
Usage:
@add_path("path", methods=["POST","GET"])
def func(json):
print "ok"
"""
path = args[0]
if "methods" in kwargs:
methods = kwargs["methods"]
else:
methods = ["POST"]
def inner(func):
AddPath(path, func, methods=methods)
return func
return inner
@safe_run_wrap
def Run(port=8888):
if type(port) != int:
return
log = logging.getLogger("werkzeug")
log.disabled = True
app.run(host="0.0.0.0", port=port)
def main():
@add_path("hello")
def func1(json):
mid = 0
if "mid" in json:
mid=json["mid"]
if mid == 1:
json["zz"] = 10
if mid == -1:
raise KeyError
return json
#AddPath("hello", func1)
"""
curl -G 127.0.0.1:8080/xxx/123/xcv
"""
@add_path("xxx/<idx>/<mmm>", methods=["GET"])
def func2(json, *args, **kwargs):
print json, args, kwargs
variable_dict = args[1]
# prints "123", unicode
print variable_dict["idx"]
# prints "xcv", unicode
print variable_dict["mmm"]
return {"zz":"你户"}
Run(8080)
if __name__ == "__main__":
main()
| conditional_block |
||
server.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Author: sansna
# Date : 2020 Aug 01 17:42:43
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")))
import re
# App Config
# XXX: https://stackoverflow.com/questions/3536620/how-to-change-a-module-variable-from-another-module
if __name__ == "__main__":
import config.base
if not config.base.Configured:
config.base.Configured = True
config.base.App = "lib/web/server"
config.base.Env = config.base.ENV_PRODUCTION
#config.base.Env = config.base.ENV_TEST
import time
from lib3.decorator.safe_run import safe_run_wrap
import logging
from lib3.lg import logger
from flask import Flask
from flask import request
import socket
app = Flask(__name__)
# Enable UTF-8 support in resp of flask
app.config['JSON_AS_ASCII'] = False
now = int(time.time())
today = int(now+8*3600)/86400*86400-8*3600
dayts = 86400
hourts = 3600
mints = 60
yesterday = today - dayts
def YMD(ts):
return time.strftime("%Y%m%d", time.localtime(ts))
def YM(ts):
return time.strftime("%Y%m", time.localtime(ts))
def DAY(ts):
return time.strftime("%d", time.localtime(ts))
pathre = re.compile('[^a-zA-Z0-9]')
def AddPath(path, f, methods=["POST"]):
if len(path) == 0:
return
if path[0] != "/":
path = "/"+path
fun = path+str(methods)
fun = pathre.sub('_', fun)
"""
see https://stackoverflow.com/questions/17256602/assertionerror-view-function-mapping-is-overwriting-an-existing-endpoint-functi
for usage of @app.route
"""
@app.route(path, methods=methods, endpoint=fun)
def run(*args, **kwargs):
"""
TODO: 针对同参数频繁请求,增加缓存
"""
if request.method == 'POST':
ret = f(request.get_json(force=True), args, kwargs)
logger.info("path: %s, hostname: %s, host: %s, raddr: %s, methods: %s, params: %s"%(path, socket.gethostname(), request.host, request.remote_addr, methods, request.get_json(force=True)))
elif request.method == 'GET':
ret = f(None, args, kwargs)
logger.info("path: %s, hostname: %s, host: %s, raddr: %s, methods: %s"%(path, socket.gethostname(), request.host, request.remote_addr, methods))
return ret
@safe_run_wrap
def add_path(*args, **kwargs):
| decorator of adding path for a function
Usage:
@add_path("path", methods=["POST","GET"])
def func(json):
print "ok"
"""
path = args[0]
if "methods" in kwargs:
methods = kwargs["methods"]
else:
methods = ["POST"]
def inner(func):
AddPath(path, func, methods=methods)
return func
return inner
@safe_run_wrap
def Run(port=8888):
if type(port) != int:
return
log = logging.getLogger("werkzeug")
log.disabled = True
app.run(host="0.0.0.0", port=port)
def main():
@add_path("hello")
def func1(json):
mid = 0
if "mid" in json:
mid=json["mid"]
if mid == 1:
json["zz"] = 10
if mid == -1:
raise KeyError
return json
#AddPath("hello", func1)
"""
curl -G 127.0.0.1:8080/xxx/123/xcv
"""
@add_path("xxx/<idx>/<mmm>", methods=["GET"])
def func2(json, *args, **kwargs):
print json, args, kwargs
variable_dict = args[1]
# prints "123", unicode
print variable_dict["idx"]
# prints "xcv", unicode
print variable_dict["mmm"]
return {"zz":"你户"}
Run(8080)
if __name__ == "__main__":
main()
| """
| identifier_name |
server.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Author: sansna
# Date : 2020 Aug 01 17:42:43
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")))
import re
# App Config
# XXX: https://stackoverflow.com/questions/3536620/how-to-change-a-module-variable-from-another-module
if __name__ == "__main__":
import config.base
if not config.base.Configured:
config.base.Configured = True
config.base.App = "lib/web/server"
config.base.Env = config.base.ENV_PRODUCTION
#config.base.Env = config.base.ENV_TEST
import time
from lib3.decorator.safe_run import safe_run_wrap
import logging
from lib3.lg import logger
from flask import Flask
from flask import request
import socket
app = Flask(__name__)
# Enable UTF-8 support in resp of flask
app.config['JSON_AS_ASCII'] = False
now = int(time.time())
today = int(now+8*3600)/86400*86400-8*3600
dayts = 86400
hourts = 3600
mints = 60
yesterday = today - dayts
def YMD(ts):
return time.strftime("%Y%m%d", time.localtime(ts))
def YM(ts):
return time.strftime("%Y%m", time.localtime(ts))
def DAY(ts):
return time.strftime("%d", time.localtime(ts))
pathre = re.compile('[^a-zA-Z0-9]') |
def AddPath(path, f, methods=["POST"]):
if len(path) == 0:
return
if path[0] != "/":
path = "/"+path
fun = path+str(methods)
fun = pathre.sub('_', fun)
"""
see https://stackoverflow.com/questions/17256602/assertionerror-view-function-mapping-is-overwriting-an-existing-endpoint-functi
for usage of @app.route
"""
@app.route(path, methods=methods, endpoint=fun)
def run(*args, **kwargs):
"""
TODO: 针对同参数频繁请求,增加缓存
"""
if request.method == 'POST':
ret = f(request.get_json(force=True), args, kwargs)
logger.info("path: %s, hostname: %s, host: %s, raddr: %s, methods: %s, params: %s"%(path, socket.gethostname(), request.host, request.remote_addr, methods, request.get_json(force=True)))
elif request.method == 'GET':
ret = f(None, args, kwargs)
logger.info("path: %s, hostname: %s, host: %s, raddr: %s, methods: %s"%(path, socket.gethostname(), request.host, request.remote_addr, methods))
return ret
@safe_run_wrap
def add_path(*args, **kwargs):
"""
decorator of adding path for a function
Usage:
@add_path("path", methods=["POST","GET"])
def func(json):
print "ok"
"""
path = args[0]
if "methods" in kwargs:
methods = kwargs["methods"]
else:
methods = ["POST"]
def inner(func):
AddPath(path, func, methods=methods)
return func
return inner
@safe_run_wrap
def Run(port=8888):
if type(port) != int:
return
log = logging.getLogger("werkzeug")
log.disabled = True
app.run(host="0.0.0.0", port=port)
def main():
@add_path("hello")
def func1(json):
mid = 0
if "mid" in json:
mid=json["mid"]
if mid == 1:
json["zz"] = 10
if mid == -1:
raise KeyError
return json
#AddPath("hello", func1)
"""
curl -G 127.0.0.1:8080/xxx/123/xcv
"""
@add_path("xxx/<idx>/<mmm>", methods=["GET"])
def func2(json, *args, **kwargs):
print json, args, kwargs
variable_dict = args[1]
# prints "123", unicode
print variable_dict["idx"]
# prints "xcv", unicode
print variable_dict["mmm"]
return {"zz":"你户"}
Run(8080)
if __name__ == "__main__":
main() | random_line_split |
|
server.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Author: sansna
# Date : 2020 Aug 01 17:42:43
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")))
import re
# App Config
# XXX: https://stackoverflow.com/questions/3536620/how-to-change-a-module-variable-from-another-module
if __name__ == "__main__":
import config.base
if not config.base.Configured:
config.base.Configured = True
config.base.App = "lib/web/server"
config.base.Env = config.base.ENV_PRODUCTION
#config.base.Env = config.base.ENV_TEST
import time
from lib3.decorator.safe_run import safe_run_wrap
import logging
from lib3.lg import logger
from flask import Flask
from flask import request
import socket
app = Flask(__name__)
# Enable UTF-8 support in resp of flask
app.config['JSON_AS_ASCII'] = False
now = int(time.time())
today = int(now+8*3600)/86400*86400-8*3600
dayts = 86400
hourts = 3600
mints = 60
yesterday = today - dayts
def YMD(ts):
return time.strftime("%Y%m%d", time.localtime(ts))
def YM(ts):
|
def DAY(ts):
return time.strftime("%d", time.localtime(ts))
pathre = re.compile('[^a-zA-Z0-9]')
def AddPath(path, f, methods=["POST"]):
if len(path) == 0:
return
if path[0] != "/":
path = "/"+path
fun = path+str(methods)
fun = pathre.sub('_', fun)
"""
see https://stackoverflow.com/questions/17256602/assertionerror-view-function-mapping-is-overwriting-an-existing-endpoint-functi
for usage of @app.route
"""
@app.route(path, methods=methods, endpoint=fun)
def run(*args, **kwargs):
"""
TODO: 针对同参数频繁请求,增加缓存
"""
if request.method == 'POST':
ret = f(request.get_json(force=True), args, kwargs)
logger.info("path: %s, hostname: %s, host: %s, raddr: %s, methods: %s, params: %s"%(path, socket.gethostname(), request.host, request.remote_addr, methods, request.get_json(force=True)))
elif request.method == 'GET':
ret = f(None, args, kwargs)
logger.info("path: %s, hostname: %s, host: %s, raddr: %s, methods: %s"%(path, socket.gethostname(), request.host, request.remote_addr, methods))
return ret
@safe_run_wrap
def add_path(*args, **kwargs):
"""
decorator of adding path for a function
Usage:
@add_path("path", methods=["POST","GET"])
def func(json):
print "ok"
"""
path = args[0]
if "methods" in kwargs:
methods = kwargs["methods"]
else:
methods = ["POST"]
def inner(func):
AddPath(path, func, methods=methods)
return func
return inner
@safe_run_wrap
def Run(port=8888):
if type(port) != int:
return
log = logging.getLogger("werkzeug")
log.disabled = True
app.run(host="0.0.0.0", port=port)
def main():
@add_path("hello")
def func1(json):
mid = 0
if "mid" in json:
mid=json["mid"]
if mid == 1:
json["zz"] = 10
if mid == -1:
raise KeyError
return json
#AddPath("hello", func1)
"""
curl -G 127.0.0.1:8080/xxx/123/xcv
"""
@add_path("xxx/<idx>/<mmm>", methods=["GET"])
def func2(json, *args, **kwargs):
print json, args, kwargs
variable_dict = args[1]
# prints "123", unicode
print variable_dict["idx"]
# prints "xcv", unicode
print variable_dict["mmm"]
return {"zz":"你户"}
Run(8080)
if __name__ == "__main__":
main()
| return time.strftime("%Y%m", time.localtime(ts)) | identifier_body |
inefficient_to_string.rs | // run-rustfix
#![deny(clippy::inefficient_to_string)]
use std::borrow::Cow;
fn | () {
let rstr: &str = "hello";
let rrstr: &&str = &rstr;
let rrrstr: &&&str = &rrstr;
let _: String = rstr.to_string();
let _: String = rrstr.to_string();
let _: String = rrrstr.to_string();
let string: String = String::from("hello");
let rstring: &String = &string;
let rrstring: &&String = &rstring;
let rrrstring: &&&String = &rrstring;
let _: String = string.to_string();
let _: String = rstring.to_string();
let _: String = rrstring.to_string();
let _: String = rrrstring.to_string();
let cow: Cow<'_, str> = Cow::Borrowed("hello");
let rcow: &Cow<'_, str> = &cow;
let rrcow: &&Cow<'_, str> = &rcow;
let rrrcow: &&&Cow<'_, str> = &rrcow;
let _: String = cow.to_string();
let _: String = rcow.to_string();
let _: String = rrcow.to_string();
let _: String = rrrcow.to_string();
}
| main | identifier_name |
inefficient_to_string.rs | // run-rustfix
#![deny(clippy::inefficient_to_string)]
use std::borrow::Cow;
fn main() {
let rstr: &str = "hello";
let rrstr: &&str = &rstr;
let rrrstr: &&&str = &rrstr; | let rstring: &String = &string;
let rrstring: &&String = &rstring;
let rrrstring: &&&String = &rrstring;
let _: String = string.to_string();
let _: String = rstring.to_string();
let _: String = rrstring.to_string();
let _: String = rrrstring.to_string();
let cow: Cow<'_, str> = Cow::Borrowed("hello");
let rcow: &Cow<'_, str> = &cow;
let rrcow: &&Cow<'_, str> = &rcow;
let rrrcow: &&&Cow<'_, str> = &rrcow;
let _: String = cow.to_string();
let _: String = rcow.to_string();
let _: String = rrcow.to_string();
let _: String = rrrcow.to_string();
} | let _: String = rstr.to_string();
let _: String = rrstr.to_string();
let _: String = rrrstr.to_string();
let string: String = String::from("hello"); | random_line_split |
inefficient_to_string.rs | // run-rustfix
#![deny(clippy::inefficient_to_string)]
use std::borrow::Cow;
fn main() | {
let rstr: &str = "hello";
let rrstr: &&str = &rstr;
let rrrstr: &&&str = &rrstr;
let _: String = rstr.to_string();
let _: String = rrstr.to_string();
let _: String = rrrstr.to_string();
let string: String = String::from("hello");
let rstring: &String = &string;
let rrstring: &&String = &rstring;
let rrrstring: &&&String = &rrstring;
let _: String = string.to_string();
let _: String = rstring.to_string();
let _: String = rrstring.to_string();
let _: String = rrrstring.to_string();
let cow: Cow<'_, str> = Cow::Borrowed("hello");
let rcow: &Cow<'_, str> = &cow;
let rrcow: &&Cow<'_, str> = &rcow;
let rrrcow: &&&Cow<'_, str> = &rrcow;
let _: String = cow.to_string();
let _: String = rcow.to_string();
let _: String = rrcow.to_string();
let _: String = rrrcow.to_string();
} | identifier_body |
|
UCNES_Class.py | import numpy as np
import os
import sys
import math
#import class files
# sys.path.append('../../../')
from source import bioRead as br
from source import classify as cl
#import PyInsect for measuring similarity
#sys.path.append('../../../../')
from PyINSECT import representations as REP
from PyINSECT import comparators as CMP
from multiprocessing import Pool
import multiprocessing
# Local function
def __getSimilaritiesForIndex(setting):
|
# End local function
# If we have cached the main analysis data
if os.path.exists('SimilaritiesAndDictionaries/UCNE.npz'):
# Use them
npz = np.load('SimilaritiesAndDictionaries/UCNE.npz')
hd = npz['hd']
cd = npz['cd']
S = npz['S']
l1 = npz['l1']
l2 = npz['l2']
l = npz['l']
L = np.append(np.zeros(l1),np.ones(l2),axis=0)
print "WARNING: Using cached data!"
else:
# else start reading
sr = br.SequenceReader()
# Get Human UCNE fasta data
sr.read('./biodata/UCNEs/hg19_UCNEs.fasta')
# sr.read('./biodata/UCNEs/hg19_UCNEs-10.fasta')
hd = sr.getDictionary()
print "Gained Human Dictionary"
# Get Chicken UCNE fasta data
sr.read('./biodata/UCNEs/galGal3_UCNEs.fasta')
# sr.read('./biodata/UCNEs/galGal3_UCNEs-10.fasta')
cd = sr.getDictionary()
print "Gained Chicken Dictionary"
# Set n-gram graph analysis parameters
n=3
Dwin=2
subjectMap = {}
ngg = {}
# Get number of UNCEs (for either type of UNCE)
l1 = len(hd.keys())
l2 = len(cd.keys())
l = l1 + l2
print "Found %d human UNCEs"%(l1)
print "Found %d chicken UNCEs"%(l2)
# For every human UNCE
i = 0
for key,a in hd.iteritems():
# Assign appropriate label
subjectMap[i] = (key,'humans')
# Create corresponding graph
ngg[i] = REP.DocumentNGramGraph(n,Dwin,a)
i += 1
print "Graphs Created for Humans"
for key,b in cd.iteritems():
subjectMap[i] = (key,'chickens')
ngg[i] = REP.DocumentNGramGraph(n,Dwin,b)
i += 1
print "Graphs Created for Chickens"
S = np.empty([l, l])
L = np.empty([l])
sop = CMP.SimilarityNVS()
print "Getting human similarities..."
# TODO: Examine default (problems with locking S)
# pThreadPool = Pool(1);
qToExecute = list() # Reset tasks
for i in range(0,l1):
print i," ",
L[i] = 0 #0 for humans
qToExecute.append((i,l,S,ngg))
# pThreadPool.map(__getSimilaritiesForIndex, qToExecute)
map(__getSimilaritiesForIndex,qToExecute)
print ""
print "Getting human similarities... Done."
qToExecute = list() # Reset tasks
print "Getting chicken similarities..."
for i in range(l1,l):
print i," ",
L[i] = 1 #0 for chickens
qToExecute.append((i,l,S,ngg))
# pThreadPool.map(__getSimilaritiesForIndex, qToExecute)
map(__getSimilaritiesForIndex, qToExecute)
# for i in range(l1,l):
# print i," ",
# L[i] = 1 #1 for chickens
# for j in range(i,l):
# S[i,j] = sop.getSimilarityDouble(ngg[i],ngg[j])
print ""
print "Getting chicken similarities... Done"
# Update symmetric matrix, based on current findings
for i in range(0,l):
for j in range(0,i):
S[i,j] = S[j,i]
print "Similarity matrix constructed.."
if not os.path.exists('SimilaritiesAndDictionaries'):
os.mkdir('SimilaritiesAndDictionaries')
np.savez('SimilaritiesAndDictionaries/UCNE.npz', hd=hd, cd=cd, l1=l1, l2=l2,
l=l, S=S)
reps = 10
L1 = L[0:l1]
L2 = L[l1:]
metrics = dict()
cm = dict()
class_types = {0:"No kernelization",1:"Spectrum Clip",2:"Spectrum Flip",3:"Spectrum Shift",4:"Spectrum Square"}
print "Testing for different kernelization methods..\n\n"
for i in range(0, len(class_types)):
try:
print class_types[i],"\n"
evaluator = cl.Evaluator(cl.SVM())
Sp = cl.kernelization(S,i)
S1 = Sp[0:l1,:]
S2 = Sp[l1:,:]
metrics[class_types[i]],cm[class_types[i]] = evaluator.Randomized_kfold((S1,S2),(L1,L2),reps,verbose=True)
print ""
except Exception as e:
print "Approach %s failed for reason:\n%s"%(class_types[i], str(e))
np.savez('SimilaritiesAndDictionaries/metrics.npz', metrics=metrics, cm=cm)
| i, l, S, ngg = setting # Explode
for j in range(i,l):
dTmp = sop.getSimilarityDouble(ngg[i],ngg[j])
if (math.isnan(dTmp)):
raise Exception("Invalid similarity! Check similarity implementation.")
S[i,j] = dTmp | identifier_body |
UCNES_Class.py | import numpy as np
import os
import sys
import math
#import class files
# sys.path.append('../../../')
from source import bioRead as br
from source import classify as cl
#import PyInsect for measuring similarity
#sys.path.append('../../../../')
from PyINSECT import representations as REP
from PyINSECT import comparators as CMP
from multiprocessing import Pool
import multiprocessing
# Local function
def __getSimilaritiesForIndex(setting):
i, l, S, ngg = setting # Explode
for j in range(i,l):
dTmp = sop.getSimilarityDouble(ngg[i],ngg[j])
if (math.isnan(dTmp)):
raise Exception("Invalid similarity! Check similarity implementation.")
S[i,j] = dTmp
# End local function
# If we have cached the main analysis data
if os.path.exists('SimilaritiesAndDictionaries/UCNE.npz'):
# Use them
npz = np.load('SimilaritiesAndDictionaries/UCNE.npz')
hd = npz['hd']
cd = npz['cd']
S = npz['S']
l1 = npz['l1']
l2 = npz['l2']
l = npz['l']
L = np.append(np.zeros(l1),np.ones(l2),axis=0)
print "WARNING: Using cached data!"
else:
# else start reading
sr = br.SequenceReader()
# Get Human UCNE fasta data
sr.read('./biodata/UCNEs/hg19_UCNEs.fasta')
# sr.read('./biodata/UCNEs/hg19_UCNEs-10.fasta')
hd = sr.getDictionary()
print "Gained Human Dictionary"
# Get Chicken UCNE fasta data
sr.read('./biodata/UCNEs/galGal3_UCNEs.fasta')
# sr.read('./biodata/UCNEs/galGal3_UCNEs-10.fasta')
cd = sr.getDictionary()
print "Gained Chicken Dictionary"
# Set n-gram graph analysis parameters
n=3
Dwin=2
subjectMap = {}
ngg = {}
# Get number of UNCEs (for either type of UNCE)
l1 = len(hd.keys())
l2 = len(cd.keys())
l = l1 + l2
print "Found %d human UNCEs"%(l1)
print "Found %d chicken UNCEs"%(l2)
# For every human UNCE
i = 0
for key,a in hd.iteritems():
# Assign appropriate label
subjectMap[i] = (key,'humans')
# Create corresponding graph
ngg[i] = REP.DocumentNGramGraph(n,Dwin,a)
i += 1
print "Graphs Created for Humans"
for key,b in cd.iteritems():
subjectMap[i] = (key,'chickens')
ngg[i] = REP.DocumentNGramGraph(n,Dwin,b)
i += 1
print "Graphs Created for Chickens"
S = np.empty([l, l])
L = np.empty([l])
sop = CMP.SimilarityNVS()
print "Getting human similarities..."
# TODO: Examine default (problems with locking S)
# pThreadPool = Pool(1);
qToExecute = list() # Reset tasks
for i in range(0,l1):
print i," ",
L[i] = 0 #0 for humans
qToExecute.append((i,l,S,ngg))
# pThreadPool.map(__getSimilaritiesForIndex, qToExecute)
map(__getSimilaritiesForIndex,qToExecute)
print ""
print "Getting human similarities... Done."
qToExecute = list() # Reset tasks
print "Getting chicken similarities..."
for i in range(l1,l):
print i," ",
L[i] = 1 #0 for chickens
qToExecute.append((i,l,S,ngg))
# pThreadPool.map(__getSimilaritiesForIndex, qToExecute)
map(__getSimilaritiesForIndex, qToExecute)
| # S[i,j] = sop.getSimilarityDouble(ngg[i],ngg[j])
print ""
print "Getting chicken similarities... Done"
# Update symmetric matrix, based on current findings
for i in range(0,l):
for j in range(0,i):
S[i,j] = S[j,i]
print "Similarity matrix constructed.."
if not os.path.exists('SimilaritiesAndDictionaries'):
os.mkdir('SimilaritiesAndDictionaries')
np.savez('SimilaritiesAndDictionaries/UCNE.npz', hd=hd, cd=cd, l1=l1, l2=l2,
l=l, S=S)
reps = 10
L1 = L[0:l1]
L2 = L[l1:]
metrics = dict()
cm = dict()
class_types = {0:"No kernelization",1:"Spectrum Clip",2:"Spectrum Flip",3:"Spectrum Shift",4:"Spectrum Square"}
print "Testing for different kernelization methods..\n\n"
for i in range(0, len(class_types)):
try:
print class_types[i],"\n"
evaluator = cl.Evaluator(cl.SVM())
Sp = cl.kernelization(S,i)
S1 = Sp[0:l1,:]
S2 = Sp[l1:,:]
metrics[class_types[i]],cm[class_types[i]] = evaluator.Randomized_kfold((S1,S2),(L1,L2),reps,verbose=True)
print ""
except Exception as e:
print "Approach %s failed for reason:\n%s"%(class_types[i], str(e))
np.savez('SimilaritiesAndDictionaries/metrics.npz', metrics=metrics, cm=cm) | # for i in range(l1,l):
# print i," ",
# L[i] = 1 #1 for chickens
# for j in range(i,l): | random_line_split |
UCNES_Class.py | import numpy as np
import os
import sys
import math
#import class files
# sys.path.append('../../../')
from source import bioRead as br
from source import classify as cl
#import PyInsect for measuring similarity
#sys.path.append('../../../../')
from PyINSECT import representations as REP
from PyINSECT import comparators as CMP
from multiprocessing import Pool
import multiprocessing
# Local function
def | (setting):
i, l, S, ngg = setting # Explode
for j in range(i,l):
dTmp = sop.getSimilarityDouble(ngg[i],ngg[j])
if (math.isnan(dTmp)):
raise Exception("Invalid similarity! Check similarity implementation.")
S[i,j] = dTmp
# End local function
# If we have cached the main analysis data
if os.path.exists('SimilaritiesAndDictionaries/UCNE.npz'):
# Use them
npz = np.load('SimilaritiesAndDictionaries/UCNE.npz')
hd = npz['hd']
cd = npz['cd']
S = npz['S']
l1 = npz['l1']
l2 = npz['l2']
l = npz['l']
L = np.append(np.zeros(l1),np.ones(l2),axis=0)
print "WARNING: Using cached data!"
else:
# else start reading
sr = br.SequenceReader()
# Get Human UCNE fasta data
sr.read('./biodata/UCNEs/hg19_UCNEs.fasta')
# sr.read('./biodata/UCNEs/hg19_UCNEs-10.fasta')
hd = sr.getDictionary()
print "Gained Human Dictionary"
# Get Chicken UCNE fasta data
sr.read('./biodata/UCNEs/galGal3_UCNEs.fasta')
# sr.read('./biodata/UCNEs/galGal3_UCNEs-10.fasta')
cd = sr.getDictionary()
print "Gained Chicken Dictionary"
# Set n-gram graph analysis parameters
n=3
Dwin=2
subjectMap = {}
ngg = {}
# Get number of UNCEs (for either type of UNCE)
l1 = len(hd.keys())
l2 = len(cd.keys())
l = l1 + l2
print "Found %d human UNCEs"%(l1)
print "Found %d chicken UNCEs"%(l2)
# For every human UNCE
i = 0
for key,a in hd.iteritems():
# Assign appropriate label
subjectMap[i] = (key,'humans')
# Create corresponding graph
ngg[i] = REP.DocumentNGramGraph(n,Dwin,a)
i += 1
print "Graphs Created for Humans"
for key,b in cd.iteritems():
subjectMap[i] = (key,'chickens')
ngg[i] = REP.DocumentNGramGraph(n,Dwin,b)
i += 1
print "Graphs Created for Chickens"
S = np.empty([l, l])
L = np.empty([l])
sop = CMP.SimilarityNVS()
print "Getting human similarities..."
# TODO: Examine default (problems with locking S)
# pThreadPool = Pool(1);
qToExecute = list() # Reset tasks
for i in range(0,l1):
print i," ",
L[i] = 0 #0 for humans
qToExecute.append((i,l,S,ngg))
# pThreadPool.map(__getSimilaritiesForIndex, qToExecute)
map(__getSimilaritiesForIndex,qToExecute)
print ""
print "Getting human similarities... Done."
qToExecute = list() # Reset tasks
print "Getting chicken similarities..."
for i in range(l1,l):
print i," ",
L[i] = 1 #0 for chickens
qToExecute.append((i,l,S,ngg))
# pThreadPool.map(__getSimilaritiesForIndex, qToExecute)
map(__getSimilaritiesForIndex, qToExecute)
# for i in range(l1,l):
# print i," ",
# L[i] = 1 #1 for chickens
# for j in range(i,l):
# S[i,j] = sop.getSimilarityDouble(ngg[i],ngg[j])
print ""
print "Getting chicken similarities... Done"
# Update symmetric matrix, based on current findings
for i in range(0,l):
for j in range(0,i):
S[i,j] = S[j,i]
print "Similarity matrix constructed.."
if not os.path.exists('SimilaritiesAndDictionaries'):
os.mkdir('SimilaritiesAndDictionaries')
np.savez('SimilaritiesAndDictionaries/UCNE.npz', hd=hd, cd=cd, l1=l1, l2=l2,
l=l, S=S)
reps = 10
L1 = L[0:l1]
L2 = L[l1:]
metrics = dict()
cm = dict()
class_types = {0:"No kernelization",1:"Spectrum Clip",2:"Spectrum Flip",3:"Spectrum Shift",4:"Spectrum Square"}
print "Testing for different kernelization methods..\n\n"
for i in range(0, len(class_types)):
try:
print class_types[i],"\n"
evaluator = cl.Evaluator(cl.SVM())
Sp = cl.kernelization(S,i)
S1 = Sp[0:l1,:]
S2 = Sp[l1:,:]
metrics[class_types[i]],cm[class_types[i]] = evaluator.Randomized_kfold((S1,S2),(L1,L2),reps,verbose=True)
print ""
except Exception as e:
print "Approach %s failed for reason:\n%s"%(class_types[i], str(e))
np.savez('SimilaritiesAndDictionaries/metrics.npz', metrics=metrics, cm=cm)
| __getSimilaritiesForIndex | identifier_name |
UCNES_Class.py | import numpy as np
import os
import sys
import math
#import class files
# sys.path.append('../../../')
from source import bioRead as br
from source import classify as cl
#import PyInsect for measuring similarity
#sys.path.append('../../../../')
from PyINSECT import representations as REP
from PyINSECT import comparators as CMP
from multiprocessing import Pool
import multiprocessing
# Local function
def __getSimilaritiesForIndex(setting):
i, l, S, ngg = setting # Explode
for j in range(i,l):
dTmp = sop.getSimilarityDouble(ngg[i],ngg[j])
if (math.isnan(dTmp)):
raise Exception("Invalid similarity! Check similarity implementation.")
S[i,j] = dTmp
# End local function
# If we have cached the main analysis data
if os.path.exists('SimilaritiesAndDictionaries/UCNE.npz'):
# Use them
npz = np.load('SimilaritiesAndDictionaries/UCNE.npz')
hd = npz['hd']
cd = npz['cd']
S = npz['S']
l1 = npz['l1']
l2 = npz['l2']
l = npz['l']
L = np.append(np.zeros(l1),np.ones(l2),axis=0)
print "WARNING: Using cached data!"
else:
# else start reading
sr = br.SequenceReader()
# Get Human UCNE fasta data
sr.read('./biodata/UCNEs/hg19_UCNEs.fasta')
# sr.read('./biodata/UCNEs/hg19_UCNEs-10.fasta')
hd = sr.getDictionary()
print "Gained Human Dictionary"
# Get Chicken UCNE fasta data
sr.read('./biodata/UCNEs/galGal3_UCNEs.fasta')
# sr.read('./biodata/UCNEs/galGal3_UCNEs-10.fasta')
cd = sr.getDictionary()
print "Gained Chicken Dictionary"
# Set n-gram graph analysis parameters
n=3
Dwin=2
subjectMap = {}
ngg = {}
# Get number of UNCEs (for either type of UNCE)
l1 = len(hd.keys())
l2 = len(cd.keys())
l = l1 + l2
print "Found %d human UNCEs"%(l1)
print "Found %d chicken UNCEs"%(l2)
# For every human UNCE
i = 0
for key,a in hd.iteritems():
# Assign appropriate label
subjectMap[i] = (key,'humans')
# Create corresponding graph
ngg[i] = REP.DocumentNGramGraph(n,Dwin,a)
i += 1
print "Graphs Created for Humans"
for key,b in cd.iteritems():
subjectMap[i] = (key,'chickens')
ngg[i] = REP.DocumentNGramGraph(n,Dwin,b)
i += 1
print "Graphs Created for Chickens"
S = np.empty([l, l])
L = np.empty([l])
sop = CMP.SimilarityNVS()
print "Getting human similarities..."
# TODO: Examine default (problems with locking S)
# pThreadPool = Pool(1);
qToExecute = list() # Reset tasks
for i in range(0,l1):
print i," ",
L[i] = 0 #0 for humans
qToExecute.append((i,l,S,ngg))
# pThreadPool.map(__getSimilaritiesForIndex, qToExecute)
map(__getSimilaritiesForIndex,qToExecute)
print ""
print "Getting human similarities... Done."
qToExecute = list() # Reset tasks
print "Getting chicken similarities..."
for i in range(l1,l):
print i," ",
L[i] = 1 #0 for chickens
qToExecute.append((i,l,S,ngg))
# pThreadPool.map(__getSimilaritiesForIndex, qToExecute)
map(__getSimilaritiesForIndex, qToExecute)
# for i in range(l1,l):
# print i," ",
# L[i] = 1 #1 for chickens
# for j in range(i,l):
# S[i,j] = sop.getSimilarityDouble(ngg[i],ngg[j])
print ""
print "Getting chicken similarities... Done"
# Update symmetric matrix, based on current findings
for i in range(0,l):
for j in range(0,i):
S[i,j] = S[j,i]
print "Similarity matrix constructed.."
if not os.path.exists('SimilaritiesAndDictionaries'):
os.mkdir('SimilaritiesAndDictionaries')
np.savez('SimilaritiesAndDictionaries/UCNE.npz', hd=hd, cd=cd, l1=l1, l2=l2,
l=l, S=S)
reps = 10
L1 = L[0:l1]
L2 = L[l1:]
metrics = dict()
cm = dict()
class_types = {0:"No kernelization",1:"Spectrum Clip",2:"Spectrum Flip",3:"Spectrum Shift",4:"Spectrum Square"}
print "Testing for different kernelization methods..\n\n"
for i in range(0, len(class_types)):
|
np.savez('SimilaritiesAndDictionaries/metrics.npz', metrics=metrics, cm=cm)
| try:
print class_types[i],"\n"
evaluator = cl.Evaluator(cl.SVM())
Sp = cl.kernelization(S,i)
S1 = Sp[0:l1,:]
S2 = Sp[l1:,:]
metrics[class_types[i]],cm[class_types[i]] = evaluator.Randomized_kfold((S1,S2),(L1,L2),reps,verbose=True)
print ""
except Exception as e:
print "Approach %s failed for reason:\n%s"%(class_types[i], str(e)) | conditional_block |
custom-typings.d.ts | /*
* Custom Type Definitions
* When including 3rd party modules you also need to include the type definition for the module
* if they don't provide one within the module. You can try to install it with @types
npm install @types/node
npm install @types/lodash
* If you can't find the type definition in the registry we can make an ambient/global definition in
* this file for now. For example
declare module 'my-module' {
export function doesSomething(value: string): string;
}
* If you are using a CommonJS module that is using module.exports then you will have to write your
* types using export = yourObjectOrFunction with a namespace above it
* notice how we have to create a namespace that is equal to the function we're
* assigning the export to
declare module 'jwt-decode' {
function jwtDecode(token: string): any;
namespace jwtDecode {}
export = jwtDecode;
}
*
* If you're prototying and you will fix the types later you can also declare it as type any
*
declare var assert: any;
declare var _: any;
declare var $: any;
*
* If you're importing a module that uses Node.js modules which are CommonJS you need to import as
* in the files such as main.browser.ts or any file within app/
*
import * as _ from 'lodash'
* You can include your type definitions in this file until you create one for the @types
*
*/ | // support NodeJS modules without type definitions
declare module '*';
/*
// for legacy tslint etc to understand rename 'modern-lru' with your package
// then comment out `declare module '*';`. For each new module copy/paste
// this method of creating an `any` module type definition
declare module 'modern-lru' {
let x: any;
export = x;
}
*/
// Extra variables that live on Global that will be replaced by webpack DefinePlugin
declare var ENV: string;
declare var HMR: boolean;
declare var System: SystemJS;
interface SystemJS {
import: (path?: string) => Promise<any>;
}
interface GlobalEnvironment {
ENV: string;
HMR: boolean;
SystemJS: SystemJS;
System: SystemJS;
}
interface Es6PromiseLoader {
(id: string): (exportName?: string) => Promise<any>;
}
type FactoryEs6PromiseLoader = () => Es6PromiseLoader;
type FactoryPromise = () => Promise<any>;
type AsyncRoutes = {
[component: string]: Es6PromiseLoader |
Function |
FactoryEs6PromiseLoader |
FactoryPromise
};
type IdleCallbacks = Es6PromiseLoader |
Function |
FactoryEs6PromiseLoader |
FactoryPromise ;
interface WebpackModule {
hot: {
data?: any,
idle: any,
accept(dependencies?: string | string[], callback?: (updatedDependencies?: any) => void): void;
decline(deps?: any | string | string[]): void;
dispose(callback?: (data?: any) => void): void;
addDisposeHandler(callback?: (data?: any) => void): void;
removeDisposeHandler(callback?: (data?: any) => void): void;
check(autoApply?: any, callback?: (err?: Error, outdatedModules?: any[]) => void): void;
apply(options?: any, callback?: (err?: Error, outdatedModules?: any[]) => void): void;
status(callback?: (status?: string) => void): void | string;
removeStatusHandler(callback?: (status?: string) => void): void;
};
}
interface WebpackRequire {
(id: string): any;
(paths: string[], callback: (...modules: any[]) => void): void;
ensure(ids: string[], callback: (req: WebpackRequire) => void, chunkName?: string): void;
context(directory: string, useSubDirectories?: boolean, regExp?: RegExp): WebpackContext;
}
interface WebpackContext extends WebpackRequire {
keys(): string[];
}
interface ErrorStackTraceLimit {
stackTraceLimit: number;
}
// Extend typings
interface NodeRequire extends WebpackRequire {}
interface ErrorConstructor extends ErrorStackTraceLimit {}
interface NodeRequireFunction extends Es6PromiseLoader {}
interface NodeModule extends WebpackModule {}
interface Global extends GlobalEnvironment {} | random_line_split |
|
test_hashing.py | import numpy as np
import pandas as pd
import pytest
from dask.dataframe.hashing import hash_pandas_object
from dask.dataframe.utils import assert_eq
@pytest.mark.parametrize('obj', [
pd.Series([1, 2, 3]),
pd.Series([1.0, 1.5, 3.2]),
pd.Series([1.0, 1.5, 3.2], index=[1.5, 1.1, 3.3]),
pd.Series(['a', 'b', 'c']),
pd.Series([True, False, True]),
pd.Index([1, 2, 3]),
pd.Index([True, False, True]),
pd.DataFrame({'x': ['a', 'b', 'c'], 'y': [1, 2, 3]}),
pd.util.testing.makeMissingDataframe(),
pd.util.testing.makeMixedDataFrame(),
pd.util.testing.makeTimeDataFrame(),
pd.util.testing.makeTimeSeries(),
pd.util.testing.makeTimedeltaIndex()])
def test_hash_pandas_object(obj):
a = hash_pandas_object(obj)
b = hash_pandas_object(obj)
if isinstance(a, np.ndarray):
np.testing.assert_equal(a, b)
else:
| assert_eq(a, b) | conditional_block |
|
test_hashing.py | import numpy as np
import pandas as pd
import pytest
from dask.dataframe.hashing import hash_pandas_object
from dask.dataframe.utils import assert_eq
@pytest.mark.parametrize('obj', [
pd.Series([1, 2, 3]),
pd.Series([1.0, 1.5, 3.2]),
pd.Series([1.0, 1.5, 3.2], index=[1.5, 1.1, 3.3]),
pd.Series(['a', 'b', 'c']),
pd.Series([True, False, True]),
pd.Index([1, 2, 3]),
pd.Index([True, False, True]),
pd.DataFrame({'x': ['a', 'b', 'c'], 'y': [1, 2, 3]}),
pd.util.testing.makeMissingDataframe(),
pd.util.testing.makeMixedDataFrame(),
pd.util.testing.makeTimeDataFrame(),
pd.util.testing.makeTimeSeries(),
pd.util.testing.makeTimedeltaIndex()])
def test_hash_pandas_object(obj): | a = hash_pandas_object(obj)
b = hash_pandas_object(obj)
if isinstance(a, np.ndarray):
np.testing.assert_equal(a, b)
else:
assert_eq(a, b) | random_line_split |
|
test_hashing.py | import numpy as np
import pandas as pd
import pytest
from dask.dataframe.hashing import hash_pandas_object
from dask.dataframe.utils import assert_eq
@pytest.mark.parametrize('obj', [
pd.Series([1, 2, 3]),
pd.Series([1.0, 1.5, 3.2]),
pd.Series([1.0, 1.5, 3.2], index=[1.5, 1.1, 3.3]),
pd.Series(['a', 'b', 'c']),
pd.Series([True, False, True]),
pd.Index([1, 2, 3]),
pd.Index([True, False, True]),
pd.DataFrame({'x': ['a', 'b', 'c'], 'y': [1, 2, 3]}),
pd.util.testing.makeMissingDataframe(),
pd.util.testing.makeMixedDataFrame(),
pd.util.testing.makeTimeDataFrame(),
pd.util.testing.makeTimeSeries(),
pd.util.testing.makeTimedeltaIndex()])
def | (obj):
a = hash_pandas_object(obj)
b = hash_pandas_object(obj)
if isinstance(a, np.ndarray):
np.testing.assert_equal(a, b)
else:
assert_eq(a, b)
| test_hash_pandas_object | identifier_name |
test_hashing.py | import numpy as np
import pandas as pd
import pytest
from dask.dataframe.hashing import hash_pandas_object
from dask.dataframe.utils import assert_eq
@pytest.mark.parametrize('obj', [
pd.Series([1, 2, 3]),
pd.Series([1.0, 1.5, 3.2]),
pd.Series([1.0, 1.5, 3.2], index=[1.5, 1.1, 3.3]),
pd.Series(['a', 'b', 'c']),
pd.Series([True, False, True]),
pd.Index([1, 2, 3]),
pd.Index([True, False, True]),
pd.DataFrame({'x': ['a', 'b', 'c'], 'y': [1, 2, 3]}),
pd.util.testing.makeMissingDataframe(),
pd.util.testing.makeMixedDataFrame(),
pd.util.testing.makeTimeDataFrame(),
pd.util.testing.makeTimeSeries(),
pd.util.testing.makeTimedeltaIndex()])
def test_hash_pandas_object(obj):
| a = hash_pandas_object(obj)
b = hash_pandas_object(obj)
if isinstance(a, np.ndarray):
np.testing.assert_equal(a, b)
else:
assert_eq(a, b) | identifier_body |
|
pre_NAMD.py | # pre_NAMD.py
# Creates the files used for NAMD based on the .pdb file dowloaded from PDB bank
#
# Usage:
# python pre_NAMD.py $PDBID
#
# $PDBID=the 4 characters identification code of the .pdb file
#
# Input:
# $PDBID.pdb: .pdb file downloaded from PDB bank
#
# Output:
# $PDBID_p.pdb: .pdb file with water molecules removed
# $PDBID_p_h.pdb: .pdb file with water removed and hydrogen atoms added
# $PDBID_p_h.psf: .psf file of $PDBID_p_h.pdb
# $PDBID_p_h.log: Log file of adding hydrogen atoms
# $PDBID_wb.pdb: .pdb file of the water box model
# $PDBID_wb.psf: .psf file of $PDBID_wb.pdb
# $PDBID_wb.log: Log file of the water box model generation
# $PDBID_wb_i.pdb: .pdb file of the ionized water box model (For NAMD)
# $PDBID_wb_i.psf: .psf file of PDBID_wb_i.pdb (For NAMD)
# $PDBID.log: Log file of the whole process (output of VMD)
# $PDBID_center.txt: File contains the grid and center information of
# the ionized water box model
#
# Author: Xiaofei Zhang
# Date: June 20 2016
from __future__ import print_function
import sys, os
def print_error(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
# main
if len(sys.argv) != 2:
|
mypath = os.path.realpath(__file__)
tclpath = os.path.split(mypath)[0] + os.path.sep + 'tcl' + os.path.sep
pdbid = sys.argv[1]
logfile = pdbid+'.log'
# Using the right path of VMD
vmd = "/Volumes/VMD-1.9.2/VMD 1.9.2.app/Contents/vmd/vmd_MACOSXX86"
print("Input: "+pdbid+".pdb")
# Remove water
print("Remove water..")
cmdline = '\"'+ vmd + '\"' +' -dispdev text -eofexit < '+ tclpath + 'remove_water.tcl' + ' ' + '-args' + ' '+ pdbid +'> '+ logfile
os.system(cmdline)
# Create .psf
print("Create PSF file...")
cmdline = '\"'+ vmd + '\"' +' -dispdev text -eofexit < '+ tclpath + 'create_psf.tcl' + ' ' + '-args' + ' '+ pdbid +'>> '+ logfile
os.system(cmdline)
# Build water box
print("Build water box...")
cmdline = '\"'+ vmd + '\"' +' -dispdev text -eofexit < '+ tclpath + 'build_water_box.tcl' + ' ' + '-args' + ' '+ pdbid +'>> '+ logfile
os.system(cmdline)
# Add ions
print("Add ions...")
cmdline = '\"'+ vmd + '\"' +' -dispdev text -eofexit < '+ tclpath + 'add_ion.tcl' + ' ' + '-args' + ' '+ pdbid +'>> '+ logfile
os.system(cmdline)
# Calculate grid and center
print("Calculate center coordinates...")
cmdline = '\"'+ vmd + '\"' +' -dispdev text -eofexit < '+ tclpath + 'get_center.tcl' + ' ' + '-args' + ' '+ pdbid +'>> '+ logfile
os.system(cmdline)
print("Finish!")
# end main
| print_error("Usage: python pre_NAMD.py $PDBID")
sys.exit(-1) | conditional_block |
pre_NAMD.py | # pre_NAMD.py
# Creates the files used for NAMD based on the .pdb file dowloaded from PDB bank
#
# Usage:
# python pre_NAMD.py $PDBID
#
# $PDBID=the 4 characters identification code of the .pdb file
#
# Input:
# $PDBID.pdb: .pdb file downloaded from PDB bank
#
# Output:
# $PDBID_p.pdb: .pdb file with water molecules removed
# $PDBID_p_h.pdb: .pdb file with water removed and hydrogen atoms added
# $PDBID_p_h.psf: .psf file of $PDBID_p_h.pdb
# $PDBID_p_h.log: Log file of adding hydrogen atoms
# $PDBID_wb.pdb: .pdb file of the water box model
# $PDBID_wb.psf: .psf file of $PDBID_wb.pdb
# $PDBID_wb.log: Log file of the water box model generation
# $PDBID_wb_i.pdb: .pdb file of the ionized water box model (For NAMD)
# $PDBID_wb_i.psf: .psf file of PDBID_wb_i.pdb (For NAMD)
# $PDBID.log: Log file of the whole process (output of VMD)
# $PDBID_center.txt: File contains the grid and center information of
# the ionized water box model
#
# Author: Xiaofei Zhang
# Date: June 20 2016
from __future__ import print_function
import sys, os
def | (*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
# main
if len(sys.argv) != 2:
print_error("Usage: python pre_NAMD.py $PDBID")
sys.exit(-1)
mypath = os.path.realpath(__file__)
tclpath = os.path.split(mypath)[0] + os.path.sep + 'tcl' + os.path.sep
pdbid = sys.argv[1]
logfile = pdbid+'.log'
# Using the right path of VMD
vmd = "/Volumes/VMD-1.9.2/VMD 1.9.2.app/Contents/vmd/vmd_MACOSXX86"
print("Input: "+pdbid+".pdb")
# Remove water
print("Remove water..")
cmdline = '\"'+ vmd + '\"' +' -dispdev text -eofexit < '+ tclpath + 'remove_water.tcl' + ' ' + '-args' + ' '+ pdbid +'> '+ logfile
os.system(cmdline)
# Create .psf
print("Create PSF file...")
cmdline = '\"'+ vmd + '\"' +' -dispdev text -eofexit < '+ tclpath + 'create_psf.tcl' + ' ' + '-args' + ' '+ pdbid +'>> '+ logfile
os.system(cmdline)
# Build water box
print("Build water box...")
cmdline = '\"'+ vmd + '\"' +' -dispdev text -eofexit < '+ tclpath + 'build_water_box.tcl' + ' ' + '-args' + ' '+ pdbid +'>> '+ logfile
os.system(cmdline)
# Add ions
print("Add ions...")
cmdline = '\"'+ vmd + '\"' +' -dispdev text -eofexit < '+ tclpath + 'add_ion.tcl' + ' ' + '-args' + ' '+ pdbid +'>> '+ logfile
os.system(cmdline)
# Calculate grid and center
print("Calculate center coordinates...")
cmdline = '\"'+ vmd + '\"' +' -dispdev text -eofexit < '+ tclpath + 'get_center.tcl' + ' ' + '-args' + ' '+ pdbid +'>> '+ logfile
os.system(cmdline)
print("Finish!")
# end main
| print_error | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.