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 |
|---|---|---|---|---|
lib.rs | //! # `peeking_take_while`
//!
//! Provides the `peeking_take_while` iterator adaptor method.
//!
//! The `peeking_take_while` method is very similar to `take_while`, but behaves
//! differently when used with a borrowed iterator (perhaps returned by
//! `Iterator::by_ref`).
//!
//! `peeking_take_while` peeks at the next item in the iterator and runs the
//! predicate on that peeked item. This avoids consuming the first item yielded
//! by the underlying iterator for which the predicate returns `false`. On the
//! other hand, `take_while` will consume that first item for which the
//! predicate returns `false`, and it will be lost.
//!
//! ```
//! extern crate peeking_take_while;
//!
//! // Bring the `peeking_take_while` method for peekable iterators into
//! // scope.
//! use peeking_take_while::PeekableExt;
//!
//! # fn main() {
//! // Let's say we have two collections we want to iterate through: `xs` and
//! // `ys`. We want to perform one operation on all the leading contiguous
//! // elements that match some predicate, and a different thing with the rest of
//! // the elements. With the `xs`, we will use the normal `take_while`. With the
//! // `ys`, we will use `peeking_take_while`.
//!
//! let xs: Vec<u8> = (0..100).collect();
//! let ys = xs.clone();
//!
//! let mut iter_xs = xs.into_iter();
//! let mut iter_ys = ys.into_iter().peekable();
//!
//! {
//! // Let's do one thing with all the items that are less than 10.
//! # fn do_things_with<T>(_: T) {}
//!
//! let xs_less_than_ten = iter_xs.by_ref().take_while(|x| *x < 10);
//! for x in xs_less_than_ten {
//! do_things_with(x);
//! }
//!
//! let ys_less_than_ten = iter_ys.by_ref().peeking_take_while(|y| *y < 10);
//! for y in ys_less_than_ten {
//! do_things_with(y);
//! }
//! }
//! | //! // or equal to 10.
//!
//! // ...except, when using plain old `take_while` we lost 10!
//! assert_eq!(iter_xs.next(), Some(11));
//!
//! // However, when using `peeking_take_while` we did not! Great!
//! assert_eq!(iter_ys.next(), Some(10));
//! # }
//! ```
use std::iter::Peekable;
/// The iterator returned by `peeking_take_while`.
///
/// See the [module documentation](./index.html) for details.
pub struct PeekingTakeWhile<'a, I, P>
where I: 'a + Iterator
{
iter: &'a mut Peekable<I>,
predicate: P,
}
impl<'a, I, P> Iterator for PeekingTakeWhile<'a, I, P>
where I: Iterator,
I::Item: ::std::fmt::Debug,
P: FnMut(&<I as Iterator>::Item) -> bool
{
type Item = <I as Iterator>::Item;
fn next(&mut self) -> Option<Self::Item> {
let predicate = &mut self.predicate;
if self.iter.peek().map_or(false, |x| !(predicate)(x)) {
None
} else {
self.iter.next()
}
}
}
/// The `Iterator` extension trait that provides the `peeking_take_while`
/// method.
///
/// See the [module documentation](./index.html) for details.
pub trait PeekableExt<'a, I>: Iterator
where I: 'a + Iterator
{
/// The `Iterator` extension trait that provides the `peeking_take_while`
/// method.
///
/// See the [module documentation](./index.html) for details.
fn peeking_take_while<P>(&'a mut self, predicate: P) -> PeekingTakeWhile<'a, I, P>
where Self: Sized,
P: FnMut(&<Self as Iterator>::Item) -> bool;
}
impl<'a, I> PeekableExt<'a, I> for Peekable<I>
where I: 'a + Iterator
{
fn peeking_take_while<P>(&'a mut self, predicate: P) -> PeekingTakeWhile<I, P>
where P: FnMut(&<Self as Iterator>::Item) -> bool
{
PeekingTakeWhile {
iter: self,
predicate: predicate,
}
}
} | //! // And now we will do some other thing with the items that are greater than | random_line_split |
lib.rs | //! # `peeking_take_while`
//!
//! Provides the `peeking_take_while` iterator adaptor method.
//!
//! The `peeking_take_while` method is very similar to `take_while`, but behaves
//! differently when used with a borrowed iterator (perhaps returned by
//! `Iterator::by_ref`).
//!
//! `peeking_take_while` peeks at the next item in the iterator and runs the
//! predicate on that peeked item. This avoids consuming the first item yielded
//! by the underlying iterator for which the predicate returns `false`. On the
//! other hand, `take_while` will consume that first item for which the
//! predicate returns `false`, and it will be lost.
//!
//! ```
//! extern crate peeking_take_while;
//!
//! // Bring the `peeking_take_while` method for peekable iterators into
//! // scope.
//! use peeking_take_while::PeekableExt;
//!
//! # fn main() {
//! // Let's say we have two collections we want to iterate through: `xs` and
//! // `ys`. We want to perform one operation on all the leading contiguous
//! // elements that match some predicate, and a different thing with the rest of
//! // the elements. With the `xs`, we will use the normal `take_while`. With the
//! // `ys`, we will use `peeking_take_while`.
//!
//! let xs: Vec<u8> = (0..100).collect();
//! let ys = xs.clone();
//!
//! let mut iter_xs = xs.into_iter();
//! let mut iter_ys = ys.into_iter().peekable();
//!
//! {
//! // Let's do one thing with all the items that are less than 10.
//! # fn do_things_with<T>(_: T) {}
//!
//! let xs_less_than_ten = iter_xs.by_ref().take_while(|x| *x < 10);
//! for x in xs_less_than_ten {
//! do_things_with(x);
//! }
//!
//! let ys_less_than_ten = iter_ys.by_ref().peeking_take_while(|y| *y < 10);
//! for y in ys_less_than_ten {
//! do_things_with(y);
//! }
//! }
//!
//! // And now we will do some other thing with the items that are greater than
//! // or equal to 10.
//!
//! // ...except, when using plain old `take_while` we lost 10!
//! assert_eq!(iter_xs.next(), Some(11));
//!
//! // However, when using `peeking_take_while` we did not! Great!
//! assert_eq!(iter_ys.next(), Some(10));
//! # }
//! ```
use std::iter::Peekable;
/// The iterator returned by `peeking_take_while`.
///
/// See the [module documentation](./index.html) for details.
pub struct PeekingTakeWhile<'a, I, P>
where I: 'a + Iterator
{
iter: &'a mut Peekable<I>,
predicate: P,
}
impl<'a, I, P> Iterator for PeekingTakeWhile<'a, I, P>
where I: Iterator,
I::Item: ::std::fmt::Debug,
P: FnMut(&<I as Iterator>::Item) -> bool
{
type Item = <I as Iterator>::Item;
fn next(&mut self) -> Option<Self::Item> {
let predicate = &mut self.predicate;
if self.iter.peek().map_or(false, |x| !(predicate)(x)) {
None
} else {
self.iter.next()
}
}
}
/// The `Iterator` extension trait that provides the `peeking_take_while`
/// method.
///
/// See the [module documentation](./index.html) for details.
pub trait PeekableExt<'a, I>: Iterator
where I: 'a + Iterator
{
/// The `Iterator` extension trait that provides the `peeking_take_while`
/// method.
///
/// See the [module documentation](./index.html) for details.
fn peeking_take_while<P>(&'a mut self, predicate: P) -> PeekingTakeWhile<'a, I, P>
where Self: Sized,
P: FnMut(&<Self as Iterator>::Item) -> bool;
}
impl<'a, I> PeekableExt<'a, I> for Peekable<I>
where I: 'a + Iterator
{
fn | <P>(&'a mut self, predicate: P) -> PeekingTakeWhile<I, P>
where P: FnMut(&<Self as Iterator>::Item) -> bool
{
PeekingTakeWhile {
iter: self,
predicate: predicate,
}
}
}
| peeking_take_while | identifier_name |
lib.rs | //! # `peeking_take_while`
//!
//! Provides the `peeking_take_while` iterator adaptor method.
//!
//! The `peeking_take_while` method is very similar to `take_while`, but behaves
//! differently when used with a borrowed iterator (perhaps returned by
//! `Iterator::by_ref`).
//!
//! `peeking_take_while` peeks at the next item in the iterator and runs the
//! predicate on that peeked item. This avoids consuming the first item yielded
//! by the underlying iterator for which the predicate returns `false`. On the
//! other hand, `take_while` will consume that first item for which the
//! predicate returns `false`, and it will be lost.
//!
//! ```
//! extern crate peeking_take_while;
//!
//! // Bring the `peeking_take_while` method for peekable iterators into
//! // scope.
//! use peeking_take_while::PeekableExt;
//!
//! # fn main() {
//! // Let's say we have two collections we want to iterate through: `xs` and
//! // `ys`. We want to perform one operation on all the leading contiguous
//! // elements that match some predicate, and a different thing with the rest of
//! // the elements. With the `xs`, we will use the normal `take_while`. With the
//! // `ys`, we will use `peeking_take_while`.
//!
//! let xs: Vec<u8> = (0..100).collect();
//! let ys = xs.clone();
//!
//! let mut iter_xs = xs.into_iter();
//! let mut iter_ys = ys.into_iter().peekable();
//!
//! {
//! // Let's do one thing with all the items that are less than 10.
//! # fn do_things_with<T>(_: T) {}
//!
//! let xs_less_than_ten = iter_xs.by_ref().take_while(|x| *x < 10);
//! for x in xs_less_than_ten {
//! do_things_with(x);
//! }
//!
//! let ys_less_than_ten = iter_ys.by_ref().peeking_take_while(|y| *y < 10);
//! for y in ys_less_than_ten {
//! do_things_with(y);
//! }
//! }
//!
//! // And now we will do some other thing with the items that are greater than
//! // or equal to 10.
//!
//! // ...except, when using plain old `take_while` we lost 10!
//! assert_eq!(iter_xs.next(), Some(11));
//!
//! // However, when using `peeking_take_while` we did not! Great!
//! assert_eq!(iter_ys.next(), Some(10));
//! # }
//! ```
use std::iter::Peekable;
/// The iterator returned by `peeking_take_while`.
///
/// See the [module documentation](./index.html) for details.
pub struct PeekingTakeWhile<'a, I, P>
where I: 'a + Iterator
{
iter: &'a mut Peekable<I>,
predicate: P,
}
impl<'a, I, P> Iterator for PeekingTakeWhile<'a, I, P>
where I: Iterator,
I::Item: ::std::fmt::Debug,
P: FnMut(&<I as Iterator>::Item) -> bool
{
type Item = <I as Iterator>::Item;
fn next(&mut self) -> Option<Self::Item> {
let predicate = &mut self.predicate;
if self.iter.peek().map_or(false, |x| !(predicate)(x)) {
None
} else |
}
}
/// The `Iterator` extension trait that provides the `peeking_take_while`
/// method.
///
/// See the [module documentation](./index.html) for details.
pub trait PeekableExt<'a, I>: Iterator
where I: 'a + Iterator
{
/// The `Iterator` extension trait that provides the `peeking_take_while`
/// method.
///
/// See the [module documentation](./index.html) for details.
fn peeking_take_while<P>(&'a mut self, predicate: P) -> PeekingTakeWhile<'a, I, P>
where Self: Sized,
P: FnMut(&<Self as Iterator>::Item) -> bool;
}
impl<'a, I> PeekableExt<'a, I> for Peekable<I>
where I: 'a + Iterator
{
fn peeking_take_while<P>(&'a mut self, predicate: P) -> PeekingTakeWhile<I, P>
where P: FnMut(&<Self as Iterator>::Item) -> bool
{
PeekingTakeWhile {
iter: self,
predicate: predicate,
}
}
}
| {
self.iter.next()
} | conditional_block |
project.py | from corecat.constants import OBJECT_CODES, MODEL_VERSION
from ._sqlalchemy import Base, CoreCatBaseMixin
from ._sqlalchemy import Column, \
Integer, \
String, Text
class Project(CoreCatBaseMixin, Base):
"""Project Model class represent for the 'projects' table
which is used to store project's basic information."""
# Add the real table name here.
# TODO: Add the database prefix here
__tablename__ = 'project'
# Column definition
project_id = Column('id', Integer,
primary_key=True,
autoincrement=True
)
project_name = Column('name', String(100),
nullable=False
)
project_description = Column('description', Text,
nullable=True
)
# Relationship
# TODO: Building relationship
def __init__(self, project_name,
created_by_user_id,
**kwargs):
| """
Constructor of Project Model Class.
:param project_name: Name of the project.
:param created_by_user_id: Project is created under this user ID.
:param project_description: Description of the project.
"""
self.set_up_basic_information(
MODEL_VERSION[OBJECT_CODES['Project']],
created_by_user_id
)
self.project_name = project_name
self.project_description = kwargs.get('project_description', None) | identifier_body | |
project.py | from corecat.constants import OBJECT_CODES, MODEL_VERSION
from ._sqlalchemy import Base, CoreCatBaseMixin
from ._sqlalchemy import Column, \
Integer, \
String, Text
class Project(CoreCatBaseMixin, Base):
"""Project Model class represent for the 'projects' table
which is used to store project's basic information."""
# Add the real table name here.
# TODO: Add the database prefix here
__tablename__ = 'project'
# Column definition
project_id = Column('id', Integer,
primary_key=True,
autoincrement=True
)
project_name = Column('name', String(100),
nullable=False
)
project_description = Column('description', Text,
nullable=True
)
# Relationship
# TODO: Building relationship
def __init__(self, project_name,
created_by_user_id,
**kwargs):
"""
Constructor of Project Model Class.
:param project_name: Name of the project.
:param created_by_user_id: Project is created under this user ID. | MODEL_VERSION[OBJECT_CODES['Project']],
created_by_user_id
)
self.project_name = project_name
self.project_description = kwargs.get('project_description', None) | :param project_description: Description of the project.
"""
self.set_up_basic_information( | random_line_split |
project.py | from corecat.constants import OBJECT_CODES, MODEL_VERSION
from ._sqlalchemy import Base, CoreCatBaseMixin
from ._sqlalchemy import Column, \
Integer, \
String, Text
class Project(CoreCatBaseMixin, Base):
"""Project Model class represent for the 'projects' table
which is used to store project's basic information."""
# Add the real table name here.
# TODO: Add the database prefix here
__tablename__ = 'project'
# Column definition
project_id = Column('id', Integer,
primary_key=True,
autoincrement=True
)
project_name = Column('name', String(100),
nullable=False
)
project_description = Column('description', Text,
nullable=True
)
# Relationship
# TODO: Building relationship
def | (self, project_name,
created_by_user_id,
**kwargs):
"""
Constructor of Project Model Class.
:param project_name: Name of the project.
:param created_by_user_id: Project is created under this user ID.
:param project_description: Description of the project.
"""
self.set_up_basic_information(
MODEL_VERSION[OBJECT_CODES['Project']],
created_by_user_id
)
self.project_name = project_name
self.project_description = kwargs.get('project_description', None)
| __init__ | identifier_name |
month.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use std::io::Write;
use std::str::FromStr;
use filters::filter::Filter;
use chrono::NaiveDateTime;
use anyhow::Error;
use anyhow::Result;
use resiter::AndThen;
use resiter::Filter as RFilter;
use libimagstore::store::FileLockEntry;
use libimagtimetrack::store::TimeTrackStore;
use libimagtimetrack::tag::TimeTrackingTag;
use libimagtimetrack::iter::filter::*;
use libimagtimetrack::timetracking::TimeTracking;
use libimagrt::runtime::Runtime;
pub fn month(rt: &Runtime) -> Result<()> | {
let cmd = rt.cli().subcommand().1.unwrap(); // checked in main
let filter = {
use chrono::offset::Local;
use chrono::naive::NaiveDate;
use chrono::Datelike;
let now = Local::now();
let start = match cmd.value_of("start").map(::chrono::naive::NaiveDateTime::from_str) {
None => NaiveDate::from_ymd(now.year(), now.month(), 1).and_hms(0, 0, 0),
Some(s) => s?,
};
let end = match cmd.value_of("end").map(::chrono::naive::NaiveDateTime::from_str) {
None => {
// Is it much harder to go to the last second of the current month than to the first
// second of the next month, right?
let (year, month) = if now.month() == 12 {
(now.year() + 1, 1)
} else {
(now.year(), now.month() + 1)
};
NaiveDate::from_ymd(year, month, 1).and_hms(0, 0, 0)
},
Some(s) => s?,
};
let tags = cmd
.values_of("tags")
.map(|ts| ts.map(String::from).map(TimeTrackingTag::from).collect::<Vec<_>>());
let start_time_filter = has_start_time_where(move |dt: &NaiveDateTime| {
start <= *dt
});
let end_time_filter = has_end_time_where(move |dt: &NaiveDateTime| {
end >= *dt
});
let tags_filter = move |fle: &FileLockEntry| {
match tags {
Some(ref tags) => has_one_of_tags(&tags).filter(fle),
None => true,
}
};
tags_filter.and(start_time_filter).and(end_time_filter)
};
rt.store()
.get_timetrackings()?
.filter_ok(|e| filter.filter(e))
.and_then_ok(|e| -> Result<_> {
debug!("Processing {:?}", e.get_location());
let tag = e.get_timetrack_tag()?;
debug!(" -> tag = {:?}", tag);
let start = e.get_start_datetime()?;
debug!(" -> start = {:?}", start);
let end = e.get_end_datetime()?;
debug!(" -> end = {:?}", end);
rt.report_touched(e.get_location())
.map_err(Error::from)
.map(|_| (tag, start, end))
})
.and_then_ok(|(tag, start, end)| {
match (start, end) {
(None, _) => writeln!(rt.stdout(), "{} has no start time.", tag),
(Some(s), None) => writeln!(rt.stdout(), "{} | {} - ...", tag, s),
(Some(s), Some(e)) => writeln!(rt.stdout(), "{} | {} - {}", tag, s, e),
}.map_err(Error::from)
})
.collect::<Result<Vec<_>>>()
.map(|_| ())
} | identifier_body | |
month.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use std::io::Write;
use std::str::FromStr;
use filters::filter::Filter;
use chrono::NaiveDateTime;
use anyhow::Error;
use anyhow::Result;
use resiter::AndThen;
use resiter::Filter as RFilter;
use libimagstore::store::FileLockEntry;
use libimagtimetrack::store::TimeTrackStore;
use libimagtimetrack::tag::TimeTrackingTag;
use libimagtimetrack::iter::filter::*;
use libimagtimetrack::timetracking::TimeTracking;
use libimagrt::runtime::Runtime;
pub fn | (rt: &Runtime) -> Result<()> {
let cmd = rt.cli().subcommand().1.unwrap(); // checked in main
let filter = {
use chrono::offset::Local;
use chrono::naive::NaiveDate;
use chrono::Datelike;
let now = Local::now();
let start = match cmd.value_of("start").map(::chrono::naive::NaiveDateTime::from_str) {
None => NaiveDate::from_ymd(now.year(), now.month(), 1).and_hms(0, 0, 0),
Some(s) => s?,
};
let end = match cmd.value_of("end").map(::chrono::naive::NaiveDateTime::from_str) {
None => {
// Is it much harder to go to the last second of the current month than to the first
// second of the next month, right?
let (year, month) = if now.month() == 12 {
(now.year() + 1, 1)
} else {
(now.year(), now.month() + 1)
};
NaiveDate::from_ymd(year, month, 1).and_hms(0, 0, 0)
},
Some(s) => s?,
};
let tags = cmd
.values_of("tags")
.map(|ts| ts.map(String::from).map(TimeTrackingTag::from).collect::<Vec<_>>());
let start_time_filter = has_start_time_where(move |dt: &NaiveDateTime| {
start <= *dt
});
let end_time_filter = has_end_time_where(move |dt: &NaiveDateTime| {
end >= *dt
});
let tags_filter = move |fle: &FileLockEntry| {
match tags {
Some(ref tags) => has_one_of_tags(&tags).filter(fle),
None => true,
}
};
tags_filter.and(start_time_filter).and(end_time_filter)
};
rt.store()
.get_timetrackings()?
.filter_ok(|e| filter.filter(e))
.and_then_ok(|e| -> Result<_> {
debug!("Processing {:?}", e.get_location());
let tag = e.get_timetrack_tag()?;
debug!(" -> tag = {:?}", tag);
let start = e.get_start_datetime()?;
debug!(" -> start = {:?}", start);
let end = e.get_end_datetime()?;
debug!(" -> end = {:?}", end);
rt.report_touched(e.get_location())
.map_err(Error::from)
.map(|_| (tag, start, end))
})
.and_then_ok(|(tag, start, end)| {
match (start, end) {
(None, _) => writeln!(rt.stdout(), "{} has no start time.", tag),
(Some(s), None) => writeln!(rt.stdout(), "{} | {} - ...", tag, s),
(Some(s), Some(e)) => writeln!(rt.stdout(), "{} | {} - {}", tag, s, e),
}.map_err(Error::from)
})
.collect::<Result<Vec<_>>>()
.map(|_| ())
}
| month | identifier_name |
month.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use std::io::Write;
use std::str::FromStr;
use filters::filter::Filter;
use chrono::NaiveDateTime;
use anyhow::Error;
use anyhow::Result;
use resiter::AndThen;
use resiter::Filter as RFilter;
use libimagstore::store::FileLockEntry;
use libimagtimetrack::store::TimeTrackStore;
use libimagtimetrack::tag::TimeTrackingTag;
use libimagtimetrack::iter::filter::*;
use libimagtimetrack::timetracking::TimeTracking;
use libimagrt::runtime::Runtime;
pub fn month(rt: &Runtime) -> Result<()> {
let cmd = rt.cli().subcommand().1.unwrap(); // checked in main
let filter = {
use chrono::offset::Local;
use chrono::naive::NaiveDate;
use chrono::Datelike;
let now = Local::now();
let start = match cmd.value_of("start").map(::chrono::naive::NaiveDateTime::from_str) {
None => NaiveDate::from_ymd(now.year(), now.month(), 1).and_hms(0, 0, 0),
Some(s) => s?,
};
let end = match cmd.value_of("end").map(::chrono::naive::NaiveDateTime::from_str) {
None => {
// Is it much harder to go to the last second of the current month than to the first
// second of the next month, right?
let (year, month) = if now.month() == 12 {
(now.year() + 1, 1)
} else {
(now.year(), now.month() + 1)
};
NaiveDate::from_ymd(year, month, 1).and_hms(0, 0, 0)
},
Some(s) => s?,
};
let tags = cmd
.values_of("tags")
.map(|ts| ts.map(String::from).map(TimeTrackingTag::from).collect::<Vec<_>>());
let start_time_filter = has_start_time_where(move |dt: &NaiveDateTime| {
start <= *dt
});
let end_time_filter = has_end_time_where(move |dt: &NaiveDateTime| {
end >= *dt
});
let tags_filter = move |fle: &FileLockEntry| {
match tags {
Some(ref tags) => has_one_of_tags(&tags).filter(fle),
None => true,
}
};
tags_filter.and(start_time_filter).and(end_time_filter)
};
rt.store()
.get_timetrackings()?
.filter_ok(|e| filter.filter(e))
.and_then_ok(|e| -> Result<_> { | debug!(" -> tag = {:?}", tag);
let start = e.get_start_datetime()?;
debug!(" -> start = {:?}", start);
let end = e.get_end_datetime()?;
debug!(" -> end = {:?}", end);
rt.report_touched(e.get_location())
.map_err(Error::from)
.map(|_| (tag, start, end))
})
.and_then_ok(|(tag, start, end)| {
match (start, end) {
(None, _) => writeln!(rt.stdout(), "{} has no start time.", tag),
(Some(s), None) => writeln!(rt.stdout(), "{} | {} - ...", tag, s),
(Some(s), Some(e)) => writeln!(rt.stdout(), "{} | {} - {}", tag, s, e),
}.map_err(Error::from)
})
.collect::<Result<Vec<_>>>()
.map(|_| ())
} | debug!("Processing {:?}", e.get_location());
let tag = e.get_timetrack_tag()?; | random_line_split |
blocks.py | from eth_utils import (
is_hex,
is_string,
is_integer,
remove_0x_prefix,
force_text,
)
def is_predefined_block_number(value):
if not is_string(value):
return False
return force_text(value) in {"latest", "pending", "earliest"}
def is_hex_encoded_block_hash(value):
if not is_string(value):
return False
return len(remove_0x_prefix(value)) == 64 and is_hex(value)
def is_hex_encoded_block_number(value):
if not is_string(value):
return False
elif is_hex_encoded_block_hash(value):
return False
try:
value_as_int = int(value, 16)
except ValueError:
return False
return 0 <= value_as_int < 2**256
def select_method_for_block_identifier(value, if_hash, if_number, if_predefined):
| if is_predefined_block_number(value):
return if_predefined
elif isinstance(value, bytes):
return if_hash
elif is_hex_encoded_block_hash(value):
return if_hash
elif is_integer(value) and (0 <= value < 2**256):
return if_number
elif is_hex_encoded_block_number(value):
return if_number
else:
raise ValueError(
"Value did not match any of the recognized block identifiers: {0}".format(value)
) | identifier_body | |
blocks.py | from eth_utils import (
is_hex,
is_string,
is_integer,
remove_0x_prefix,
force_text,
)
def is_predefined_block_number(value):
if not is_string(value):
return False
return force_text(value) in {"latest", "pending", "earliest"}
def is_hex_encoded_block_hash(value):
if not is_string(value):
return False
return len(remove_0x_prefix(value)) == 64 and is_hex(value)
def is_hex_encoded_block_number(value):
if not is_string(value):
return False
elif is_hex_encoded_block_hash(value):
return False
try:
value_as_int = int(value, 16)
except ValueError: | return 0 <= value_as_int < 2**256
def select_method_for_block_identifier(value, if_hash, if_number, if_predefined):
if is_predefined_block_number(value):
return if_predefined
elif isinstance(value, bytes):
return if_hash
elif is_hex_encoded_block_hash(value):
return if_hash
elif is_integer(value) and (0 <= value < 2**256):
return if_number
elif is_hex_encoded_block_number(value):
return if_number
else:
raise ValueError(
"Value did not match any of the recognized block identifiers: {0}".format(value)
) | return False | random_line_split |
blocks.py | from eth_utils import (
is_hex,
is_string,
is_integer,
remove_0x_prefix,
force_text,
)
def is_predefined_block_number(value):
if not is_string(value):
return False
return force_text(value) in {"latest", "pending", "earliest"}
def is_hex_encoded_block_hash(value):
if not is_string(value):
return False
return len(remove_0x_prefix(value)) == 64 and is_hex(value)
def is_hex_encoded_block_number(value):
if not is_string(value):
return False
elif is_hex_encoded_block_hash(value):
return False
try:
value_as_int = int(value, 16)
except ValueError:
return False
return 0 <= value_as_int < 2**256
def | (value, if_hash, if_number, if_predefined):
if is_predefined_block_number(value):
return if_predefined
elif isinstance(value, bytes):
return if_hash
elif is_hex_encoded_block_hash(value):
return if_hash
elif is_integer(value) and (0 <= value < 2**256):
return if_number
elif is_hex_encoded_block_number(value):
return if_number
else:
raise ValueError(
"Value did not match any of the recognized block identifiers: {0}".format(value)
)
| select_method_for_block_identifier | identifier_name |
blocks.py | from eth_utils import (
is_hex,
is_string,
is_integer,
remove_0x_prefix,
force_text,
)
def is_predefined_block_number(value):
if not is_string(value):
return False
return force_text(value) in {"latest", "pending", "earliest"}
def is_hex_encoded_block_hash(value):
if not is_string(value):
return False
return len(remove_0x_prefix(value)) == 64 and is_hex(value)
def is_hex_encoded_block_number(value):
if not is_string(value):
|
elif is_hex_encoded_block_hash(value):
return False
try:
value_as_int = int(value, 16)
except ValueError:
return False
return 0 <= value_as_int < 2**256
def select_method_for_block_identifier(value, if_hash, if_number, if_predefined):
if is_predefined_block_number(value):
return if_predefined
elif isinstance(value, bytes):
return if_hash
elif is_hex_encoded_block_hash(value):
return if_hash
elif is_integer(value) and (0 <= value < 2**256):
return if_number
elif is_hex_encoded_block_number(value):
return if_number
else:
raise ValueError(
"Value did not match any of the recognized block identifiers: {0}".format(value)
)
| return False | conditional_block |
network.py | # -*- coding: utf-8 -*-
"""
Network Plugin
Network usage and connections
"""
import os, netifaces, psutil, time
from pkm import utils, SHAREDIR
from pkm.decorators import never_raise, threaded_method
from pkm.plugin import BasePlugin, BaseConfig
from pkm.filters import register_filter
NAME = 'Network'
DEFAULT_IGNORES = 'lxc tun'
class | (BasePlugin):
DEFAULT_INTERVAL = 1
@threaded_method
def enable(self):
self.nics = {}
self.ignores = self.pkmeter.config.get(self.namespace, 'ignores', '')
self.ignores = list(filter(None, self.ignores.split(' ')))
super(Plugin, self).enable()
@never_raise
def update(self):
for iface, newio in psutil.net_io_counters(True).items():
if not iface.startswith('lo'):
netinfo = netifaces.ifaddresses(iface)
if netinfo.get(netifaces.AF_INET) and not self._is_ignored(iface):
newio = self._net_io_counters(newio)
newio['iface'] = iface
newio.update(netinfo[netifaces.AF_INET][0])
self._deltas(self.nics.get(iface,{}), newio)
self.nics[iface] = newio
elif iface in self.nics:
del self.nics[iface]
self.data['nics'] = sorted(self.nics.values(), key=lambda n:n['iface'])
self.data['total'] = self._deltas(self.data.get('total',{}), self._net_io_counters())
super(Plugin, self).update()
def _is_ignored(self, iface):
if self.ignores:
for ignore in self.ignores:
if iface.startswith(ignore):
return True
return False
def _net_io_counters(self, io=None):
io = io or psutil.net_io_counters()
return {
'bytes_sent': io.bytes_sent,
'bytes_recv': io.bytes_recv,
'packets_sent': io.packets_sent,
'packets_recv': io.packets_recv,
'errin': io.errin,
'errout': io.errout,
'dropin': io.dropin,
'dropout': io.dropout,
}
def _deltas(self, previo, newio):
now = time.time()
tdelta = now - previo.get('updated',0)
for key in ['bytes_sent', 'bytes_recv']:
newio['%s_per_sec' % key] = int((newio[key] - previo.get(key,0)) / tdelta)
newio['updated'] = now
return newio
class Config(BaseConfig):
TEMPLATE = os.path.join(SHAREDIR, 'templates', 'network_config.html')
FIELDS = utils.Bunch(BaseConfig.FIELDS,
ignores = {'default':DEFAULT_IGNORES}
)
@register_filter()
def network_friendly_iface(iface):
iface = iface.replace('eth', 'Ethernet ')
iface = iface.replace('wlan', 'Wireless ')
iface = iface.replace(' 0', '')
return iface
| Plugin | identifier_name |
network.py | # -*- coding: utf-8 -*-
"""
Network Plugin
Network usage and connections
"""
import os, netifaces, psutil, time
from pkm import utils, SHAREDIR
from pkm.decorators import never_raise, threaded_method
from pkm.plugin import BasePlugin, BaseConfig
from pkm.filters import register_filter
NAME = 'Network'
DEFAULT_IGNORES = 'lxc tun'
class Plugin(BasePlugin):
DEFAULT_INTERVAL = 1
@threaded_method
def enable(self):
self.nics = {}
self.ignores = self.pkmeter.config.get(self.namespace, 'ignores', '')
self.ignores = list(filter(None, self.ignores.split(' ')))
super(Plugin, self).enable()
@never_raise
def update(self):
for iface, newio in psutil.net_io_counters(True).items():
if not iface.startswith('lo'):
netinfo = netifaces.ifaddresses(iface)
if netinfo.get(netifaces.AF_INET) and not self._is_ignored(iface):
newio = self._net_io_counters(newio)
newio['iface'] = iface
newio.update(netinfo[netifaces.AF_INET][0])
self._deltas(self.nics.get(iface,{}), newio)
self.nics[iface] = newio
elif iface in self.nics:
del self.nics[iface]
self.data['nics'] = sorted(self.nics.values(), key=lambda n:n['iface'])
self.data['total'] = self._deltas(self.data.get('total',{}), self._net_io_counters())
super(Plugin, self).update()
def _is_ignored(self, iface):
if self.ignores:
for ignore in self.ignores:
|
return False
def _net_io_counters(self, io=None):
io = io or psutil.net_io_counters()
return {
'bytes_sent': io.bytes_sent,
'bytes_recv': io.bytes_recv,
'packets_sent': io.packets_sent,
'packets_recv': io.packets_recv,
'errin': io.errin,
'errout': io.errout,
'dropin': io.dropin,
'dropout': io.dropout,
}
def _deltas(self, previo, newio):
now = time.time()
tdelta = now - previo.get('updated',0)
for key in ['bytes_sent', 'bytes_recv']:
newio['%s_per_sec' % key] = int((newio[key] - previo.get(key,0)) / tdelta)
newio['updated'] = now
return newio
class Config(BaseConfig):
TEMPLATE = os.path.join(SHAREDIR, 'templates', 'network_config.html')
FIELDS = utils.Bunch(BaseConfig.FIELDS,
ignores = {'default':DEFAULT_IGNORES}
)
@register_filter()
def network_friendly_iface(iface):
iface = iface.replace('eth', 'Ethernet ')
iface = iface.replace('wlan', 'Wireless ')
iface = iface.replace(' 0', '')
return iface
| if iface.startswith(ignore):
return True | conditional_block |
network.py | # -*- coding: utf-8 -*-
"""
Network Plugin
Network usage and connections
"""
import os, netifaces, psutil, time
from pkm import utils, SHAREDIR
from pkm.decorators import never_raise, threaded_method
from pkm.plugin import BasePlugin, BaseConfig
from pkm.filters import register_filter
NAME = 'Network'
DEFAULT_IGNORES = 'lxc tun'
class Plugin(BasePlugin):
DEFAULT_INTERVAL = 1
@threaded_method
def enable(self):
self.nics = {}
self.ignores = self.pkmeter.config.get(self.namespace, 'ignores', '')
self.ignores = list(filter(None, self.ignores.split(' ')))
super(Plugin, self).enable()
@never_raise
def update(self):
|
def _is_ignored(self, iface):
if self.ignores:
for ignore in self.ignores:
if iface.startswith(ignore):
return True
return False
def _net_io_counters(self, io=None):
io = io or psutil.net_io_counters()
return {
'bytes_sent': io.bytes_sent,
'bytes_recv': io.bytes_recv,
'packets_sent': io.packets_sent,
'packets_recv': io.packets_recv,
'errin': io.errin,
'errout': io.errout,
'dropin': io.dropin,
'dropout': io.dropout,
}
def _deltas(self, previo, newio):
now = time.time()
tdelta = now - previo.get('updated',0)
for key in ['bytes_sent', 'bytes_recv']:
newio['%s_per_sec' % key] = int((newio[key] - previo.get(key,0)) / tdelta)
newio['updated'] = now
return newio
class Config(BaseConfig):
TEMPLATE = os.path.join(SHAREDIR, 'templates', 'network_config.html')
FIELDS = utils.Bunch(BaseConfig.FIELDS,
ignores = {'default':DEFAULT_IGNORES}
)
@register_filter()
def network_friendly_iface(iface):
iface = iface.replace('eth', 'Ethernet ')
iface = iface.replace('wlan', 'Wireless ')
iface = iface.replace(' 0', '')
return iface
| for iface, newio in psutil.net_io_counters(True).items():
if not iface.startswith('lo'):
netinfo = netifaces.ifaddresses(iface)
if netinfo.get(netifaces.AF_INET) and not self._is_ignored(iface):
newio = self._net_io_counters(newio)
newio['iface'] = iface
newio.update(netinfo[netifaces.AF_INET][0])
self._deltas(self.nics.get(iface,{}), newio)
self.nics[iface] = newio
elif iface in self.nics:
del self.nics[iface]
self.data['nics'] = sorted(self.nics.values(), key=lambda n:n['iface'])
self.data['total'] = self._deltas(self.data.get('total',{}), self._net_io_counters())
super(Plugin, self).update() | identifier_body |
network.py | # -*- coding: utf-8 -*-
"""
Network Plugin
Network usage and connections
"""
import os, netifaces, psutil, time
from pkm import utils, SHAREDIR
from pkm.decorators import never_raise, threaded_method
from pkm.plugin import BasePlugin, BaseConfig
from pkm.filters import register_filter
NAME = 'Network'
DEFAULT_IGNORES = 'lxc tun'
class Plugin(BasePlugin):
DEFAULT_INTERVAL = 1
@threaded_method
def enable(self):
self.nics = {}
self.ignores = self.pkmeter.config.get(self.namespace, 'ignores', '')
self.ignores = list(filter(None, self.ignores.split(' ')))
super(Plugin, self).enable()
@never_raise
def update(self):
for iface, newio in psutil.net_io_counters(True).items():
if not iface.startswith('lo'):
netinfo = netifaces.ifaddresses(iface)
if netinfo.get(netifaces.AF_INET) and not self._is_ignored(iface):
newio = self._net_io_counters(newio)
newio['iface'] = iface
newio.update(netinfo[netifaces.AF_INET][0])
self._deltas(self.nics.get(iface,{}), newio)
self.nics[iface] = newio
elif iface in self.nics:
del self.nics[iface]
self.data['nics'] = sorted(self.nics.values(), key=lambda n:n['iface'])
self.data['total'] = self._deltas(self.data.get('total',{}), self._net_io_counters())
super(Plugin, self).update()
def _is_ignored(self, iface):
if self.ignores:
for ignore in self.ignores:
if iface.startswith(ignore):
return True
return False
def _net_io_counters(self, io=None):
io = io or psutil.net_io_counters()
return {
'bytes_sent': io.bytes_sent,
'bytes_recv': io.bytes_recv,
'packets_sent': io.packets_sent, | 'errin': io.errin,
'errout': io.errout,
'dropin': io.dropin,
'dropout': io.dropout,
}
def _deltas(self, previo, newio):
now = time.time()
tdelta = now - previo.get('updated',0)
for key in ['bytes_sent', 'bytes_recv']:
newio['%s_per_sec' % key] = int((newio[key] - previo.get(key,0)) / tdelta)
newio['updated'] = now
return newio
class Config(BaseConfig):
TEMPLATE = os.path.join(SHAREDIR, 'templates', 'network_config.html')
FIELDS = utils.Bunch(BaseConfig.FIELDS,
ignores = {'default':DEFAULT_IGNORES}
)
@register_filter()
def network_friendly_iface(iface):
iface = iface.replace('eth', 'Ethernet ')
iface = iface.replace('wlan', 'Wireless ')
iface = iface.replace(' 0', '')
return iface | 'packets_recv': io.packets_recv, | random_line_split |
show_neighbors.py | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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.
"""
Show CDP neighbors using SNMP.
"""
import sys
from pycopia.Devices import Discovery
def main(argv):
host = argv[1]
community = argv[2]
dev = Discovery.get_manager(host, community)
Discovery.show_neighbors(dev) |
main(sys.argv) | random_line_split | |
show_neighbors.py | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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.
"""
Show CDP neighbors using SNMP.
"""
import sys
from pycopia.Devices import Discovery
def | (argv):
host = argv[1]
community = argv[2]
dev = Discovery.get_manager(host, community)
Discovery.show_neighbors(dev)
main(sys.argv)
| main | identifier_name |
show_neighbors.py | #!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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.
"""
Show CDP neighbors using SNMP.
"""
import sys
from pycopia.Devices import Discovery
def main(argv):
|
main(sys.argv)
| host = argv[1]
community = argv[2]
dev = Discovery.get_manager(host, community)
Discovery.show_neighbors(dev) | identifier_body |
ActivityIndicatorExample.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
'use strict';
import type {Node} from 'React';
import {ActivityIndicator, StyleSheet, View} from 'react-native';
import React, {Component} from 'react';
type State = {|animating: boolean|};
type Props = $ReadOnly<{||}>;
type Timer = TimeoutID;
class | extends Component<Props, State> {
_timer: Timer;
constructor(props: Props) {
super(props);
this.state = {
animating: true,
};
}
componentDidMount() {
this.setToggleTimeout();
}
componentWillUnmount() {
clearTimeout(this._timer);
}
setToggleTimeout() {
this._timer = setTimeout(() => {
this.setState({animating: !this.state.animating});
this.setToggleTimeout();
}, 2000);
}
render(): Node {
return (
<ActivityIndicator
animating={this.state.animating}
style={[styles.centering, {height: 80}]}
size="large"
/>
);
}
}
const styles = StyleSheet.create({
centering: {
alignItems: 'center',
justifyContent: 'center',
padding: 8,
},
gray: {
backgroundColor: '#cccccc',
},
horizontal: {
flexDirection: 'row',
justifyContent: 'space-around',
padding: 8,
},
});
exports.displayName = (undefined: ?string);
exports.category = 'UI';
exports.framework = 'React';
exports.title = 'ActivityIndicator';
exports.documentationURL = 'https://reactnative.dev/docs/activityindicator';
exports.description = 'Animated loading indicators.';
exports.examples = [
{
title: 'Default (small, white)',
render(): Node {
return (
<ActivityIndicator
style={[styles.centering, styles.gray]}
color="white"
/>
);
},
},
{
title: 'Gray',
render(): Node {
return (
<View>
<ActivityIndicator style={[styles.centering]} />
<ActivityIndicator style={[styles.centering, styles.gray]} />
</View>
);
},
},
{
title: 'Custom colors',
render(): Node {
return (
<View style={styles.horizontal}>
<ActivityIndicator color="#0000ff" />
<ActivityIndicator color="#aa00aa" />
<ActivityIndicator color="#aa3300" />
<ActivityIndicator color="#00aa00" />
</View>
);
},
},
{
title: 'Large',
render(): Node {
return (
<ActivityIndicator
style={[styles.centering, styles.gray]}
size="large"
color="white"
/>
);
},
},
{
title: 'Large, custom colors',
render(): Node {
return (
<View style={styles.horizontal}>
<ActivityIndicator size="large" color="#0000ff" />
<ActivityIndicator size="large" color="#aa00aa" />
<ActivityIndicator size="large" color="#aa3300" />
<ActivityIndicator size="large" color="#00aa00" />
</View>
);
},
},
{
title: 'Start/stop',
render(): Node {
return <ToggleAnimatingActivityIndicator />;
},
},
{
title: 'Custom size',
render(): Node {
return (
<ActivityIndicator
style={[styles.centering, {transform: [{scale: 1.5}]}]}
size="large"
/>
);
},
},
{
platform: 'android',
title: 'Custom size (size: 75)',
render(): Node {
return <ActivityIndicator style={styles.centering} size={75} />;
},
},
];
| ToggleAnimatingActivityIndicator | identifier_name |
ActivityIndicatorExample.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
'use strict';
import type {Node} from 'React';
import {ActivityIndicator, StyleSheet, View} from 'react-native';
import React, {Component} from 'react';
type State = {|animating: boolean|};
type Props = $ReadOnly<{||}>;
type Timer = TimeoutID;
class ToggleAnimatingActivityIndicator extends Component<Props, State> {
_timer: Timer;
constructor(props: Props) {
super(props);
this.state = {
animating: true,
};
}
componentDidMount() {
this.setToggleTimeout();
}
componentWillUnmount() {
clearTimeout(this._timer);
}
setToggleTimeout() {
this._timer = setTimeout(() => {
this.setState({animating: !this.state.animating});
this.setToggleTimeout();
}, 2000);
}
render(): Node {
return (
<ActivityIndicator
animating={this.state.animating}
style={[styles.centering, {height: 80}]}
size="large"
/>
); | }
}
const styles = StyleSheet.create({
centering: {
alignItems: 'center',
justifyContent: 'center',
padding: 8,
},
gray: {
backgroundColor: '#cccccc',
},
horizontal: {
flexDirection: 'row',
justifyContent: 'space-around',
padding: 8,
},
});
exports.displayName = (undefined: ?string);
exports.category = 'UI';
exports.framework = 'React';
exports.title = 'ActivityIndicator';
exports.documentationURL = 'https://reactnative.dev/docs/activityindicator';
exports.description = 'Animated loading indicators.';
exports.examples = [
{
title: 'Default (small, white)',
render(): Node {
return (
<ActivityIndicator
style={[styles.centering, styles.gray]}
color="white"
/>
);
},
},
{
title: 'Gray',
render(): Node {
return (
<View>
<ActivityIndicator style={[styles.centering]} />
<ActivityIndicator style={[styles.centering, styles.gray]} />
</View>
);
},
},
{
title: 'Custom colors',
render(): Node {
return (
<View style={styles.horizontal}>
<ActivityIndicator color="#0000ff" />
<ActivityIndicator color="#aa00aa" />
<ActivityIndicator color="#aa3300" />
<ActivityIndicator color="#00aa00" />
</View>
);
},
},
{
title: 'Large',
render(): Node {
return (
<ActivityIndicator
style={[styles.centering, styles.gray]}
size="large"
color="white"
/>
);
},
},
{
title: 'Large, custom colors',
render(): Node {
return (
<View style={styles.horizontal}>
<ActivityIndicator size="large" color="#0000ff" />
<ActivityIndicator size="large" color="#aa00aa" />
<ActivityIndicator size="large" color="#aa3300" />
<ActivityIndicator size="large" color="#00aa00" />
</View>
);
},
},
{
title: 'Start/stop',
render(): Node {
return <ToggleAnimatingActivityIndicator />;
},
},
{
title: 'Custom size',
render(): Node {
return (
<ActivityIndicator
style={[styles.centering, {transform: [{scale: 1.5}]}]}
size="large"
/>
);
},
},
{
platform: 'android',
title: 'Custom size (size: 75)',
render(): Node {
return <ActivityIndicator style={styles.centering} size={75} />;
},
},
]; | random_line_split | |
move_.rs |
use crate::direction::Direction;
/// This structure contains everything needed to do or undo a Sokoban move.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Move {
/// Was a crate moved?
pub moves_crate: bool,
/// Where was the move directed?
pub direction: Direction,
}
impl Move {
pub fn new(direction: Direction, moves_crate: bool) -> Self {
Move {
moves_crate,
direction,
}
}
/// Describe a move using one character signifying its direction. The character is upper case
/// if and only if `self.moves_crate` is true.
pub fn to_char(&self) -> char {
let mut c = match self.direction {
Direction::Left => 'l',
Direction::Right => 'r',
Direction::Up => 'u',
Direction::Down => 'd',
};
if self.moves_crate {
c.make_ascii_uppercase();
}
c
}
}
/// Parse a string representation of moves.
pub fn parse(s: &str) -> Result<Vec<Move>, char> {
s.chars().map(Move::try_from).collect::<Result<Vec<_>, _>>()
}
impl fmt::Display for Move {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.to_char())
}
}
impl TryFrom<char> for Move {
type Error = char;
fn try_from(c: char) -> Result<Move, char> {
use crate::Direction::*;
let dir = match c {
'l' | 'L' => Left,
'r' | 'R' => Right,
'u' | 'U' => Up,
'd' | 'D' => Down,
_ => return Err(c),
};
let push = c.is_ascii_uppercase();
Ok(Move::new(dir, push))
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn to_from() {
for &dir in &crate::direction::DIRECTIONS {
let mv = Move::new(dir, true);
assert_eq!(Ok(mv.clone()), Move::try_from(mv.to_char()));
let mv = Move::new(dir, false);
assert_eq!(Ok(mv.clone()), Move::try_from(mv.to_char()));
}
}
#[test]
fn invalid_char() {
for chr in "abcefghijkmnopqstvwxyz".chars() {
assert!(Move::try_from(chr).is_err());
}
}
#[test]
fn parse_str() {
let s = "UldrdddDddlLrrRRuLulLLUUdrdlduUDLR";
let moves = parse(s).unwrap();
let s2: String = moves.into_iter().map(|x| x.to_char()).collect();
assert_eq!(s, s2);
}
} | use std::convert::TryFrom;
use std::fmt; | random_line_split | |
move_.rs | use std::convert::TryFrom;
use std::fmt;
use crate::direction::Direction;
/// This structure contains everything needed to do or undo a Sokoban move.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Move {
/// Was a crate moved?
pub moves_crate: bool,
/// Where was the move directed?
pub direction: Direction,
}
impl Move {
pub fn new(direction: Direction, moves_crate: bool) -> Self {
Move {
moves_crate,
direction,
}
}
/// Describe a move using one character signifying its direction. The character is upper case
/// if and only if `self.moves_crate` is true.
pub fn to_char(&self) -> char {
let mut c = match self.direction {
Direction::Left => 'l',
Direction::Right => 'r',
Direction::Up => 'u',
Direction::Down => 'd',
};
if self.moves_crate |
c
}
}
/// Parse a string representation of moves.
pub fn parse(s: &str) -> Result<Vec<Move>, char> {
s.chars().map(Move::try_from).collect::<Result<Vec<_>, _>>()
}
impl fmt::Display for Move {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.to_char())
}
}
impl TryFrom<char> for Move {
type Error = char;
fn try_from(c: char) -> Result<Move, char> {
use crate::Direction::*;
let dir = match c {
'l' | 'L' => Left,
'r' | 'R' => Right,
'u' | 'U' => Up,
'd' | 'D' => Down,
_ => return Err(c),
};
let push = c.is_ascii_uppercase();
Ok(Move::new(dir, push))
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn to_from() {
for &dir in &crate::direction::DIRECTIONS {
let mv = Move::new(dir, true);
assert_eq!(Ok(mv.clone()), Move::try_from(mv.to_char()));
let mv = Move::new(dir, false);
assert_eq!(Ok(mv.clone()), Move::try_from(mv.to_char()));
}
}
#[test]
fn invalid_char() {
for chr in "abcefghijkmnopqstvwxyz".chars() {
assert!(Move::try_from(chr).is_err());
}
}
#[test]
fn parse_str() {
let s = "UldrdddDddlLrrRRuLulLLUUdrdlduUDLR";
let moves = parse(s).unwrap();
let s2: String = moves.into_iter().map(|x| x.to_char()).collect();
assert_eq!(s, s2);
}
}
| {
c.make_ascii_uppercase();
} | conditional_block |
move_.rs | use std::convert::TryFrom;
use std::fmt;
use crate::direction::Direction;
/// This structure contains everything needed to do or undo a Sokoban move.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Move {
/// Was a crate moved?
pub moves_crate: bool,
/// Where was the move directed?
pub direction: Direction,
}
impl Move {
pub fn new(direction: Direction, moves_crate: bool) -> Self {
Move {
moves_crate,
direction,
}
}
/// Describe a move using one character signifying its direction. The character is upper case
/// if and only if `self.moves_crate` is true.
pub fn | (&self) -> char {
let mut c = match self.direction {
Direction::Left => 'l',
Direction::Right => 'r',
Direction::Up => 'u',
Direction::Down => 'd',
};
if self.moves_crate {
c.make_ascii_uppercase();
}
c
}
}
/// Parse a string representation of moves.
pub fn parse(s: &str) -> Result<Vec<Move>, char> {
s.chars().map(Move::try_from).collect::<Result<Vec<_>, _>>()
}
impl fmt::Display for Move {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.to_char())
}
}
impl TryFrom<char> for Move {
type Error = char;
fn try_from(c: char) -> Result<Move, char> {
use crate::Direction::*;
let dir = match c {
'l' | 'L' => Left,
'r' | 'R' => Right,
'u' | 'U' => Up,
'd' | 'D' => Down,
_ => return Err(c),
};
let push = c.is_ascii_uppercase();
Ok(Move::new(dir, push))
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn to_from() {
for &dir in &crate::direction::DIRECTIONS {
let mv = Move::new(dir, true);
assert_eq!(Ok(mv.clone()), Move::try_from(mv.to_char()));
let mv = Move::new(dir, false);
assert_eq!(Ok(mv.clone()), Move::try_from(mv.to_char()));
}
}
#[test]
fn invalid_char() {
for chr in "abcefghijkmnopqstvwxyz".chars() {
assert!(Move::try_from(chr).is_err());
}
}
#[test]
fn parse_str() {
let s = "UldrdddDddlLrrRRuLulLLUUdrdlduUDLR";
let moves = parse(s).unwrap();
let s2: String = moves.into_iter().map(|x| x.to_char()).collect();
assert_eq!(s, s2);
}
}
| to_char | identifier_name |
move_.rs | use std::convert::TryFrom;
use std::fmt;
use crate::direction::Direction;
/// This structure contains everything needed to do or undo a Sokoban move.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Move {
/// Was a crate moved?
pub moves_crate: bool,
/// Where was the move directed?
pub direction: Direction,
}
impl Move {
pub fn new(direction: Direction, moves_crate: bool) -> Self {
Move {
moves_crate,
direction,
}
}
/// Describe a move using one character signifying its direction. The character is upper case
/// if and only if `self.moves_crate` is true.
pub fn to_char(&self) -> char {
let mut c = match self.direction {
Direction::Left => 'l',
Direction::Right => 'r',
Direction::Up => 'u',
Direction::Down => 'd',
};
if self.moves_crate {
c.make_ascii_uppercase();
}
c
}
}
/// Parse a string representation of moves.
pub fn parse(s: &str) -> Result<Vec<Move>, char> {
s.chars().map(Move::try_from).collect::<Result<Vec<_>, _>>()
}
impl fmt::Display for Move {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result |
}
impl TryFrom<char> for Move {
type Error = char;
fn try_from(c: char) -> Result<Move, char> {
use crate::Direction::*;
let dir = match c {
'l' | 'L' => Left,
'r' | 'R' => Right,
'u' | 'U' => Up,
'd' | 'D' => Down,
_ => return Err(c),
};
let push = c.is_ascii_uppercase();
Ok(Move::new(dir, push))
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn to_from() {
for &dir in &crate::direction::DIRECTIONS {
let mv = Move::new(dir, true);
assert_eq!(Ok(mv.clone()), Move::try_from(mv.to_char()));
let mv = Move::new(dir, false);
assert_eq!(Ok(mv.clone()), Move::try_from(mv.to_char()));
}
}
#[test]
fn invalid_char() {
for chr in "abcefghijkmnopqstvwxyz".chars() {
assert!(Move::try_from(chr).is_err());
}
}
#[test]
fn parse_str() {
let s = "UldrdddDddlLrrRRuLulLLUUdrdlduUDLR";
let moves = parse(s).unwrap();
let s2: String = moves.into_iter().map(|x| x.to_char()).collect();
assert_eq!(s, s2);
}
}
| {
write!(f, "{}", self.to_char())
} | identifier_body |
field_manager_mixin.js | odoo.define('web.FieldManagerMixin', function (require) {
"use strict";
/**
* The FieldManagerMixin is a mixin, designed to do the plumbing between field
* widgets and a basicmodel. Field widgets can be used outside of a view. In
* that case, someone needs to listen to events bubbling up from the widgets and
* calling the correct methods on the model. This is the field_manager's job.
*/
var BasicModel = require('web.BasicModel');
var concurrency = require('web.concurrency');
var FieldManagerMixin = {
custom_events: {
field_changed: '_onFieldChanged',
load: '_onLoad',
mutexify: '_onMutexify',
},
/**
* A FieldManagerMixin can be initialized with an instance of a basicModel.
* If not, it will simply uses its own.
*
* @param {BasicModel} [model]
*/
init: function (model) {
this.model = model || new BasicModel(this);
this.mutex = new concurrency.Mutex();
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* Apply changes by notifying the basic model, then saving the data if
* necessary, and finally, confirming the changes to the UI.
*
* @todo find a way to remove ugly 3rd argument...
*
* @param {string} dataPointID
* @param {Object} changes
* @param {OdooEvent} event
* @returns {Promise} resolves when the change has been done, and the UI
* updated
*/
_applyChanges: function (dataPointID, changes, event) {
var self = this;
var options = _.pick(event.data, 'context', 'doNotSetDirty', 'notifyChange', 'viewType', 'allowWarning');
return this.model.notifyChanges(dataPointID, changes, options)
.then(function (result) {
if (event.data.force_save) {
return self.model.save(dataPointID).then(function () {
return self._confirmSave(dataPointID);
}).guardedCatch(function () {
return self._rejectSave(dataPointID);
});
} else if (options.notifyChange !== false) {
return self._confirmChange(dataPointID, result, event);
}
});
},
/**
* This method will be called whenever a field value has changed (and has
* been confirmed by the model).
*
* @abstract
* @param {string} id basicModel Id for the changed record
* @param {string[]} fields the fields (names) that have been changed
* @param {OdooEvent} event the event that triggered the change
* @returns {Promise}
*/
_confirmChange: function (id, fields, event) {
return Promise.resolve();
},
/**
* This method will be called whenever a save has been triggered by a change
* in some controlled field value. For example, when a priority widget is
* being changed in a readonly form.
*
* @see _onFieldChanged
* @abstract
* @param {string} id The basicModel ID for the saved record
* @returns {Promise}
*/
_confirmSave: function (id) {
return Promise.resolve();
},
/**
* This method will be called whenever a save has been triggered by a change
* and has failed. For example, when a statusbar button is clicked in a
* readonly form view.
*
* @abstract
* @private
* @param {string} id The basicModel ID for the saved record
* @returns {Deferred}
*/
_rejectSave: function (id) {
return Promise.resolve();
},
//--------------------------------------------------------------------------
// Handlers
//--------------------------------------------------------------------------
/**
* This is the main job of the FMM: deciding what to do when a controlled
* field changes. Most of the time, it notifies the model that a change
* just occurred, then confirm the change.
*
* @param {OdooEvent} event
*/
_onFieldChanged: function (event) {
// in case of field changed in relational record (e.g. in the form view
// of a one2many subrecord), the field_changed event must be stopped as
// soon as is it handled by a field_manager (i.e. the one of the
// subrecord's form view), otherwise it bubbles up to the main form view
// but its model doesn't have any data related to the given dataPointID
event.stopPropagation();
return this._applyChanges(event.data.dataPointID, event.data.changes, event)
.then(event.data.onSuccess || function () {})
.guardedCatch(event.data.onFailure || function () {});
},
/**
* Some widgets need to trigger a reload of their data. For example, a
* one2many with a pager needs to be able to fetch the next page. To do | *
* @param {OdooEvent} event
* @param {number} [event.data.limit]
* @param {number} [event.data.offset]
* @param {function} [event.data.on_success] callback
*/
_onLoad: function (event) {
var self = this;
event.stopPropagation(); // prevent other field managers from handling this request
var data = event.data;
if (!data.on_success) { return; }
var params = {};
if ('limit' in data) {
params.limit = data.limit;
}
if ('offset' in data) {
params.offset = data.offset;
}
this.mutex.exec(function () {
return self.model.reload(data.id, params).then(function (db_id) {
data.on_success(self.model.get(db_id));
});
});
},
/**
* @private
* @param {OdooEvent} ev
* @param {function} ev.data.action the function to execute in the mutex
*/
_onMutexify: function (ev) {
ev.stopPropagation(); // prevent other field managers from handling this request
this.mutex.exec(ev.data.action);
},
};
return FieldManagerMixin;
}); | * that, it can trigger a load event. This will then ask the model to
* actually reload the data, then call the on_success callback. | random_line_split |
field_manager_mixin.js | odoo.define('web.FieldManagerMixin', function (require) {
"use strict";
/**
* The FieldManagerMixin is a mixin, designed to do the plumbing between field
* widgets and a basicmodel. Field widgets can be used outside of a view. In
* that case, someone needs to listen to events bubbling up from the widgets and
* calling the correct methods on the model. This is the field_manager's job.
*/
var BasicModel = require('web.BasicModel');
var concurrency = require('web.concurrency');
var FieldManagerMixin = {
custom_events: {
field_changed: '_onFieldChanged',
load: '_onLoad',
mutexify: '_onMutexify',
},
/**
* A FieldManagerMixin can be initialized with an instance of a basicModel.
* If not, it will simply uses its own.
*
* @param {BasicModel} [model]
*/
init: function (model) {
this.model = model || new BasicModel(this);
this.mutex = new concurrency.Mutex();
},
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* Apply changes by notifying the basic model, then saving the data if
* necessary, and finally, confirming the changes to the UI.
*
* @todo find a way to remove ugly 3rd argument...
*
* @param {string} dataPointID
* @param {Object} changes
* @param {OdooEvent} event
* @returns {Promise} resolves when the change has been done, and the UI
* updated
*/
_applyChanges: function (dataPointID, changes, event) {
var self = this;
var options = _.pick(event.data, 'context', 'doNotSetDirty', 'notifyChange', 'viewType', 'allowWarning');
return this.model.notifyChanges(dataPointID, changes, options)
.then(function (result) {
if (event.data.force_save) {
return self.model.save(dataPointID).then(function () {
return self._confirmSave(dataPointID);
}).guardedCatch(function () {
return self._rejectSave(dataPointID);
});
} else if (options.notifyChange !== false) |
});
},
/**
* This method will be called whenever a field value has changed (and has
* been confirmed by the model).
*
* @abstract
* @param {string} id basicModel Id for the changed record
* @param {string[]} fields the fields (names) that have been changed
* @param {OdooEvent} event the event that triggered the change
* @returns {Promise}
*/
_confirmChange: function (id, fields, event) {
return Promise.resolve();
},
/**
* This method will be called whenever a save has been triggered by a change
* in some controlled field value. For example, when a priority widget is
* being changed in a readonly form.
*
* @see _onFieldChanged
* @abstract
* @param {string} id The basicModel ID for the saved record
* @returns {Promise}
*/
_confirmSave: function (id) {
return Promise.resolve();
},
/**
* This method will be called whenever a save has been triggered by a change
* and has failed. For example, when a statusbar button is clicked in a
* readonly form view.
*
* @abstract
* @private
* @param {string} id The basicModel ID for the saved record
* @returns {Deferred}
*/
_rejectSave: function (id) {
return Promise.resolve();
},
//--------------------------------------------------------------------------
// Handlers
//--------------------------------------------------------------------------
/**
* This is the main job of the FMM: deciding what to do when a controlled
* field changes. Most of the time, it notifies the model that a change
* just occurred, then confirm the change.
*
* @param {OdooEvent} event
*/
_onFieldChanged: function (event) {
// in case of field changed in relational record (e.g. in the form view
// of a one2many subrecord), the field_changed event must be stopped as
// soon as is it handled by a field_manager (i.e. the one of the
// subrecord's form view), otherwise it bubbles up to the main form view
// but its model doesn't have any data related to the given dataPointID
event.stopPropagation();
return this._applyChanges(event.data.dataPointID, event.data.changes, event)
.then(event.data.onSuccess || function () {})
.guardedCatch(event.data.onFailure || function () {});
},
/**
* Some widgets need to trigger a reload of their data. For example, a
* one2many with a pager needs to be able to fetch the next page. To do
* that, it can trigger a load event. This will then ask the model to
* actually reload the data, then call the on_success callback.
*
* @param {OdooEvent} event
* @param {number} [event.data.limit]
* @param {number} [event.data.offset]
* @param {function} [event.data.on_success] callback
*/
_onLoad: function (event) {
var self = this;
event.stopPropagation(); // prevent other field managers from handling this request
var data = event.data;
if (!data.on_success) { return; }
var params = {};
if ('limit' in data) {
params.limit = data.limit;
}
if ('offset' in data) {
params.offset = data.offset;
}
this.mutex.exec(function () {
return self.model.reload(data.id, params).then(function (db_id) {
data.on_success(self.model.get(db_id));
});
});
},
/**
* @private
* @param {OdooEvent} ev
* @param {function} ev.data.action the function to execute in the mutex
*/
_onMutexify: function (ev) {
ev.stopPropagation(); // prevent other field managers from handling this request
this.mutex.exec(ev.data.action);
},
};
return FieldManagerMixin;
});
| {
return self._confirmChange(dataPointID, result, event);
} | conditional_block |
actionManager.ts | import "reflect-metadata";
export const symbolRobotAction = Symbol("robotAction");
export function robotAction(name: string, ...args: string[]) {
return (target: any, propertyKey: string, descriptor: any) => {
if (descriptor.value) {
ActionManager.instance.registerClass(target.constructor);
let types = Reflect.getMetadata("design:paramtypes", target, propertyKey);
ActionManager.instance.register(descriptor.value, target.constructor.name, name, args, types);
}
};
}
export interface FunctionDefinion { | className: string
func: Function
chineseName: string
chineseArgs: string[]
argTypes: any
}
export default class ActionManager {
private static readonly INSTANCE = new ActionManager();
public static get instance() {
return this.INSTANCE;
}
constructor() {
}
private _classMap = new Map<string, object>();
private _functionMap = new Map<string, FunctionDefinion>();
public registerClass(cons: FunctionConstructor) {
if (this._classMap.has(cons.name)) return;
this._classMap.set(cons.name, new cons());
console.log("class registered", cons.name);
console.log(cons);
}
public register(func: Function, classname: string, name: string, args: string[], types: any) {
this._functionMap.set(name, {
className: classname,
func: func,
chineseName: name,
chineseArgs: args,
argTypes: types
});
console.log("function registered", name, args, types);
}
public getAction(name: string) {
return this._functionMap.get(name);
}
public getThisObj(name: string) {
return this._classMap.get(name);
}
}
export class Email {
addr: string;
server: string;
constructor(str: string) {
let data = str.split('@');
this.addr = data[0];
this.server = data[1];
}
toString() {
return this.addr + '@' + this.server;
}
}
export class Path {
path: string;
type!: string; // dir, file, link
exist: boolean = false;
constructor(str: string) {
this.path = str;
}
}
export class Password {
data: string;
constructor(str: string) {
this.data = str;
}
} | random_line_split | |
actionManager.ts | import "reflect-metadata";
export const symbolRobotAction = Symbol("robotAction");
export function robotAction(name: string, ...args: string[]) {
return (target: any, propertyKey: string, descriptor: any) => {
if (descriptor.value) {
ActionManager.instance.registerClass(target.constructor);
let types = Reflect.getMetadata("design:paramtypes", target, propertyKey);
ActionManager.instance.register(descriptor.value, target.constructor.name, name, args, types);
}
};
}
export interface FunctionDefinion {
className: string
func: Function
chineseName: string
chineseArgs: string[]
argTypes: any
}
export default class ActionManager {
private static readonly INSTANCE = new ActionManager();
public static get instance() {
return this.INSTANCE;
}
constructor() {
}
private _classMap = new Map<string, object>();
private _functionMap = new Map<string, FunctionDefinion>();
public registerClass(cons: FunctionConstructor) {
if (this._classMap.has(cons.name)) return;
this._classMap.set(cons.name, new cons());
console.log("class registered", cons.name);
console.log(cons);
}
public register(func: Function, classname: string, name: string, args: string[], types: any) {
this._functionMap.set(name, {
className: classname,
func: func,
chineseName: name,
chineseArgs: args,
argTypes: types
});
console.log("function registered", name, args, types);
}
public | (name: string) {
return this._functionMap.get(name);
}
public getThisObj(name: string) {
return this._classMap.get(name);
}
}
export class Email {
addr: string;
server: string;
constructor(str: string) {
let data = str.split('@');
this.addr = data[0];
this.server = data[1];
}
toString() {
return this.addr + '@' + this.server;
}
}
export class Path {
path: string;
type!: string; // dir, file, link
exist: boolean = false;
constructor(str: string) {
this.path = str;
}
}
export class Password {
data: string;
constructor(str: string) {
this.data = str;
}
} | getAction | identifier_name |
sitemaps.py | '''
Classes to generate the Example.com sitemap based on django.contrib.sitemaps.
'''
from django.contrib.sitemaps import Sitemap
from django.utils.datetime_safe import datetime
from canvas.models import Category, Visibility, Comment
from django.core import urlresolvers
from django.conf import settings
import urlparse
from canvas import util
class BaseSitemap(Sitemap):
def get_urls(self, page=1, site=None):
""" A hack so that we don't have to use django.sites
"""
urls = super(BaseSitemap, self).get_urls(page, site)
if site.domain != settings.DOMAIN:
|
return urls
class Categories(BaseSitemap):
# Crawling category pages is important.
priority = 1.0
def items(self):
""" Returns a list of categories that are visibile.
"""
return Category.objects.filter(visibility=Visibility.PUBLIC)
def last_mod(self, category):
"""
The last time this URL has changed. For categories, we use the current time because groups get posted to all
the time.
@TODO: Figure out a way to get a more precise last_mod time
"""
return datetime.now()
def location(self, category):
return util.make_absolute_url(category.get_absolute_url(), "http:")
#class Threads(BaseSitemap):
# priority = 0.7
#
# def items(self):
# threads = Comment.objects.filter(parent_comment=None, visibility=Visibility.PUBLIC).order(score)
class StaticSitemap(BaseSitemap):
"""
Generates a sitemp for the static/direct_to_template pages.
"""
priority = 0.5
url_patterns = []
def __init__(self, url_patterns):
self.url_patterns = url_patterns
def items(self):
return self.url_patterns
def changefreq(self, obj):
return 'monthly'
def location(self, regex_url):
relative_url = regex_url.regex.pattern.replace("^", "/").replace("$", "")
return util.make_absolute_url(relative_url, "http")
| for url in urls:
url['location'] = url['location'].replace("http://"+site.domain, "", 1) | conditional_block |
sitemaps.py | '''
Classes to generate the Example.com sitemap based on django.contrib.sitemaps.
'''
from django.contrib.sitemaps import Sitemap
from django.utils.datetime_safe import datetime
from canvas.models import Category, Visibility, Comment
from django.core import urlresolvers
from django.conf import settings
import urlparse
from canvas import util
class BaseSitemap(Sitemap):
def get_urls(self, page=1, site=None):
""" A hack so that we don't have to use django.sites
"""
urls = super(BaseSitemap, self).get_urls(page, site)
if site.domain != settings.DOMAIN:
for url in urls:
url['location'] = url['location'].replace("http://"+site.domain, "", 1)
return urls
class Categories(BaseSitemap): | priority = 1.0
def items(self):
""" Returns a list of categories that are visibile.
"""
return Category.objects.filter(visibility=Visibility.PUBLIC)
def last_mod(self, category):
"""
The last time this URL has changed. For categories, we use the current time because groups get posted to all
the time.
@TODO: Figure out a way to get a more precise last_mod time
"""
return datetime.now()
def location(self, category):
return util.make_absolute_url(category.get_absolute_url(), "http:")
#class Threads(BaseSitemap):
# priority = 0.7
#
# def items(self):
# threads = Comment.objects.filter(parent_comment=None, visibility=Visibility.PUBLIC).order(score)
class StaticSitemap(BaseSitemap):
"""
Generates a sitemp for the static/direct_to_template pages.
"""
priority = 0.5
url_patterns = []
def __init__(self, url_patterns):
self.url_patterns = url_patterns
def items(self):
return self.url_patterns
def changefreq(self, obj):
return 'monthly'
def location(self, regex_url):
relative_url = regex_url.regex.pattern.replace("^", "/").replace("$", "")
return util.make_absolute_url(relative_url, "http") | # Crawling category pages is important. | random_line_split |
sitemaps.py | '''
Classes to generate the Example.com sitemap based on django.contrib.sitemaps.
'''
from django.contrib.sitemaps import Sitemap
from django.utils.datetime_safe import datetime
from canvas.models import Category, Visibility, Comment
from django.core import urlresolvers
from django.conf import settings
import urlparse
from canvas import util
class BaseSitemap(Sitemap):
def get_urls(self, page=1, site=None):
""" A hack so that we don't have to use django.sites
"""
urls = super(BaseSitemap, self).get_urls(page, site)
if site.domain != settings.DOMAIN:
for url in urls:
url['location'] = url['location'].replace("http://"+site.domain, "", 1)
return urls
class Categories(BaseSitemap):
# Crawling category pages is important.
priority = 1.0
def items(self):
|
def last_mod(self, category):
"""
The last time this URL has changed. For categories, we use the current time because groups get posted to all
the time.
@TODO: Figure out a way to get a more precise last_mod time
"""
return datetime.now()
def location(self, category):
return util.make_absolute_url(category.get_absolute_url(), "http:")
#class Threads(BaseSitemap):
# priority = 0.7
#
# def items(self):
# threads = Comment.objects.filter(parent_comment=None, visibility=Visibility.PUBLIC).order(score)
class StaticSitemap(BaseSitemap):
"""
Generates a sitemp for the static/direct_to_template pages.
"""
priority = 0.5
url_patterns = []
def __init__(self, url_patterns):
self.url_patterns = url_patterns
def items(self):
return self.url_patterns
def changefreq(self, obj):
return 'monthly'
def location(self, regex_url):
relative_url = regex_url.regex.pattern.replace("^", "/").replace("$", "")
return util.make_absolute_url(relative_url, "http")
| """ Returns a list of categories that are visibile.
"""
return Category.objects.filter(visibility=Visibility.PUBLIC) | identifier_body |
sitemaps.py | '''
Classes to generate the Example.com sitemap based on django.contrib.sitemaps.
'''
from django.contrib.sitemaps import Sitemap
from django.utils.datetime_safe import datetime
from canvas.models import Category, Visibility, Comment
from django.core import urlresolvers
from django.conf import settings
import urlparse
from canvas import util
class BaseSitemap(Sitemap):
def get_urls(self, page=1, site=None):
""" A hack so that we don't have to use django.sites
"""
urls = super(BaseSitemap, self).get_urls(page, site)
if site.domain != settings.DOMAIN:
for url in urls:
url['location'] = url['location'].replace("http://"+site.domain, "", 1)
return urls
class | (BaseSitemap):
# Crawling category pages is important.
priority = 1.0
def items(self):
""" Returns a list of categories that are visibile.
"""
return Category.objects.filter(visibility=Visibility.PUBLIC)
def last_mod(self, category):
"""
The last time this URL has changed. For categories, we use the current time because groups get posted to all
the time.
@TODO: Figure out a way to get a more precise last_mod time
"""
return datetime.now()
def location(self, category):
return util.make_absolute_url(category.get_absolute_url(), "http:")
#class Threads(BaseSitemap):
# priority = 0.7
#
# def items(self):
# threads = Comment.objects.filter(parent_comment=None, visibility=Visibility.PUBLIC).order(score)
class StaticSitemap(BaseSitemap):
"""
Generates a sitemp for the static/direct_to_template pages.
"""
priority = 0.5
url_patterns = []
def __init__(self, url_patterns):
self.url_patterns = url_patterns
def items(self):
return self.url_patterns
def changefreq(self, obj):
return 'monthly'
def location(self, regex_url):
relative_url = regex_url.regex.pattern.replace("^", "/").replace("$", "")
return util.make_absolute_url(relative_url, "http")
| Categories | identifier_name |
100_doors.rs | // Implements http://rosettacode.org/wiki/100_doors
use std::num::Float;
use std::iter::Map;
use std::ops::Range;
type DoorIter = Map<Range<u32>, fn(u32) -> DoorState>;
#[derive(Debug, PartialEq)]
enum DoorState { Open, Closed, }
// This is an example of returning an iterator, this allows the caller to
// choose if they want to allocate or just process as a stream.
fn calculate_doors() -> DoorIter {
fn door_status(door_number: u32) -> DoorState {
let x = (door_number as f64).sqrt();
if x == x.round() { DoorState::Open } else { DoorState::Closed }
}
(1u32..101).map(door_status as fn(u32) -> DoorState)
}
#[cfg(not(test))]
fn main() {
let doors = calculate_doors();
for (i, x) in doors.enumerate() { println!("Door {} is {:?}" , i + 1 , x); }
}
#[test]
fn solution() | {
let doors = calculate_doors().collect::<Vec<DoorState>>();
// test that the doors with index corresponding to
// a perfect square are now open
for i in 1..11 {
assert_eq!(doors[i*i - 1], DoorState::Open);
}
} | identifier_body | |
100_doors.rs | // Implements http://rosettacode.org/wiki/100_doors
use std::num::Float;
use std::iter::Map;
use std::ops::Range;
type DoorIter = Map<Range<u32>, fn(u32) -> DoorState>;
#[derive(Debug, PartialEq)]
enum DoorState { Open, Closed, }
// This is an example of returning an iterator, this allows the caller to
// choose if they want to allocate or just process as a stream.
fn calculate_doors() -> DoorIter {
fn door_status(door_number: u32) -> DoorState {
let x = (door_number as f64).sqrt();
if x == x.round() { DoorState::Open } else |
}
(1u32..101).map(door_status as fn(u32) -> DoorState)
}
#[cfg(not(test))]
fn main() {
let doors = calculate_doors();
for (i, x) in doors.enumerate() { println!("Door {} is {:?}" , i + 1 , x); }
}
#[test]
fn solution() {
let doors = calculate_doors().collect::<Vec<DoorState>>();
// test that the doors with index corresponding to
// a perfect square are now open
for i in 1..11 {
assert_eq!(doors[i*i - 1], DoorState::Open);
}
}
| { DoorState::Closed } | conditional_block |
100_doors.rs | // Implements http://rosettacode.org/wiki/100_doors
use std::num::Float;
use std::iter::Map;
use std::ops::Range;
type DoorIter = Map<Range<u32>, fn(u32) -> DoorState>;
#[derive(Debug, PartialEq)]
enum DoorState { Open, Closed, }
// This is an example of returning an iterator, this allows the caller to
// choose if they want to allocate or just process as a stream.
fn | () -> DoorIter {
fn door_status(door_number: u32) -> DoorState {
let x = (door_number as f64).sqrt();
if x == x.round() { DoorState::Open } else { DoorState::Closed }
}
(1u32..101).map(door_status as fn(u32) -> DoorState)
}
#[cfg(not(test))]
fn main() {
let doors = calculate_doors();
for (i, x) in doors.enumerate() { println!("Door {} is {:?}" , i + 1 , x); }
}
#[test]
fn solution() {
let doors = calculate_doors().collect::<Vec<DoorState>>();
// test that the doors with index corresponding to
// a perfect square are now open
for i in 1..11 {
assert_eq!(doors[i*i - 1], DoorState::Open);
}
}
| calculate_doors | identifier_name |
100_doors.rs | // Implements http://rosettacode.org/wiki/100_doors |
#[derive(Debug, PartialEq)]
enum DoorState { Open, Closed, }
// This is an example of returning an iterator, this allows the caller to
// choose if they want to allocate or just process as a stream.
fn calculate_doors() -> DoorIter {
fn door_status(door_number: u32) -> DoorState {
let x = (door_number as f64).sqrt();
if x == x.round() { DoorState::Open } else { DoorState::Closed }
}
(1u32..101).map(door_status as fn(u32) -> DoorState)
}
#[cfg(not(test))]
fn main() {
let doors = calculate_doors();
for (i, x) in doors.enumerate() { println!("Door {} is {:?}" , i + 1 , x); }
}
#[test]
fn solution() {
let doors = calculate_doors().collect::<Vec<DoorState>>();
// test that the doors with index corresponding to
// a perfect square are now open
for i in 1..11 {
assert_eq!(doors[i*i - 1], DoorState::Open);
}
} | use std::num::Float;
use std::iter::Map;
use std::ops::Range;
type DoorIter = Map<Range<u32>, fn(u32) -> DoorState>; | random_line_split |
train_util.py | # Copyright 2022 The DDSP Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Library of training functions."""
import inspect
import json
import os
import time
from absl import logging
from ddsp.training import cloud
import gin
import tensorflow.compat.v2 as tf
# ---------------------- Helper Functions --------------------------------------
def get_strategy(tpu='', cluster_config=''):
"""Create a distribution strategy for running on accelerators.
For CPU, single-GPU, or multi-GPU jobs on a single machine, call this function
without args to return a MirroredStrategy.
For TPU jobs, specify an address to the `tpu` argument.
For multi-machine GPU jobs, specify a `cluster_config` argument of the cluster
configuration.
Args:
tpu: Address of the TPU. No TPU if left blank.
cluster_config: Should be specified only for multi-worker jobs.
Task specific dictionary for cluster config dict in the TF_CONFIG format.
https://www.tensorflow.org/guide/distributed_training#setting_up_tf_config_environment_variable
If passed as a string, will be parsed to a dictionary. Two components
should be specified: cluster and task. Cluster provides information about
the training cluster, which is a dict consisting of different types of
jobs such as chief and worker. Task is information about the current task.
For example: "{"cluster": {"worker": ["host1:port", "host2:port"]},
"task": {"type": "worker", "index": 0}}"
Returns:
A distribution strategy. MirroredStrategy by default. TPUStrategy if `tpu`
arg is specified. MultiWorkerMirroredStrategy if `cluster_config` arg is
specified.
"""
if tpu:
logging.info('Use TPU at %s', tpu)
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu=tpu)
tf.config.experimental_connect_to_cluster(resolver)
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.TPUStrategy(resolver)
elif cluster_config:
if not isinstance(cluster_config, dict):
cluster_config = json.loads(cluster_config)
cluster_spec = tf.train.ClusterSpec(cluster_config['cluster'])
resolver = tf.distribute.cluster_resolver.SimpleClusterResolver(
cluster_spec=cluster_spec,
task_type=cluster_config['task']['type'],
task_id=cluster_config['task']['index'],
num_accelerators={'GPU': len(tf.config.list_physical_devices('GPU'))},
rpc_layer='grpc')
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
cluster_resolver=resolver)
else:
logging.info('Defaulting to MirroredStrategy')
strategy = tf.distribute.MirroredStrategy()
return strategy
def expand_path(file_path):
return os.path.expanduser(os.path.expandvars(file_path))
def get_latest_file(dir_path, prefix='operative_config-', suffix='.gin'):
"""Returns latest file with pattern '/dir_path/prefix[iteration]suffix'.
Args:
dir_path: Path to the directory.
prefix: Filename prefix, not including directory.
suffix: Filename suffix, including extension.
Returns:
Path to the latest file
Raises:
FileNotFoundError: If no files match the pattern
'/dir_path/prefix[int]suffix'.
"""
dir_path = expand_path(dir_path)
dir_prefix = os.path.join(dir_path, prefix)
search_pattern = dir_prefix + '*' + suffix
file_paths = tf.io.gfile.glob(search_pattern)
if not file_paths:
raise FileNotFoundError(
f'No files found matching the pattern \'{search_pattern}\'.')
try:
# Filter to get highest iteration, no negative iterations.
get_iter = lambda fp: abs(int(fp.split(dir_prefix)[-1].split(suffix)[0]))
latest_file = max(file_paths, key=get_iter)
return latest_file
except ValueError as verror:
raise FileNotFoundError(
f'Files found with pattern \'{search_pattern}\' do not match '
f'the pattern \'{dir_prefix}[iteration_number]{suffix}\'.\n\n'
f'Files found:\n{file_paths}') from verror
def get_latest_checkpoint(checkpoint_path):
"""Helper function to get path to latest checkpoint.
Args:
checkpoint_path: Path to the directory containing model checkpoints, or
to a specific checkpoint (e.g. `/path/to/model.ckpt-iteration`).
Returns:
Path to latest checkpoint.
Raises:
FileNotFoundError: If no checkpoint is found.
"""
checkpoint_path = expand_path(checkpoint_path)
is_checkpoint = tf.io.gfile.exists(checkpoint_path + '.index')
if is_checkpoint:
# Return the path if it points to a checkpoint.
return checkpoint_path
else:
# Search using 'checkpoints' file.
# Returns None if no 'checkpoints' file, or directory doesn't exist.
ckpt = tf.train.latest_checkpoint(checkpoint_path)
if ckpt:
return ckpt
else:
# Last resort, look for '/path/ckpt-[iter].index' files.
ckpt_f = get_latest_file(checkpoint_path, prefix='ckpt-', suffix='.index')
return ckpt_f.split('.index')[0]
# ---------------------------------- Gin ---------------------------------------
def get_latest_operative_config(restore_dir):
"""Finds the most recently saved operative_config in a directory.
Args:
restore_dir: Path to directory with gin operative_configs. Will also work
if passing a path to a file in that directory such as a checkpoint.
Returns:
Filepath to most recent operative config.
Raises:
FileNotFoundError: If no config is found.
"""
try:
return get_latest_file(
restore_dir, prefix='operative_config-', suffix='.gin')
except FileNotFoundError:
return get_latest_file(
os.path.dirname(restore_dir), prefix='operative_config-', suffix='.gin')
def write_gin_config(summary_writer, save_dir, step):
""""Writes gin operative_config to save_dir and tensorboard."""
config_str = gin.operative_config_str()
# Save the original config string to a file.
base_name = 'operative_config-{}'.format(step)
fname = os.path.join(save_dir, base_name + '.gin')
with tf.io.gfile.GFile(fname, 'w') as f:
f.write(config_str)
# Formatting hack copied from gin.tf.GinConfigSaverHook.
def format_for_tensorboard(line):
"""Convert a single line to markdown format."""
if not line.startswith('#'):
return ' ' + line
line = line[2:]
if line.startswith('===='):
return ''
if line.startswith('None'):
return ' # None.'
if line.endswith(':'):
return '#### ' + line
return line
# Convert config string to markdown.
md_lines = []
for line in config_str.splitlines():
md_line = format_for_tensorboard(line)
if md_line is not None:
md_lines.append(md_line)
md_config_str = '\n'.join(md_lines)
# Add to tensorboard.
with summary_writer.as_default():
text_tensor = tf.convert_to_tensor(md_config_str)
tf.summary.text(name='gin/' + base_name, data=text_tensor, step=step)
summary_writer.flush()
def gin_register_keras_layers():
"""Registers all keras layers and Sequential to be referenceable in gin."""
# Register sequential model.
gin.external_configurable(tf.keras.Sequential, 'tf.keras.Sequential')
# Register all the layers.
for k, v in inspect.getmembers(tf.keras.layers):
# Duck typing for tf.keras.layers.Layer since keras uses metaclasses.
if hasattr(v, 'variables'):
gin.external_configurable(v, f'tf.keras.layers.{k}')
# ------------------------ Training Loop ---------------------------------------
@gin.configurable
def train(data_provider,
trainer,
batch_size=32,
num_steps=1000000,
steps_per_summary=300,
steps_per_save=300,
save_dir='/tmp/ddsp',
restore_dir='/tmp/ddsp',
early_stop_loss_value=None,
report_loss_to_hypertune=False):
"""Main training loop.
Args:
data_provider: DataProvider object for training data.
trainer: Trainer object built with Model to train.
batch_size: Total batch size.
num_steps: Number of training steps.
steps_per_summary: Number of training steps per summary save.
steps_per_save: Number of training steps per checkpoint save.
save_dir: Directory where checkpoints and summaries will be saved.
If empty string, no checkpoints or summaries will be saved.
restore_dir: Directory where latest checkpoints for resuming the training
are stored. If there are no checkpoints in this directory, training will
begin anew.
early_stop_loss_value: Early stopping. When the total_loss reaches below this
value training stops. If None training will run for num_steps steps.
report_loss_to_hypertune: Report loss values to hypertune package for
hyperparameter tuning, such as on Google Cloud AI-Platform.
"""
# Get a distributed dataset iterator.
dataset = data_provider.get_batch(batch_size, shuffle=True, repeats=-1)
dataset = trainer.distribute_dataset(dataset)
dataset_iter = iter(dataset)
# Build model, easiest to just run forward pass.
trainer.build(next(dataset_iter))
# Load latest checkpoint if one exists in load directory.
try:
trainer.restore(restore_dir)
except FileNotFoundError:
logging.info('No existing checkpoint found in %s, skipping '
'checkpoint loading.', restore_dir)
if save_dir:
# Set up the summary writer and metrics.
summary_dir = os.path.join(save_dir, 'summaries', 'train')
summary_writer = tf.summary.create_file_writer(summary_dir)
# Save the gin config.
write_gin_config(summary_writer, save_dir, trainer.step.numpy())
else:
# Need to create a dummy writer, even if no save_dir is provided.
summary_writer = tf.summary.create_noop_writer()
# Train.
with summary_writer.as_default():
tick = time.time()
for iteration in range(num_steps):
step = trainer.step # Step is not iteration if restarting a model.
# Take a step.
losses = trainer.train_step(dataset_iter)
# Create training loss metrics when starting/restarting training.
if iteration == 0:
loss_names = list(losses.keys())
logging.info('Creating metrics for %s', loss_names)
avg_losses = {name: tf.keras.metrics.Mean(name=name, dtype=tf.float32)
for name in loss_names}
# Update metrics.
for k, v in losses.items():
avg_losses[k].update_state(v)
# Log the step.
log_str = 'step: {}\t'.format(int(step.numpy()))
for k, v in losses.items():
log_str += '{}: {:.2f}\t'.format(k, v)
logging.info(log_str)
# Write Summaries.
if step % steps_per_summary == 0 and save_dir:
# Speed.
steps_per_sec = steps_per_summary / (time.time() - tick)
tf.summary.scalar('steps_per_sec', steps_per_sec, step=step)
tick = time.time()
# Metrics.
for k, metric in avg_losses.items():
tf.summary.scalar('losses/{}'.format(k), metric.result(), step=step)
metric.reset_states()
# Report metrics for hyperparameter tuning if enabled.
if report_loss_to_hypertune:
|
# Stop the training when the loss reaches given value
if (early_stop_loss_value is not None and
losses['total_loss'] <= early_stop_loss_value):
logging.info('Total loss reached early stopping value of %s',
early_stop_loss_value)
# Write a final checkpoint.
if save_dir:
trainer.save(save_dir)
summary_writer.flush()
break
# Save Model.
if step % steps_per_save == 0 and save_dir:
trainer.save(save_dir)
summary_writer.flush()
logging.info('Training Finished!')
| cloud.report_metric_to_hypertune(losses['total_loss'], step.numpy()) | conditional_block |
train_util.py | # Copyright 2022 The DDSP Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Library of training functions."""
import inspect
import json
import os
import time
from absl import logging
from ddsp.training import cloud
import gin
import tensorflow.compat.v2 as tf
# ---------------------- Helper Functions --------------------------------------
def get_strategy(tpu='', cluster_config=''):
|
def expand_path(file_path):
return os.path.expanduser(os.path.expandvars(file_path))
def get_latest_file(dir_path, prefix='operative_config-', suffix='.gin'):
"""Returns latest file with pattern '/dir_path/prefix[iteration]suffix'.
Args:
dir_path: Path to the directory.
prefix: Filename prefix, not including directory.
suffix: Filename suffix, including extension.
Returns:
Path to the latest file
Raises:
FileNotFoundError: If no files match the pattern
'/dir_path/prefix[int]suffix'.
"""
dir_path = expand_path(dir_path)
dir_prefix = os.path.join(dir_path, prefix)
search_pattern = dir_prefix + '*' + suffix
file_paths = tf.io.gfile.glob(search_pattern)
if not file_paths:
raise FileNotFoundError(
f'No files found matching the pattern \'{search_pattern}\'.')
try:
# Filter to get highest iteration, no negative iterations.
get_iter = lambda fp: abs(int(fp.split(dir_prefix)[-1].split(suffix)[0]))
latest_file = max(file_paths, key=get_iter)
return latest_file
except ValueError as verror:
raise FileNotFoundError(
f'Files found with pattern \'{search_pattern}\' do not match '
f'the pattern \'{dir_prefix}[iteration_number]{suffix}\'.\n\n'
f'Files found:\n{file_paths}') from verror
def get_latest_checkpoint(checkpoint_path):
"""Helper function to get path to latest checkpoint.
Args:
checkpoint_path: Path to the directory containing model checkpoints, or
to a specific checkpoint (e.g. `/path/to/model.ckpt-iteration`).
Returns:
Path to latest checkpoint.
Raises:
FileNotFoundError: If no checkpoint is found.
"""
checkpoint_path = expand_path(checkpoint_path)
is_checkpoint = tf.io.gfile.exists(checkpoint_path + '.index')
if is_checkpoint:
# Return the path if it points to a checkpoint.
return checkpoint_path
else:
# Search using 'checkpoints' file.
# Returns None if no 'checkpoints' file, or directory doesn't exist.
ckpt = tf.train.latest_checkpoint(checkpoint_path)
if ckpt:
return ckpt
else:
# Last resort, look for '/path/ckpt-[iter].index' files.
ckpt_f = get_latest_file(checkpoint_path, prefix='ckpt-', suffix='.index')
return ckpt_f.split('.index')[0]
# ---------------------------------- Gin ---------------------------------------
def get_latest_operative_config(restore_dir):
"""Finds the most recently saved operative_config in a directory.
Args:
restore_dir: Path to directory with gin operative_configs. Will also work
if passing a path to a file in that directory such as a checkpoint.
Returns:
Filepath to most recent operative config.
Raises:
FileNotFoundError: If no config is found.
"""
try:
return get_latest_file(
restore_dir, prefix='operative_config-', suffix='.gin')
except FileNotFoundError:
return get_latest_file(
os.path.dirname(restore_dir), prefix='operative_config-', suffix='.gin')
def write_gin_config(summary_writer, save_dir, step):
""""Writes gin operative_config to save_dir and tensorboard."""
config_str = gin.operative_config_str()
# Save the original config string to a file.
base_name = 'operative_config-{}'.format(step)
fname = os.path.join(save_dir, base_name + '.gin')
with tf.io.gfile.GFile(fname, 'w') as f:
f.write(config_str)
# Formatting hack copied from gin.tf.GinConfigSaverHook.
def format_for_tensorboard(line):
"""Convert a single line to markdown format."""
if not line.startswith('#'):
return ' ' + line
line = line[2:]
if line.startswith('===='):
return ''
if line.startswith('None'):
return ' # None.'
if line.endswith(':'):
return '#### ' + line
return line
# Convert config string to markdown.
md_lines = []
for line in config_str.splitlines():
md_line = format_for_tensorboard(line)
if md_line is not None:
md_lines.append(md_line)
md_config_str = '\n'.join(md_lines)
# Add to tensorboard.
with summary_writer.as_default():
text_tensor = tf.convert_to_tensor(md_config_str)
tf.summary.text(name='gin/' + base_name, data=text_tensor, step=step)
summary_writer.flush()
def gin_register_keras_layers():
"""Registers all keras layers and Sequential to be referenceable in gin."""
# Register sequential model.
gin.external_configurable(tf.keras.Sequential, 'tf.keras.Sequential')
# Register all the layers.
for k, v in inspect.getmembers(tf.keras.layers):
# Duck typing for tf.keras.layers.Layer since keras uses metaclasses.
if hasattr(v, 'variables'):
gin.external_configurable(v, f'tf.keras.layers.{k}')
# ------------------------ Training Loop ---------------------------------------
@gin.configurable
def train(data_provider,
trainer,
batch_size=32,
num_steps=1000000,
steps_per_summary=300,
steps_per_save=300,
save_dir='/tmp/ddsp',
restore_dir='/tmp/ddsp',
early_stop_loss_value=None,
report_loss_to_hypertune=False):
"""Main training loop.
Args:
data_provider: DataProvider object for training data.
trainer: Trainer object built with Model to train.
batch_size: Total batch size.
num_steps: Number of training steps.
steps_per_summary: Number of training steps per summary save.
steps_per_save: Number of training steps per checkpoint save.
save_dir: Directory where checkpoints and summaries will be saved.
If empty string, no checkpoints or summaries will be saved.
restore_dir: Directory where latest checkpoints for resuming the training
are stored. If there are no checkpoints in this directory, training will
begin anew.
early_stop_loss_value: Early stopping. When the total_loss reaches below this
value training stops. If None training will run for num_steps steps.
report_loss_to_hypertune: Report loss values to hypertune package for
hyperparameter tuning, such as on Google Cloud AI-Platform.
"""
# Get a distributed dataset iterator.
dataset = data_provider.get_batch(batch_size, shuffle=True, repeats=-1)
dataset = trainer.distribute_dataset(dataset)
dataset_iter = iter(dataset)
# Build model, easiest to just run forward pass.
trainer.build(next(dataset_iter))
# Load latest checkpoint if one exists in load directory.
try:
trainer.restore(restore_dir)
except FileNotFoundError:
logging.info('No existing checkpoint found in %s, skipping '
'checkpoint loading.', restore_dir)
if save_dir:
# Set up the summary writer and metrics.
summary_dir = os.path.join(save_dir, 'summaries', 'train')
summary_writer = tf.summary.create_file_writer(summary_dir)
# Save the gin config.
write_gin_config(summary_writer, save_dir, trainer.step.numpy())
else:
# Need to create a dummy writer, even if no save_dir is provided.
summary_writer = tf.summary.create_noop_writer()
# Train.
with summary_writer.as_default():
tick = time.time()
for iteration in range(num_steps):
step = trainer.step # Step is not iteration if restarting a model.
# Take a step.
losses = trainer.train_step(dataset_iter)
# Create training loss metrics when starting/restarting training.
if iteration == 0:
loss_names = list(losses.keys())
logging.info('Creating metrics for %s', loss_names)
avg_losses = {name: tf.keras.metrics.Mean(name=name, dtype=tf.float32)
for name in loss_names}
# Update metrics.
for k, v in losses.items():
avg_losses[k].update_state(v)
# Log the step.
log_str = 'step: {}\t'.format(int(step.numpy()))
for k, v in losses.items():
log_str += '{}: {:.2f}\t'.format(k, v)
logging.info(log_str)
# Write Summaries.
if step % steps_per_summary == 0 and save_dir:
# Speed.
steps_per_sec = steps_per_summary / (time.time() - tick)
tf.summary.scalar('steps_per_sec', steps_per_sec, step=step)
tick = time.time()
# Metrics.
for k, metric in avg_losses.items():
tf.summary.scalar('losses/{}'.format(k), metric.result(), step=step)
metric.reset_states()
# Report metrics for hyperparameter tuning if enabled.
if report_loss_to_hypertune:
cloud.report_metric_to_hypertune(losses['total_loss'], step.numpy())
# Stop the training when the loss reaches given value
if (early_stop_loss_value is not None and
losses['total_loss'] <= early_stop_loss_value):
logging.info('Total loss reached early stopping value of %s',
early_stop_loss_value)
# Write a final checkpoint.
if save_dir:
trainer.save(save_dir)
summary_writer.flush()
break
# Save Model.
if step % steps_per_save == 0 and save_dir:
trainer.save(save_dir)
summary_writer.flush()
logging.info('Training Finished!')
| """Create a distribution strategy for running on accelerators.
For CPU, single-GPU, or multi-GPU jobs on a single machine, call this function
without args to return a MirroredStrategy.
For TPU jobs, specify an address to the `tpu` argument.
For multi-machine GPU jobs, specify a `cluster_config` argument of the cluster
configuration.
Args:
tpu: Address of the TPU. No TPU if left blank.
cluster_config: Should be specified only for multi-worker jobs.
Task specific dictionary for cluster config dict in the TF_CONFIG format.
https://www.tensorflow.org/guide/distributed_training#setting_up_tf_config_environment_variable
If passed as a string, will be parsed to a dictionary. Two components
should be specified: cluster and task. Cluster provides information about
the training cluster, which is a dict consisting of different types of
jobs such as chief and worker. Task is information about the current task.
For example: "{"cluster": {"worker": ["host1:port", "host2:port"]},
"task": {"type": "worker", "index": 0}}"
Returns:
A distribution strategy. MirroredStrategy by default. TPUStrategy if `tpu`
arg is specified. MultiWorkerMirroredStrategy if `cluster_config` arg is
specified.
"""
if tpu:
logging.info('Use TPU at %s', tpu)
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu=tpu)
tf.config.experimental_connect_to_cluster(resolver)
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.TPUStrategy(resolver)
elif cluster_config:
if not isinstance(cluster_config, dict):
cluster_config = json.loads(cluster_config)
cluster_spec = tf.train.ClusterSpec(cluster_config['cluster'])
resolver = tf.distribute.cluster_resolver.SimpleClusterResolver(
cluster_spec=cluster_spec,
task_type=cluster_config['task']['type'],
task_id=cluster_config['task']['index'],
num_accelerators={'GPU': len(tf.config.list_physical_devices('GPU'))},
rpc_layer='grpc')
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
cluster_resolver=resolver)
else:
logging.info('Defaulting to MirroredStrategy')
strategy = tf.distribute.MirroredStrategy()
return strategy | identifier_body |
train_util.py | # Copyright 2022 The DDSP Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Library of training functions."""
import inspect
import json
import os
import time
from absl import logging
from ddsp.training import cloud
import gin
import tensorflow.compat.v2 as tf
# ---------------------- Helper Functions --------------------------------------
def get_strategy(tpu='', cluster_config=''):
"""Create a distribution strategy for running on accelerators.
For CPU, single-GPU, or multi-GPU jobs on a single machine, call this function
without args to return a MirroredStrategy.
For TPU jobs, specify an address to the `tpu` argument.
For multi-machine GPU jobs, specify a `cluster_config` argument of the cluster
configuration.
Args:
tpu: Address of the TPU. No TPU if left blank.
cluster_config: Should be specified only for multi-worker jobs.
Task specific dictionary for cluster config dict in the TF_CONFIG format.
https://www.tensorflow.org/guide/distributed_training#setting_up_tf_config_environment_variable
If passed as a string, will be parsed to a dictionary. Two components
should be specified: cluster and task. Cluster provides information about
the training cluster, which is a dict consisting of different types of
jobs such as chief and worker. Task is information about the current task.
For example: "{"cluster": {"worker": ["host1:port", "host2:port"]},
"task": {"type": "worker", "index": 0}}"
Returns:
A distribution strategy. MirroredStrategy by default. TPUStrategy if `tpu`
arg is specified. MultiWorkerMirroredStrategy if `cluster_config` arg is
specified.
"""
if tpu:
logging.info('Use TPU at %s', tpu)
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu=tpu)
tf.config.experimental_connect_to_cluster(resolver)
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.TPUStrategy(resolver)
elif cluster_config:
if not isinstance(cluster_config, dict):
cluster_config = json.loads(cluster_config)
cluster_spec = tf.train.ClusterSpec(cluster_config['cluster'])
resolver = tf.distribute.cluster_resolver.SimpleClusterResolver(
cluster_spec=cluster_spec,
task_type=cluster_config['task']['type'],
task_id=cluster_config['task']['index'],
num_accelerators={'GPU': len(tf.config.list_physical_devices('GPU'))},
rpc_layer='grpc')
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
cluster_resolver=resolver)
else:
logging.info('Defaulting to MirroredStrategy')
strategy = tf.distribute.MirroredStrategy()
return strategy
def expand_path(file_path):
return os.path.expanduser(os.path.expandvars(file_path))
def get_latest_file(dir_path, prefix='operative_config-', suffix='.gin'):
"""Returns latest file with pattern '/dir_path/prefix[iteration]suffix'.
Args:
dir_path: Path to the directory.
prefix: Filename prefix, not including directory.
suffix: Filename suffix, including extension.
Returns:
Path to the latest file
Raises:
FileNotFoundError: If no files match the pattern
'/dir_path/prefix[int]suffix'.
"""
dir_path = expand_path(dir_path)
dir_prefix = os.path.join(dir_path, prefix)
search_pattern = dir_prefix + '*' + suffix
file_paths = tf.io.gfile.glob(search_pattern)
if not file_paths:
raise FileNotFoundError(
f'No files found matching the pattern \'{search_pattern}\'.')
try:
# Filter to get highest iteration, no negative iterations.
get_iter = lambda fp: abs(int(fp.split(dir_prefix)[-1].split(suffix)[0]))
latest_file = max(file_paths, key=get_iter)
return latest_file
except ValueError as verror:
raise FileNotFoundError(
f'Files found with pattern \'{search_pattern}\' do not match '
f'the pattern \'{dir_prefix}[iteration_number]{suffix}\'.\n\n'
f'Files found:\n{file_paths}') from verror
def get_latest_checkpoint(checkpoint_path):
"""Helper function to get path to latest checkpoint.
Args:
checkpoint_path: Path to the directory containing model checkpoints, or
to a specific checkpoint (e.g. `/path/to/model.ckpt-iteration`).
Returns:
Path to latest checkpoint.
Raises:
FileNotFoundError: If no checkpoint is found.
"""
checkpoint_path = expand_path(checkpoint_path)
is_checkpoint = tf.io.gfile.exists(checkpoint_path + '.index')
if is_checkpoint:
# Return the path if it points to a checkpoint.
return checkpoint_path
else:
# Search using 'checkpoints' file.
# Returns None if no 'checkpoints' file, or directory doesn't exist.
ckpt = tf.train.latest_checkpoint(checkpoint_path)
if ckpt:
return ckpt
else:
# Last resort, look for '/path/ckpt-[iter].index' files.
ckpt_f = get_latest_file(checkpoint_path, prefix='ckpt-', suffix='.index')
return ckpt_f.split('.index')[0]
# ---------------------------------- Gin ---------------------------------------
def get_latest_operative_config(restore_dir):
"""Finds the most recently saved operative_config in a directory.
Args:
restore_dir: Path to directory with gin operative_configs. Will also work
if passing a path to a file in that directory such as a checkpoint.
Returns:
Filepath to most recent operative config.
Raises:
FileNotFoundError: If no config is found.
"""
try:
return get_latest_file(
restore_dir, prefix='operative_config-', suffix='.gin')
except FileNotFoundError:
return get_latest_file(
os.path.dirname(restore_dir), prefix='operative_config-', suffix='.gin')
def write_gin_config(summary_writer, save_dir, step):
""""Writes gin operative_config to save_dir and tensorboard."""
config_str = gin.operative_config_str()
# Save the original config string to a file.
base_name = 'operative_config-{}'.format(step)
fname = os.path.join(save_dir, base_name + '.gin')
with tf.io.gfile.GFile(fname, 'w') as f:
f.write(config_str)
# Formatting hack copied from gin.tf.GinConfigSaverHook.
def format_for_tensorboard(line):
"""Convert a single line to markdown format."""
if not line.startswith('#'):
return ' ' + line
line = line[2:]
if line.startswith('===='):
return ''
if line.startswith('None'):
return ' # None.'
if line.endswith(':'):
return '#### ' + line
return line
# Convert config string to markdown.
md_lines = []
for line in config_str.splitlines():
md_line = format_for_tensorboard(line)
if md_line is not None:
md_lines.append(md_line)
md_config_str = '\n'.join(md_lines)
# Add to tensorboard.
with summary_writer.as_default():
text_tensor = tf.convert_to_tensor(md_config_str)
tf.summary.text(name='gin/' + base_name, data=text_tensor, step=step)
summary_writer.flush()
def gin_register_keras_layers():
"""Registers all keras layers and Sequential to be referenceable in gin."""
# Register sequential model.
gin.external_configurable(tf.keras.Sequential, 'tf.keras.Sequential')
# Register all the layers.
for k, v in inspect.getmembers(tf.keras.layers):
# Duck typing for tf.keras.layers.Layer since keras uses metaclasses.
if hasattr(v, 'variables'):
gin.external_configurable(v, f'tf.keras.layers.{k}')
# ------------------------ Training Loop ---------------------------------------
@gin.configurable
def train(data_provider,
trainer,
batch_size=32,
num_steps=1000000,
steps_per_summary=300,
steps_per_save=300,
save_dir='/tmp/ddsp',
restore_dir='/tmp/ddsp',
early_stop_loss_value=None,
report_loss_to_hypertune=False):
"""Main training loop.
Args:
data_provider: DataProvider object for training data.
trainer: Trainer object built with Model to train.
batch_size: Total batch size.
num_steps: Number of training steps.
steps_per_summary: Number of training steps per summary save.
steps_per_save: Number of training steps per checkpoint save.
save_dir: Directory where checkpoints and summaries will be saved.
If empty string, no checkpoints or summaries will be saved.
restore_dir: Directory where latest checkpoints for resuming the training
are stored. If there are no checkpoints in this directory, training will
begin anew.
early_stop_loss_value: Early stopping. When the total_loss reaches below this
value training stops. If None training will run for num_steps steps.
report_loss_to_hypertune: Report loss values to hypertune package for
hyperparameter tuning, such as on Google Cloud AI-Platform.
"""
# Get a distributed dataset iterator.
dataset = data_provider.get_batch(batch_size, shuffle=True, repeats=-1)
dataset = trainer.distribute_dataset(dataset)
dataset_iter = iter(dataset)
# Build model, easiest to just run forward pass.
trainer.build(next(dataset_iter))
# Load latest checkpoint if one exists in load directory.
try:
trainer.restore(restore_dir)
except FileNotFoundError:
logging.info('No existing checkpoint found in %s, skipping '
'checkpoint loading.', restore_dir)
if save_dir:
# Set up the summary writer and metrics.
summary_dir = os.path.join(save_dir, 'summaries', 'train')
summary_writer = tf.summary.create_file_writer(summary_dir)
# Save the gin config.
write_gin_config(summary_writer, save_dir, trainer.step.numpy())
else:
# Need to create a dummy writer, even if no save_dir is provided. | tick = time.time()
for iteration in range(num_steps):
step = trainer.step # Step is not iteration if restarting a model.
# Take a step.
losses = trainer.train_step(dataset_iter)
# Create training loss metrics when starting/restarting training.
if iteration == 0:
loss_names = list(losses.keys())
logging.info('Creating metrics for %s', loss_names)
avg_losses = {name: tf.keras.metrics.Mean(name=name, dtype=tf.float32)
for name in loss_names}
# Update metrics.
for k, v in losses.items():
avg_losses[k].update_state(v)
# Log the step.
log_str = 'step: {}\t'.format(int(step.numpy()))
for k, v in losses.items():
log_str += '{}: {:.2f}\t'.format(k, v)
logging.info(log_str)
# Write Summaries.
if step % steps_per_summary == 0 and save_dir:
# Speed.
steps_per_sec = steps_per_summary / (time.time() - tick)
tf.summary.scalar('steps_per_sec', steps_per_sec, step=step)
tick = time.time()
# Metrics.
for k, metric in avg_losses.items():
tf.summary.scalar('losses/{}'.format(k), metric.result(), step=step)
metric.reset_states()
# Report metrics for hyperparameter tuning if enabled.
if report_loss_to_hypertune:
cloud.report_metric_to_hypertune(losses['total_loss'], step.numpy())
# Stop the training when the loss reaches given value
if (early_stop_loss_value is not None and
losses['total_loss'] <= early_stop_loss_value):
logging.info('Total loss reached early stopping value of %s',
early_stop_loss_value)
# Write a final checkpoint.
if save_dir:
trainer.save(save_dir)
summary_writer.flush()
break
# Save Model.
if step % steps_per_save == 0 and save_dir:
trainer.save(save_dir)
summary_writer.flush()
logging.info('Training Finished!') | summary_writer = tf.summary.create_noop_writer()
# Train.
with summary_writer.as_default(): | random_line_split |
train_util.py | # Copyright 2022 The DDSP Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""Library of training functions."""
import inspect
import json
import os
import time
from absl import logging
from ddsp.training import cloud
import gin
import tensorflow.compat.v2 as tf
# ---------------------- Helper Functions --------------------------------------
def get_strategy(tpu='', cluster_config=''):
"""Create a distribution strategy for running on accelerators.
For CPU, single-GPU, or multi-GPU jobs on a single machine, call this function
without args to return a MirroredStrategy.
For TPU jobs, specify an address to the `tpu` argument.
For multi-machine GPU jobs, specify a `cluster_config` argument of the cluster
configuration.
Args:
tpu: Address of the TPU. No TPU if left blank.
cluster_config: Should be specified only for multi-worker jobs.
Task specific dictionary for cluster config dict in the TF_CONFIG format.
https://www.tensorflow.org/guide/distributed_training#setting_up_tf_config_environment_variable
If passed as a string, will be parsed to a dictionary. Two components
should be specified: cluster and task. Cluster provides information about
the training cluster, which is a dict consisting of different types of
jobs such as chief and worker. Task is information about the current task.
For example: "{"cluster": {"worker": ["host1:port", "host2:port"]},
"task": {"type": "worker", "index": 0}}"
Returns:
A distribution strategy. MirroredStrategy by default. TPUStrategy if `tpu`
arg is specified. MultiWorkerMirroredStrategy if `cluster_config` arg is
specified.
"""
if tpu:
logging.info('Use TPU at %s', tpu)
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu=tpu)
tf.config.experimental_connect_to_cluster(resolver)
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.TPUStrategy(resolver)
elif cluster_config:
if not isinstance(cluster_config, dict):
cluster_config = json.loads(cluster_config)
cluster_spec = tf.train.ClusterSpec(cluster_config['cluster'])
resolver = tf.distribute.cluster_resolver.SimpleClusterResolver(
cluster_spec=cluster_spec,
task_type=cluster_config['task']['type'],
task_id=cluster_config['task']['index'],
num_accelerators={'GPU': len(tf.config.list_physical_devices('GPU'))},
rpc_layer='grpc')
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
cluster_resolver=resolver)
else:
logging.info('Defaulting to MirroredStrategy')
strategy = tf.distribute.MirroredStrategy()
return strategy
def expand_path(file_path):
return os.path.expanduser(os.path.expandvars(file_path))
def get_latest_file(dir_path, prefix='operative_config-', suffix='.gin'):
"""Returns latest file with pattern '/dir_path/prefix[iteration]suffix'.
Args:
dir_path: Path to the directory.
prefix: Filename prefix, not including directory.
suffix: Filename suffix, including extension.
Returns:
Path to the latest file
Raises:
FileNotFoundError: If no files match the pattern
'/dir_path/prefix[int]suffix'.
"""
dir_path = expand_path(dir_path)
dir_prefix = os.path.join(dir_path, prefix)
search_pattern = dir_prefix + '*' + suffix
file_paths = tf.io.gfile.glob(search_pattern)
if not file_paths:
raise FileNotFoundError(
f'No files found matching the pattern \'{search_pattern}\'.')
try:
# Filter to get highest iteration, no negative iterations.
get_iter = lambda fp: abs(int(fp.split(dir_prefix)[-1].split(suffix)[0]))
latest_file = max(file_paths, key=get_iter)
return latest_file
except ValueError as verror:
raise FileNotFoundError(
f'Files found with pattern \'{search_pattern}\' do not match '
f'the pattern \'{dir_prefix}[iteration_number]{suffix}\'.\n\n'
f'Files found:\n{file_paths}') from verror
def get_latest_checkpoint(checkpoint_path):
"""Helper function to get path to latest checkpoint.
Args:
checkpoint_path: Path to the directory containing model checkpoints, or
to a specific checkpoint (e.g. `/path/to/model.ckpt-iteration`).
Returns:
Path to latest checkpoint.
Raises:
FileNotFoundError: If no checkpoint is found.
"""
checkpoint_path = expand_path(checkpoint_path)
is_checkpoint = tf.io.gfile.exists(checkpoint_path + '.index')
if is_checkpoint:
# Return the path if it points to a checkpoint.
return checkpoint_path
else:
# Search using 'checkpoints' file.
# Returns None if no 'checkpoints' file, or directory doesn't exist.
ckpt = tf.train.latest_checkpoint(checkpoint_path)
if ckpt:
return ckpt
else:
# Last resort, look for '/path/ckpt-[iter].index' files.
ckpt_f = get_latest_file(checkpoint_path, prefix='ckpt-', suffix='.index')
return ckpt_f.split('.index')[0]
# ---------------------------------- Gin ---------------------------------------
def get_latest_operative_config(restore_dir):
"""Finds the most recently saved operative_config in a directory.
Args:
restore_dir: Path to directory with gin operative_configs. Will also work
if passing a path to a file in that directory such as a checkpoint.
Returns:
Filepath to most recent operative config.
Raises:
FileNotFoundError: If no config is found.
"""
try:
return get_latest_file(
restore_dir, prefix='operative_config-', suffix='.gin')
except FileNotFoundError:
return get_latest_file(
os.path.dirname(restore_dir), prefix='operative_config-', suffix='.gin')
def write_gin_config(summary_writer, save_dir, step):
""""Writes gin operative_config to save_dir and tensorboard."""
config_str = gin.operative_config_str()
# Save the original config string to a file.
base_name = 'operative_config-{}'.format(step)
fname = os.path.join(save_dir, base_name + '.gin')
with tf.io.gfile.GFile(fname, 'w') as f:
f.write(config_str)
# Formatting hack copied from gin.tf.GinConfigSaverHook.
def | (line):
"""Convert a single line to markdown format."""
if not line.startswith('#'):
return ' ' + line
line = line[2:]
if line.startswith('===='):
return ''
if line.startswith('None'):
return ' # None.'
if line.endswith(':'):
return '#### ' + line
return line
# Convert config string to markdown.
md_lines = []
for line in config_str.splitlines():
md_line = format_for_tensorboard(line)
if md_line is not None:
md_lines.append(md_line)
md_config_str = '\n'.join(md_lines)
# Add to tensorboard.
with summary_writer.as_default():
text_tensor = tf.convert_to_tensor(md_config_str)
tf.summary.text(name='gin/' + base_name, data=text_tensor, step=step)
summary_writer.flush()
def gin_register_keras_layers():
"""Registers all keras layers and Sequential to be referenceable in gin."""
# Register sequential model.
gin.external_configurable(tf.keras.Sequential, 'tf.keras.Sequential')
# Register all the layers.
for k, v in inspect.getmembers(tf.keras.layers):
# Duck typing for tf.keras.layers.Layer since keras uses metaclasses.
if hasattr(v, 'variables'):
gin.external_configurable(v, f'tf.keras.layers.{k}')
# ------------------------ Training Loop ---------------------------------------
@gin.configurable
def train(data_provider,
trainer,
batch_size=32,
num_steps=1000000,
steps_per_summary=300,
steps_per_save=300,
save_dir='/tmp/ddsp',
restore_dir='/tmp/ddsp',
early_stop_loss_value=None,
report_loss_to_hypertune=False):
"""Main training loop.
Args:
data_provider: DataProvider object for training data.
trainer: Trainer object built with Model to train.
batch_size: Total batch size.
num_steps: Number of training steps.
steps_per_summary: Number of training steps per summary save.
steps_per_save: Number of training steps per checkpoint save.
save_dir: Directory where checkpoints and summaries will be saved.
If empty string, no checkpoints or summaries will be saved.
restore_dir: Directory where latest checkpoints for resuming the training
are stored. If there are no checkpoints in this directory, training will
begin anew.
early_stop_loss_value: Early stopping. When the total_loss reaches below this
value training stops. If None training will run for num_steps steps.
report_loss_to_hypertune: Report loss values to hypertune package for
hyperparameter tuning, such as on Google Cloud AI-Platform.
"""
# Get a distributed dataset iterator.
dataset = data_provider.get_batch(batch_size, shuffle=True, repeats=-1)
dataset = trainer.distribute_dataset(dataset)
dataset_iter = iter(dataset)
# Build model, easiest to just run forward pass.
trainer.build(next(dataset_iter))
# Load latest checkpoint if one exists in load directory.
try:
trainer.restore(restore_dir)
except FileNotFoundError:
logging.info('No existing checkpoint found in %s, skipping '
'checkpoint loading.', restore_dir)
if save_dir:
# Set up the summary writer and metrics.
summary_dir = os.path.join(save_dir, 'summaries', 'train')
summary_writer = tf.summary.create_file_writer(summary_dir)
# Save the gin config.
write_gin_config(summary_writer, save_dir, trainer.step.numpy())
else:
# Need to create a dummy writer, even if no save_dir is provided.
summary_writer = tf.summary.create_noop_writer()
# Train.
with summary_writer.as_default():
tick = time.time()
for iteration in range(num_steps):
step = trainer.step # Step is not iteration if restarting a model.
# Take a step.
losses = trainer.train_step(dataset_iter)
# Create training loss metrics when starting/restarting training.
if iteration == 0:
loss_names = list(losses.keys())
logging.info('Creating metrics for %s', loss_names)
avg_losses = {name: tf.keras.metrics.Mean(name=name, dtype=tf.float32)
for name in loss_names}
# Update metrics.
for k, v in losses.items():
avg_losses[k].update_state(v)
# Log the step.
log_str = 'step: {}\t'.format(int(step.numpy()))
for k, v in losses.items():
log_str += '{}: {:.2f}\t'.format(k, v)
logging.info(log_str)
# Write Summaries.
if step % steps_per_summary == 0 and save_dir:
# Speed.
steps_per_sec = steps_per_summary / (time.time() - tick)
tf.summary.scalar('steps_per_sec', steps_per_sec, step=step)
tick = time.time()
# Metrics.
for k, metric in avg_losses.items():
tf.summary.scalar('losses/{}'.format(k), metric.result(), step=step)
metric.reset_states()
# Report metrics for hyperparameter tuning if enabled.
if report_loss_to_hypertune:
cloud.report_metric_to_hypertune(losses['total_loss'], step.numpy())
# Stop the training when the loss reaches given value
if (early_stop_loss_value is not None and
losses['total_loss'] <= early_stop_loss_value):
logging.info('Total loss reached early stopping value of %s',
early_stop_loss_value)
# Write a final checkpoint.
if save_dir:
trainer.save(save_dir)
summary_writer.flush()
break
# Save Model.
if step % steps_per_save == 0 and save_dir:
trainer.save(save_dir)
summary_writer.flush()
logging.info('Training Finished!')
| format_for_tensorboard | identifier_name |
attr-stmt-expr.rs | // Copyright 2018 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.
// aux-build:attr-stmt-expr.rs
#![feature(proc_macro_hygiene)]
extern crate attr_stmt_expr;
use attr_stmt_expr::{expect_let, expect_print_stmt, expect_expr, expect_print_expr};
fn | (string: &'static str) {
// macros are handled a bit differently
#[expect_print_expr]
//~^ ERROR attributes on expressions are experimental
//~| HELP add #![feature(stmt_expr_attributes)] to the crate attributes to enable
println!("{}", string)
}
fn main() {
#[expect_let]
let string = "Hello, world!";
#[expect_print_stmt]
println!("{}", string);
#[expect_expr]
//~^ ERROR attributes on expressions are experimental
//~| HELP add #![feature(stmt_expr_attributes)] to the crate attributes to enable
print_str("string")
}
| print_str | identifier_name |
attr-stmt-expr.rs | // Copyright 2018 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.
// aux-build:attr-stmt-expr.rs
#![feature(proc_macro_hygiene)]
extern crate attr_stmt_expr;
use attr_stmt_expr::{expect_let, expect_print_stmt, expect_expr, expect_print_expr};
fn print_str(string: &'static str) {
// macros are handled a bit differently | }
fn main() {
#[expect_let]
let string = "Hello, world!";
#[expect_print_stmt]
println!("{}", string);
#[expect_expr]
//~^ ERROR attributes on expressions are experimental
//~| HELP add #![feature(stmt_expr_attributes)] to the crate attributes to enable
print_str("string")
} | #[expect_print_expr]
//~^ ERROR attributes on expressions are experimental
//~| HELP add #![feature(stmt_expr_attributes)] to the crate attributes to enable
println!("{}", string) | random_line_split |
attr-stmt-expr.rs | // Copyright 2018 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.
// aux-build:attr-stmt-expr.rs
#![feature(proc_macro_hygiene)]
extern crate attr_stmt_expr;
use attr_stmt_expr::{expect_let, expect_print_stmt, expect_expr, expect_print_expr};
fn print_str(string: &'static str) {
// macros are handled a bit differently
#[expect_print_expr]
//~^ ERROR attributes on expressions are experimental
//~| HELP add #![feature(stmt_expr_attributes)] to the crate attributes to enable
println!("{}", string)
}
fn main() | {
#[expect_let]
let string = "Hello, world!";
#[expect_print_stmt]
println!("{}", string);
#[expect_expr]
//~^ ERROR attributes on expressions are experimental
//~| HELP add #![feature(stmt_expr_attributes)] to the crate attributes to enable
print_str("string")
} | identifier_body | |
buttons-input.rs | /*
* Copyright (c) 2018 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use gtk::{
EditableSignals,
Inhibit,
prelude::ButtonExt,
prelude::EntryExt,
prelude::LabelExt,
prelude::OrientableExt,
prelude::WidgetExt,
};
use gtk::Orientation::{Horizontal, Vertical};
use relm::{Relm, Widget};
use relm_derive::{Msg, widget};
use self::Msg::*;
pub struct Model {
left_text: String,
relm: Relm<Win>,
right_text: String,
text: String,
}
#[derive(Clone, Msg)]
pub enum Msg {
Cancel,
Concat,
DataAvailable(String),
DataCleared,
LeftChanged(String),
RightChanged(String),
Quit,
}
#[widget]
impl Widget for Win {
fn model(relm: &Relm<Self>, (): ()) -> Model {
Model {
left_text: String::new(),
right_text: String::new(),
relm: relm.clone(),
text: String::new(),
}
}
fn update(&mut self, event: Msg) {
match event {
Cancel => {
self.model.left_text = String::new();
self.model.right_text = String::new();
self.model.text = String::new();
self.model.relm.stream().emit(DataCleared);
},
Concat => | ,
// To be listened to by the user.
DataAvailable(_) | DataCleared => (),
LeftChanged(text) => self.model.left_text = text,
RightChanged(text) => self.model.right_text = text,
Quit => gtk::main_quit(),
}
}
view! {
#[name="window"]
gtk::Window {
gtk::Box {
gtk::Box {
#[name="left_entry"]
gtk::Entry {
text: &self.model.left_text,
changed(entry) => LeftChanged(entry.text().to_string()),
},
#[name="right_entry"]
gtk::Entry {
text: &self.model.right_text,
changed(entry) => RightChanged(entry.text().to_string()),
},
orientation: Horizontal,
},
gtk::ButtonBox {
#[name="concat_button"]
gtk::Button {
clicked => Concat,
label: "Concat",
},
#[name="cancel_button"]
gtk::Button {
clicked => Cancel,
label: "Cancel",
},
orientation: Horizontal,
},
orientation: Vertical,
#[name="label"]
gtk::Label {
label: &self.model.text,
},
},
delete_event(_, _) => (Quit, Inhibit(false)),
}
}
}
#[cfg(test)]
mod tests {
use gdk::keys::constants as key;
use gtk::prelude::{
EntryExt,
GtkWindowExt,
LabelExt,
WidgetExt,
};
use gtk_test::{
assert_text,
focus,
};
use relm_test::{
enter_key,
enter_keys,
relm_observer_new,
relm_observer_wait,
};
use crate::Msg::{DataAvailable, DataCleared};
use crate::Win;
#[test]
fn label_change() {
let (component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed");
let cancel_button = &widgets.cancel_button;
let concat_button = &widgets.concat_button;
let label = &widgets.label;
let left_entry = &widgets.left_entry;
let right_entry = &widgets.right_entry;
let window = &widgets.window;
let available_observer = relm_observer_new!(component, DataAvailable(_));
let cleared_observer = relm_observer_new!(component, DataCleared);
assert_text!(label, "");
enter_keys(&window.focused_widget().expect("focused widget"), "left");
enter_key(window, key::Tab);
assert!(right_entry.has_focus());
enter_keys(&window.focused_widget().expect("focused widget"), "right");
enter_key(window, key::Tab);
assert!(concat_button.has_focus());
enter_key(
&window.focused_widget().expect("focused widget"),
key::space,
);
assert_text!(label, "leftright");
enter_key(window, key::Tab);
assert!(cancel_button.has_focus());
enter_key(
&window.focused_widget().expect("focused widget"),
key::space,
);
assert_text!(label, "");
assert_text!(left_entry, "");
assert_text!(right_entry, "");
focus(left_entry);
assert!(left_entry.has_focus());
focus(right_entry);
assert!(right_entry.has_focus());
relm_observer_wait!(let DataAvailable(text) = available_observer);
assert_eq!(text, "leftright");
relm_observer_wait!(let DataCleared = cleared_observer);
}
}
| {
self.model.text = format!("{}{}", self.model.left_text, self.model.right_text);
self.model.relm.stream().emit(DataAvailable(self.model.text.clone()));
} | conditional_block |
buttons-input.rs | /*
* Copyright (c) 2018 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use gtk::{
EditableSignals,
Inhibit,
prelude::ButtonExt,
prelude::EntryExt,
prelude::LabelExt,
prelude::OrientableExt,
prelude::WidgetExt,
};
use gtk::Orientation::{Horizontal, Vertical};
use relm::{Relm, Widget};
use relm_derive::{Msg, widget};
use self::Msg::*;
pub struct Model {
left_text: String,
relm: Relm<Win>,
right_text: String,
text: String,
}
#[derive(Clone, Msg)]
pub enum Msg {
Cancel,
Concat,
DataAvailable(String),
DataCleared,
LeftChanged(String),
RightChanged(String),
Quit,
}
#[widget]
impl Widget for Win {
fn model(relm: &Relm<Self>, (): ()) -> Model {
Model {
left_text: String::new(),
right_text: String::new(),
relm: relm.clone(),
text: String::new(),
}
}
fn update(&mut self, event: Msg) {
match event {
Cancel => {
self.model.left_text = String::new();
self.model.right_text = String::new();
self.model.text = String::new();
self.model.relm.stream().emit(DataCleared);
},
Concat => {
self.model.text = format!("{}{}", self.model.left_text, self.model.right_text);
self.model.relm.stream().emit(DataAvailable(self.model.text.clone()));
},
// To be listened to by the user.
DataAvailable(_) | DataCleared => (),
LeftChanged(text) => self.model.left_text = text,
RightChanged(text) => self.model.right_text = text,
Quit => gtk::main_quit(),
}
}
view! {
#[name="window"]
gtk::Window {
gtk::Box {
gtk::Box {
#[name="left_entry"]
gtk::Entry {
text: &self.model.left_text,
changed(entry) => LeftChanged(entry.text().to_string()),
},
#[name="right_entry"]
gtk::Entry {
text: &self.model.right_text,
changed(entry) => RightChanged(entry.text().to_string()),
},
orientation: Horizontal,
},
gtk::ButtonBox {
#[name="concat_button"]
gtk::Button {
clicked => Concat,
label: "Concat",
},
#[name="cancel_button"]
gtk::Button {
clicked => Cancel,
label: "Cancel",
},
orientation: Horizontal,
},
orientation: Vertical,
#[name="label"]
gtk::Label {
label: &self.model.text,
},
},
delete_event(_, _) => (Quit, Inhibit(false)),
}
}
}
#[cfg(test)]
mod tests {
use gdk::keys::constants as key;
use gtk::prelude::{
EntryExt,
GtkWindowExt,
LabelExt,
WidgetExt,
};
use gtk_test::{
assert_text,
focus,
};
use relm_test::{
enter_key,
enter_keys,
relm_observer_new,
relm_observer_wait,
};
use crate::Msg::{DataAvailable, DataCleared};
use crate::Win;
#[test]
fn | () {
let (component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed");
let cancel_button = &widgets.cancel_button;
let concat_button = &widgets.concat_button;
let label = &widgets.label;
let left_entry = &widgets.left_entry;
let right_entry = &widgets.right_entry;
let window = &widgets.window;
let available_observer = relm_observer_new!(component, DataAvailable(_));
let cleared_observer = relm_observer_new!(component, DataCleared);
assert_text!(label, "");
enter_keys(&window.focused_widget().expect("focused widget"), "left");
enter_key(window, key::Tab);
assert!(right_entry.has_focus());
enter_keys(&window.focused_widget().expect("focused widget"), "right");
enter_key(window, key::Tab);
assert!(concat_button.has_focus());
enter_key(
&window.focused_widget().expect("focused widget"),
key::space,
);
assert_text!(label, "leftright");
enter_key(window, key::Tab);
assert!(cancel_button.has_focus());
enter_key(
&window.focused_widget().expect("focused widget"),
key::space,
);
assert_text!(label, "");
assert_text!(left_entry, "");
assert_text!(right_entry, "");
focus(left_entry);
assert!(left_entry.has_focus());
focus(right_entry);
assert!(right_entry.has_focus());
relm_observer_wait!(let DataAvailable(text) = available_observer);
assert_eq!(text, "leftright");
relm_observer_wait!(let DataCleared = cleared_observer);
}
}
| label_change | identifier_name |
buttons-input.rs | /*
* Copyright (c) 2018 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use gtk::{
EditableSignals, | prelude::LabelExt,
prelude::OrientableExt,
prelude::WidgetExt,
};
use gtk::Orientation::{Horizontal, Vertical};
use relm::{Relm, Widget};
use relm_derive::{Msg, widget};
use self::Msg::*;
pub struct Model {
left_text: String,
relm: Relm<Win>,
right_text: String,
text: String,
}
#[derive(Clone, Msg)]
pub enum Msg {
Cancel,
Concat,
DataAvailable(String),
DataCleared,
LeftChanged(String),
RightChanged(String),
Quit,
}
#[widget]
impl Widget for Win {
fn model(relm: &Relm<Self>, (): ()) -> Model {
Model {
left_text: String::new(),
right_text: String::new(),
relm: relm.clone(),
text: String::new(),
}
}
fn update(&mut self, event: Msg) {
match event {
Cancel => {
self.model.left_text = String::new();
self.model.right_text = String::new();
self.model.text = String::new();
self.model.relm.stream().emit(DataCleared);
},
Concat => {
self.model.text = format!("{}{}", self.model.left_text, self.model.right_text);
self.model.relm.stream().emit(DataAvailable(self.model.text.clone()));
},
// To be listened to by the user.
DataAvailable(_) | DataCleared => (),
LeftChanged(text) => self.model.left_text = text,
RightChanged(text) => self.model.right_text = text,
Quit => gtk::main_quit(),
}
}
view! {
#[name="window"]
gtk::Window {
gtk::Box {
gtk::Box {
#[name="left_entry"]
gtk::Entry {
text: &self.model.left_text,
changed(entry) => LeftChanged(entry.text().to_string()),
},
#[name="right_entry"]
gtk::Entry {
text: &self.model.right_text,
changed(entry) => RightChanged(entry.text().to_string()),
},
orientation: Horizontal,
},
gtk::ButtonBox {
#[name="concat_button"]
gtk::Button {
clicked => Concat,
label: "Concat",
},
#[name="cancel_button"]
gtk::Button {
clicked => Cancel,
label: "Cancel",
},
orientation: Horizontal,
},
orientation: Vertical,
#[name="label"]
gtk::Label {
label: &self.model.text,
},
},
delete_event(_, _) => (Quit, Inhibit(false)),
}
}
}
#[cfg(test)]
mod tests {
use gdk::keys::constants as key;
use gtk::prelude::{
EntryExt,
GtkWindowExt,
LabelExt,
WidgetExt,
};
use gtk_test::{
assert_text,
focus,
};
use relm_test::{
enter_key,
enter_keys,
relm_observer_new,
relm_observer_wait,
};
use crate::Msg::{DataAvailable, DataCleared};
use crate::Win;
#[test]
fn label_change() {
let (component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed");
let cancel_button = &widgets.cancel_button;
let concat_button = &widgets.concat_button;
let label = &widgets.label;
let left_entry = &widgets.left_entry;
let right_entry = &widgets.right_entry;
let window = &widgets.window;
let available_observer = relm_observer_new!(component, DataAvailable(_));
let cleared_observer = relm_observer_new!(component, DataCleared);
assert_text!(label, "");
enter_keys(&window.focused_widget().expect("focused widget"), "left");
enter_key(window, key::Tab);
assert!(right_entry.has_focus());
enter_keys(&window.focused_widget().expect("focused widget"), "right");
enter_key(window, key::Tab);
assert!(concat_button.has_focus());
enter_key(
&window.focused_widget().expect("focused widget"),
key::space,
);
assert_text!(label, "leftright");
enter_key(window, key::Tab);
assert!(cancel_button.has_focus());
enter_key(
&window.focused_widget().expect("focused widget"),
key::space,
);
assert_text!(label, "");
assert_text!(left_entry, "");
assert_text!(right_entry, "");
focus(left_entry);
assert!(left_entry.has_focus());
focus(right_entry);
assert!(right_entry.has_focus());
relm_observer_wait!(let DataAvailable(text) = available_observer);
assert_eq!(text, "leftright");
relm_observer_wait!(let DataCleared = cleared_observer);
}
} | Inhibit,
prelude::ButtonExt,
prelude::EntryExt, | random_line_split |
buttons-input.rs | /*
* Copyright (c) 2018 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use gtk::{
EditableSignals,
Inhibit,
prelude::ButtonExt,
prelude::EntryExt,
prelude::LabelExt,
prelude::OrientableExt,
prelude::WidgetExt,
};
use gtk::Orientation::{Horizontal, Vertical};
use relm::{Relm, Widget};
use relm_derive::{Msg, widget};
use self::Msg::*;
pub struct Model {
left_text: String,
relm: Relm<Win>,
right_text: String,
text: String,
}
#[derive(Clone, Msg)]
pub enum Msg {
Cancel,
Concat,
DataAvailable(String),
DataCleared,
LeftChanged(String),
RightChanged(String),
Quit,
}
#[widget]
impl Widget for Win {
fn model(relm: &Relm<Self>, (): ()) -> Model |
fn update(&mut self, event: Msg) {
match event {
Cancel => {
self.model.left_text = String::new();
self.model.right_text = String::new();
self.model.text = String::new();
self.model.relm.stream().emit(DataCleared);
},
Concat => {
self.model.text = format!("{}{}", self.model.left_text, self.model.right_text);
self.model.relm.stream().emit(DataAvailable(self.model.text.clone()));
},
// To be listened to by the user.
DataAvailable(_) | DataCleared => (),
LeftChanged(text) => self.model.left_text = text,
RightChanged(text) => self.model.right_text = text,
Quit => gtk::main_quit(),
}
}
view! {
#[name="window"]
gtk::Window {
gtk::Box {
gtk::Box {
#[name="left_entry"]
gtk::Entry {
text: &self.model.left_text,
changed(entry) => LeftChanged(entry.text().to_string()),
},
#[name="right_entry"]
gtk::Entry {
text: &self.model.right_text,
changed(entry) => RightChanged(entry.text().to_string()),
},
orientation: Horizontal,
},
gtk::ButtonBox {
#[name="concat_button"]
gtk::Button {
clicked => Concat,
label: "Concat",
},
#[name="cancel_button"]
gtk::Button {
clicked => Cancel,
label: "Cancel",
},
orientation: Horizontal,
},
orientation: Vertical,
#[name="label"]
gtk::Label {
label: &self.model.text,
},
},
delete_event(_, _) => (Quit, Inhibit(false)),
}
}
}
#[cfg(test)]
mod tests {
use gdk::keys::constants as key;
use gtk::prelude::{
EntryExt,
GtkWindowExt,
LabelExt,
WidgetExt,
};
use gtk_test::{
assert_text,
focus,
};
use relm_test::{
enter_key,
enter_keys,
relm_observer_new,
relm_observer_wait,
};
use crate::Msg::{DataAvailable, DataCleared};
use crate::Win;
#[test]
fn label_change() {
let (component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed");
let cancel_button = &widgets.cancel_button;
let concat_button = &widgets.concat_button;
let label = &widgets.label;
let left_entry = &widgets.left_entry;
let right_entry = &widgets.right_entry;
let window = &widgets.window;
let available_observer = relm_observer_new!(component, DataAvailable(_));
let cleared_observer = relm_observer_new!(component, DataCleared);
assert_text!(label, "");
enter_keys(&window.focused_widget().expect("focused widget"), "left");
enter_key(window, key::Tab);
assert!(right_entry.has_focus());
enter_keys(&window.focused_widget().expect("focused widget"), "right");
enter_key(window, key::Tab);
assert!(concat_button.has_focus());
enter_key(
&window.focused_widget().expect("focused widget"),
key::space,
);
assert_text!(label, "leftright");
enter_key(window, key::Tab);
assert!(cancel_button.has_focus());
enter_key(
&window.focused_widget().expect("focused widget"),
key::space,
);
assert_text!(label, "");
assert_text!(left_entry, "");
assert_text!(right_entry, "");
focus(left_entry);
assert!(left_entry.has_focus());
focus(right_entry);
assert!(right_entry.has_focus());
relm_observer_wait!(let DataAvailable(text) = available_observer);
assert_eq!(text, "leftright");
relm_observer_wait!(let DataCleared = cleared_observer);
}
}
| {
Model {
left_text: String::new(),
right_text: String::new(),
relm: relm.clone(),
text: String::new(),
}
} | identifier_body |
setup.py | import setuptools
import sys
import numpy as np
# NOTE: If edt.cpp does not exist:
# cython -3 --fast-fail -v --cplus edt.pyx
extra_compile_args = []
if sys.platform == 'win32':
extra_compile_args += [
'/std:c++11', '/O2'
]
else:
extra_compile_args += [
'-std=c++11', '-O3', '-ffast-math', '-pthread'
]
if sys.platform == 'darwin':
|
setuptools.setup(
setup_requires=['pbr'],
python_requires="~=3.6", # >= 3.6 < 4.0
ext_modules=[
setuptools.Extension(
'edt',
sources=[ 'edt.cpp' ],
language='c++',
include_dirs=[ np.get_include() ],
extra_compile_args=extra_compile_args,
),
],
long_description_content_type='text/markdown',
pbr=True
) | extra_compile_args += [ '-stdlib=libc++', '-mmacosx-version-min=10.9' ] | conditional_block |
setup.py | import setuptools
import sys
import numpy as np
# NOTE: If edt.cpp does not exist:
# cython -3 --fast-fail -v --cplus edt.pyx
extra_compile_args = []
if sys.platform == 'win32':
extra_compile_args += [
'/std:c++11', '/O2'
]
else:
extra_compile_args += [
'-std=c++11', '-O3', '-ffast-math', '-pthread'
]
if sys.platform == 'darwin':
extra_compile_args += [ '-stdlib=libc++', '-mmacosx-version-min=10.9' ]
setuptools.setup(
setup_requires=['pbr'],
python_requires="~=3.6", # >= 3.6 < 4.0
ext_modules=[ | setuptools.Extension(
'edt',
sources=[ 'edt.cpp' ],
language='c++',
include_dirs=[ np.get_include() ],
extra_compile_args=extra_compile_args,
),
],
long_description_content_type='text/markdown',
pbr=True
) | random_line_split | |
plugin.js | /**
* plugin.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
tinymce.PluginManager.add('link', function(editor) {
var attachState = {};
function createLinkList(callback) {
return function() {
var linkList = editor.settings.link_list;
if (typeof linkList == "string") {
tinymce.util.XHR.send({
url: linkList,
success: function(text) {
callback(tinymce.util.JSON.parse(text));
}
});
} else if (typeof linkList == "function") {
linkList(callback);
} else {
callback(linkList);
}
};
}
function buildListItems(inputList, itemCallback, startItems) {
function appendItems(values, output) {
output = output || [];
tinymce.each(values, function(item) {
var menuItem = {text: item.text || item.title};
if (item.menu) {
menuItem.menu = appendItems(item.menu);
} else {
menuItem.value = item.value;
if (itemCallback) {
itemCallback(menuItem);
}
}
output.push(menuItem);
});
return output;
}
return appendItems(inputList, startItems || []);
}
function showDialog(linkList) {
var data = {}, selection = editor.selection, dom = editor.dom, selectedElm, anchorElm, initialText;
var win, onlyText, textListCtrl, linkListCtrl, relListCtrl, targetListCtrl, classListCtrl, linkTitleCtrl, value;
function linkListChangeHandler(e) {
var textCtrl = win.find('#text');
if (!textCtrl.value() || (e.lastControl && textCtrl.value() == e.lastControl.text())) {
textCtrl.value(e.control.text());
}
win.find('#href').value(e.control.value());
}
function buildAnchorListControl(url) {
var anchorList = [];
tinymce.each(editor.dom.select('a:not([href])'), function(anchor) {
var id = anchor.name || anchor.id;
if (id) {
anchorList.push({
text: id,
value: '#' + id,
selected: url.indexOf('#' + id) != -1
});
}
});
if (anchorList.length) {
anchorList.unshift({text: 'None', value: ''});
return {
name: 'anchor',
type: 'listbox',
label: 'Anchors',
values: anchorList,
onselect: linkListChangeHandler
};
}
}
function updateText() {
if (!initialText && data.text.length === 0 && onlyText) {
this.parent().parent().find('#text')[0].value(this.value());
}
}
function urlChange(e) {
var meta = e.meta || {};
if (linkListCtrl) {
linkListCtrl.value(editor.convertURL(this.value(), 'href'));
}
tinymce.each(e.meta, function(value, key) {
var inp = win.find('#' + key);
if (key === 'text') {
if (initialText.length === 0) {
inp.value(value);
data.text = value;
}
} else {
inp.value(value);
}
});
if (meta.attach) {
attachState = {
href: this.value(),
attach: meta.attach
};
}
if (!meta.text) {
updateText.call(this);
}
}
function isOnlyTextSelected(anchorElm) {
var html = selection.getContent();
// Partial html and not a fully selected anchor element
if (/</.test(html) && (!/^<a [^>]+>[^<]+<\/a>$/.test(html) || html.indexOf('href=') == -1)) {
return false;
}
if (anchorElm) {
var nodes = anchorElm.childNodes, i;
if (nodes.length === 0) {
return false;
}
for (i = nodes.length - 1; i >= 0; i--) {
if (nodes[i].nodeType != 3) {
return false;
}
}
}
return true;
}
selectedElm = selection.getNode();
anchorElm = dom.getParent(selectedElm, 'a[href]');
onlyText = isOnlyTextSelected();
data.text = initialText = anchorElm ? (anchorElm.innerText || anchorElm.textContent) : selection.getContent({format: 'text'});
data.href = anchorElm ? dom.getAttrib(anchorElm, 'href') : '';
if (anchorElm) {
data.target = dom.getAttrib(anchorElm, 'target');
} else if (editor.settings.default_link_target) {
data.target = editor.settings.default_link_target;
}
if ((value = dom.getAttrib(anchorElm, 'rel'))) {
data.rel = value;
}
if ((value = dom.getAttrib(anchorElm, 'class'))) {
data['class'] = value;
}
if ((value = dom.getAttrib(anchorElm, 'title'))) {
data.title = value;
}
if (onlyText) {
textListCtrl = {
name: 'text',
type: 'textbox',
size: 40,
label: 'Text to display',
onchange: function() {
data.text = this.value();
}
};
}
if (linkList) {
linkListCtrl = {
type: 'listbox',
label: 'Link list',
values: buildListItems(
linkList,
function(item) {
item.value = editor.convertURL(item.value || item.url, 'href');
},
[{text: 'None', value: ''}]
),
onselect: linkListChangeHandler,
value: editor.convertURL(data.href, 'href'),
onPostRender: function() {
/*eslint consistent-this:0*/
linkListCtrl = this;
}
};
}
if (editor.settings.target_list !== false) {
if (!editor.settings.target_list) {
editor.settings.target_list = [
{text: 'None', value: ''},
{text: 'New window', value: '_blank'}
];
}
targetListCtrl = {
name: 'target',
type: 'listbox',
label: 'Target',
values: buildListItems(editor.settings.target_list)
};
}
if (editor.settings.rel_list) {
relListCtrl = {
name: 'rel',
type: 'listbox',
label: 'Rel',
values: buildListItems(editor.settings.rel_list)
};
}
if (editor.settings.link_class_list) {
classListCtrl = {
name: 'class',
type: 'listbox',
label: 'Class',
values: buildListItems(
editor.settings.link_class_list,
function(item) {
if (item.value) {
item.textStyle = function() {
return editor.formatter.getCssText({inline: 'a', classes: [item.value]});
};
}
}
)
};
}
if (editor.settings.link_title !== false) {
linkTitleCtrl = {
name: 'title',
type: 'textbox',
label: 'Title',
value: data.title
};
}
win = editor.windowManager.open({
title: 'Insert link',
data: data,
body: [
{
name: 'href',
type: 'filepicker',
filetype: 'file',
size: 40,
autofocus: true,
label: 'Url',
onchange: urlChange,
onkeyup: updateText
},
textListCtrl,
linkTitleCtrl,
buildAnchorListControl(data.href),
linkListCtrl,
relListCtrl,
targetListCtrl,
classListCtrl
],
onSubmit: function(e) {
/*eslint dot-notation: 0*/
var href;
data = tinymce.extend(data, e.data);
href = data.href;
// Delay confirm since onSubmit will move focus
function delayedConfirm(message, callback) |
function createLink() {
var linkAttrs = {
href: href,
target: data.target ? data.target : null,
rel: data.rel ? data.rel : null,
"class": data["class"] ? data["class"] : null,
title: data.title ? data.title : null
};
if (href === attachState.href) {
attachState.attach();
attachState = {};
}
if (anchorElm) {
editor.focus();
if (onlyText && data.text != initialText) {
if ("innerText" in anchorElm) {
anchorElm.innerText = data.text;
} else {
anchorElm.textContent = data.text;
}
}
dom.setAttribs(anchorElm, linkAttrs);
selection.select(anchorElm);
editor.undoManager.add();
} else {
if (onlyText) {
editor.insertContent(dom.createHTML('a', linkAttrs, dom.encode(data.text)));
} else {
editor.execCommand('mceInsertLink', false, linkAttrs);
}
}
}
function insertLink() {
editor.undoManager.transact(createLink);
}
if (!href) {
editor.execCommand('unlink');
return;
}
// Is email and not //user@domain.com
if (href.indexOf('@') > 0 && href.indexOf('//') == -1 && href.indexOf('mailto:') == -1) {
delayedConfirm(
'The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?',
function(state) {
if (state) {
href = 'mailto:' + href;
}
insertLink();
}
);
return;
}
// Is not protocol prefixed
if ((editor.settings.link_assume_external_targets && !/^\w+:/i.test(href)) ||
(!editor.settings.link_assume_external_targets && /^\s*www[\.|\d\.]/i.test(href))) {
delayedConfirm(
'The URL you entered seems to be an external link. Do you want to add the required http:// prefix?',
function(state) {
if (state) {
href = 'http://' + href;
}
insertLink();
}
);
return;
}
insertLink();
}
});
}
editor.addButton('link', {
icon: 'link',
tooltip: 'Insert/edit link',
shortcut: 'Meta+K',
onclick: createLinkList(showDialog),
stateSelector: 'a[href]'
});
editor.addButton('unlink', {
icon: 'unlink',
tooltip: 'Remove link',
cmd: 'unlink',
stateSelector: 'a[href]'
});
editor.addShortcut('Meta+K', '', createLinkList(showDialog));
editor.addCommand('mceLink', createLinkList(showDialog));
this.showDialog = showDialog;
editor.addMenuItem('link', {
icon: 'link',
text: 'Insert/edit link',
shortcut: 'Meta+K',
onclick: createLinkList(showDialog),
stateSelector: 'a[href]',
context: 'insert',
prependToContext: true
});
});
| {
var rng = editor.selection.getRng();
tinymce.util.Delay.setEditorTimeout(editor, function() {
editor.windowManager.confirm(message, function(state) {
editor.selection.setRng(rng);
callback(state);
});
});
} | identifier_body |
plugin.js | /**
* plugin.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
tinymce.PluginManager.add('link', function(editor) {
var attachState = {};
function createLinkList(callback) {
return function() {
var linkList = editor.settings.link_list;
if (typeof linkList == "string") {
tinymce.util.XHR.send({
url: linkList,
success: function(text) {
callback(tinymce.util.JSON.parse(text));
}
});
} else if (typeof linkList == "function") {
linkList(callback);
} else {
callback(linkList);
}
};
}
function buildListItems(inputList, itemCallback, startItems) {
function appendItems(values, output) {
output = output || [];
tinymce.each(values, function(item) {
var menuItem = {text: item.text || item.title};
if (item.menu) {
menuItem.menu = appendItems(item.menu);
} else {
menuItem.value = item.value;
if (itemCallback) {
itemCallback(menuItem);
}
}
output.push(menuItem);
});
return output;
}
return appendItems(inputList, startItems || []);
}
function | (linkList) {
var data = {}, selection = editor.selection, dom = editor.dom, selectedElm, anchorElm, initialText;
var win, onlyText, textListCtrl, linkListCtrl, relListCtrl, targetListCtrl, classListCtrl, linkTitleCtrl, value;
function linkListChangeHandler(e) {
var textCtrl = win.find('#text');
if (!textCtrl.value() || (e.lastControl && textCtrl.value() == e.lastControl.text())) {
textCtrl.value(e.control.text());
}
win.find('#href').value(e.control.value());
}
function buildAnchorListControl(url) {
var anchorList = [];
tinymce.each(editor.dom.select('a:not([href])'), function(anchor) {
var id = anchor.name || anchor.id;
if (id) {
anchorList.push({
text: id,
value: '#' + id,
selected: url.indexOf('#' + id) != -1
});
}
});
if (anchorList.length) {
anchorList.unshift({text: 'None', value: ''});
return {
name: 'anchor',
type: 'listbox',
label: 'Anchors',
values: anchorList,
onselect: linkListChangeHandler
};
}
}
function updateText() {
if (!initialText && data.text.length === 0 && onlyText) {
this.parent().parent().find('#text')[0].value(this.value());
}
}
function urlChange(e) {
var meta = e.meta || {};
if (linkListCtrl) {
linkListCtrl.value(editor.convertURL(this.value(), 'href'));
}
tinymce.each(e.meta, function(value, key) {
var inp = win.find('#' + key);
if (key === 'text') {
if (initialText.length === 0) {
inp.value(value);
data.text = value;
}
} else {
inp.value(value);
}
});
if (meta.attach) {
attachState = {
href: this.value(),
attach: meta.attach
};
}
if (!meta.text) {
updateText.call(this);
}
}
function isOnlyTextSelected(anchorElm) {
var html = selection.getContent();
// Partial html and not a fully selected anchor element
if (/</.test(html) && (!/^<a [^>]+>[^<]+<\/a>$/.test(html) || html.indexOf('href=') == -1)) {
return false;
}
if (anchorElm) {
var nodes = anchorElm.childNodes, i;
if (nodes.length === 0) {
return false;
}
for (i = nodes.length - 1; i >= 0; i--) {
if (nodes[i].nodeType != 3) {
return false;
}
}
}
return true;
}
selectedElm = selection.getNode();
anchorElm = dom.getParent(selectedElm, 'a[href]');
onlyText = isOnlyTextSelected();
data.text = initialText = anchorElm ? (anchorElm.innerText || anchorElm.textContent) : selection.getContent({format: 'text'});
data.href = anchorElm ? dom.getAttrib(anchorElm, 'href') : '';
if (anchorElm) {
data.target = dom.getAttrib(anchorElm, 'target');
} else if (editor.settings.default_link_target) {
data.target = editor.settings.default_link_target;
}
if ((value = dom.getAttrib(anchorElm, 'rel'))) {
data.rel = value;
}
if ((value = dom.getAttrib(anchorElm, 'class'))) {
data['class'] = value;
}
if ((value = dom.getAttrib(anchorElm, 'title'))) {
data.title = value;
}
if (onlyText) {
textListCtrl = {
name: 'text',
type: 'textbox',
size: 40,
label: 'Text to display',
onchange: function() {
data.text = this.value();
}
};
}
if (linkList) {
linkListCtrl = {
type: 'listbox',
label: 'Link list',
values: buildListItems(
linkList,
function(item) {
item.value = editor.convertURL(item.value || item.url, 'href');
},
[{text: 'None', value: ''}]
),
onselect: linkListChangeHandler,
value: editor.convertURL(data.href, 'href'),
onPostRender: function() {
/*eslint consistent-this:0*/
linkListCtrl = this;
}
};
}
if (editor.settings.target_list !== false) {
if (!editor.settings.target_list) {
editor.settings.target_list = [
{text: 'None', value: ''},
{text: 'New window', value: '_blank'}
];
}
targetListCtrl = {
name: 'target',
type: 'listbox',
label: 'Target',
values: buildListItems(editor.settings.target_list)
};
}
if (editor.settings.rel_list) {
relListCtrl = {
name: 'rel',
type: 'listbox',
label: 'Rel',
values: buildListItems(editor.settings.rel_list)
};
}
if (editor.settings.link_class_list) {
classListCtrl = {
name: 'class',
type: 'listbox',
label: 'Class',
values: buildListItems(
editor.settings.link_class_list,
function(item) {
if (item.value) {
item.textStyle = function() {
return editor.formatter.getCssText({inline: 'a', classes: [item.value]});
};
}
}
)
};
}
if (editor.settings.link_title !== false) {
linkTitleCtrl = {
name: 'title',
type: 'textbox',
label: 'Title',
value: data.title
};
}
win = editor.windowManager.open({
title: 'Insert link',
data: data,
body: [
{
name: 'href',
type: 'filepicker',
filetype: 'file',
size: 40,
autofocus: true,
label: 'Url',
onchange: urlChange,
onkeyup: updateText
},
textListCtrl,
linkTitleCtrl,
buildAnchorListControl(data.href),
linkListCtrl,
relListCtrl,
targetListCtrl,
classListCtrl
],
onSubmit: function(e) {
/*eslint dot-notation: 0*/
var href;
data = tinymce.extend(data, e.data);
href = data.href;
// Delay confirm since onSubmit will move focus
function delayedConfirm(message, callback) {
var rng = editor.selection.getRng();
tinymce.util.Delay.setEditorTimeout(editor, function() {
editor.windowManager.confirm(message, function(state) {
editor.selection.setRng(rng);
callback(state);
});
});
}
function createLink() {
var linkAttrs = {
href: href,
target: data.target ? data.target : null,
rel: data.rel ? data.rel : null,
"class": data["class"] ? data["class"] : null,
title: data.title ? data.title : null
};
if (href === attachState.href) {
attachState.attach();
attachState = {};
}
if (anchorElm) {
editor.focus();
if (onlyText && data.text != initialText) {
if ("innerText" in anchorElm) {
anchorElm.innerText = data.text;
} else {
anchorElm.textContent = data.text;
}
}
dom.setAttribs(anchorElm, linkAttrs);
selection.select(anchorElm);
editor.undoManager.add();
} else {
if (onlyText) {
editor.insertContent(dom.createHTML('a', linkAttrs, dom.encode(data.text)));
} else {
editor.execCommand('mceInsertLink', false, linkAttrs);
}
}
}
function insertLink() {
editor.undoManager.transact(createLink);
}
if (!href) {
editor.execCommand('unlink');
return;
}
// Is email and not //user@domain.com
if (href.indexOf('@') > 0 && href.indexOf('//') == -1 && href.indexOf('mailto:') == -1) {
delayedConfirm(
'The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?',
function(state) {
if (state) {
href = 'mailto:' + href;
}
insertLink();
}
);
return;
}
// Is not protocol prefixed
if ((editor.settings.link_assume_external_targets && !/^\w+:/i.test(href)) ||
(!editor.settings.link_assume_external_targets && /^\s*www[\.|\d\.]/i.test(href))) {
delayedConfirm(
'The URL you entered seems to be an external link. Do you want to add the required http:// prefix?',
function(state) {
if (state) {
href = 'http://' + href;
}
insertLink();
}
);
return;
}
insertLink();
}
});
}
editor.addButton('link', {
icon: 'link',
tooltip: 'Insert/edit link',
shortcut: 'Meta+K',
onclick: createLinkList(showDialog),
stateSelector: 'a[href]'
});
editor.addButton('unlink', {
icon: 'unlink',
tooltip: 'Remove link',
cmd: 'unlink',
stateSelector: 'a[href]'
});
editor.addShortcut('Meta+K', '', createLinkList(showDialog));
editor.addCommand('mceLink', createLinkList(showDialog));
this.showDialog = showDialog;
editor.addMenuItem('link', {
icon: 'link',
text: 'Insert/edit link',
shortcut: 'Meta+K',
onclick: createLinkList(showDialog),
stateSelector: 'a[href]',
context: 'insert',
prependToContext: true
});
});
| showDialog | identifier_name |
plugin.js | /**
* plugin.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
tinymce.PluginManager.add('link', function(editor) {
var attachState = {};
function createLinkList(callback) {
return function() {
var linkList = editor.settings.link_list;
if (typeof linkList == "string") {
tinymce.util.XHR.send({
url: linkList,
success: function(text) {
callback(tinymce.util.JSON.parse(text));
}
});
} else if (typeof linkList == "function") {
linkList(callback);
} else {
callback(linkList);
}
};
}
function buildListItems(inputList, itemCallback, startItems) {
function appendItems(values, output) {
output = output || [];
tinymce.each(values, function(item) {
var menuItem = {text: item.text || item.title};
if (item.menu) {
menuItem.menu = appendItems(item.menu);
} else {
menuItem.value = item.value;
if (itemCallback) {
itemCallback(menuItem);
}
}
output.push(menuItem);
});
return output;
}
return appendItems(inputList, startItems || []);
}
function showDialog(linkList) {
var data = {}, selection = editor.selection, dom = editor.dom, selectedElm, anchorElm, initialText;
var win, onlyText, textListCtrl, linkListCtrl, relListCtrl, targetListCtrl, classListCtrl, linkTitleCtrl, value;
function linkListChangeHandler(e) {
var textCtrl = win.find('#text');
if (!textCtrl.value() || (e.lastControl && textCtrl.value() == e.lastControl.text())) {
textCtrl.value(e.control.text());
}
win.find('#href').value(e.control.value());
}
function buildAnchorListControl(url) {
var anchorList = [];
tinymce.each(editor.dom.select('a:not([href])'), function(anchor) {
var id = anchor.name || anchor.id;
if (id) {
anchorList.push({
text: id,
value: '#' + id,
selected: url.indexOf('#' + id) != -1
});
}
});
if (anchorList.length) {
anchorList.unshift({text: 'None', value: ''});
return {
name: 'anchor',
type: 'listbox',
label: 'Anchors',
values: anchorList,
onselect: linkListChangeHandler
};
}
}
function updateText() {
if (!initialText && data.text.length === 0 && onlyText) {
this.parent().parent().find('#text')[0].value(this.value());
}
}
function urlChange(e) {
var meta = e.meta || {};
if (linkListCtrl) {
linkListCtrl.value(editor.convertURL(this.value(), 'href'));
}
tinymce.each(e.meta, function(value, key) {
var inp = win.find('#' + key);
if (key === 'text') {
if (initialText.length === 0) {
inp.value(value);
data.text = value;
}
} else {
inp.value(value);
}
});
if (meta.attach) {
attachState = {
href: this.value(),
attach: meta.attach
};
}
if (!meta.text) {
updateText.call(this);
}
}
function isOnlyTextSelected(anchorElm) {
var html = selection.getContent();
// Partial html and not a fully selected anchor element
if (/</.test(html) && (!/^<a [^>]+>[^<]+<\/a>$/.test(html) || html.indexOf('href=') == -1)) {
return false;
}
if (anchorElm) {
var nodes = anchorElm.childNodes, i;
if (nodes.length === 0) {
return false;
}
for (i = nodes.length - 1; i >= 0; i--) {
if (nodes[i].nodeType != 3) {
return false;
}
}
}
return true;
}
selectedElm = selection.getNode();
anchorElm = dom.getParent(selectedElm, 'a[href]');
onlyText = isOnlyTextSelected();
data.text = initialText = anchorElm ? (anchorElm.innerText || anchorElm.textContent) : selection.getContent({format: 'text'});
data.href = anchorElm ? dom.getAttrib(anchorElm, 'href') : '';
if (anchorElm) {
data.target = dom.getAttrib(anchorElm, 'target');
} else if (editor.settings.default_link_target) {
data.target = editor.settings.default_link_target;
}
if ((value = dom.getAttrib(anchorElm, 'rel'))) {
data.rel = value;
}
if ((value = dom.getAttrib(anchorElm, 'class'))) {
data['class'] = value;
}
if ((value = dom.getAttrib(anchorElm, 'title'))) {
data.title = value;
}
if (onlyText) {
textListCtrl = {
name: 'text',
type: 'textbox',
size: 40,
label: 'Text to display',
onchange: function() {
data.text = this.value();
}
};
}
if (linkList) {
linkListCtrl = {
type: 'listbox',
label: 'Link list',
values: buildListItems(
linkList,
function(item) {
item.value = editor.convertURL(item.value || item.url, 'href');
},
[{text: 'None', value: ''}]
),
onselect: linkListChangeHandler,
value: editor.convertURL(data.href, 'href'),
onPostRender: function() {
/*eslint consistent-this:0*/
linkListCtrl = this;
}
};
}
if (editor.settings.target_list !== false) {
if (!editor.settings.target_list) {
editor.settings.target_list = [
{text: 'None', value: ''},
{text: 'New window', value: '_blank'}
];
}
targetListCtrl = {
name: 'target',
type: 'listbox',
label: 'Target',
values: buildListItems(editor.settings.target_list)
};
}
if (editor.settings.rel_list) {
relListCtrl = {
name: 'rel',
type: 'listbox',
label: 'Rel',
values: buildListItems(editor.settings.rel_list)
};
}
if (editor.settings.link_class_list) {
classListCtrl = {
name: 'class',
type: 'listbox',
label: 'Class',
values: buildListItems(
editor.settings.link_class_list,
function(item) {
if (item.value) {
item.textStyle = function() {
return editor.formatter.getCssText({inline: 'a', classes: [item.value]});
};
}
}
)
};
}
if (editor.settings.link_title !== false) {
linkTitleCtrl = {
name: 'title',
type: 'textbox',
label: 'Title',
value: data.title
};
}
win = editor.windowManager.open({
title: 'Insert link',
data: data,
body: [
{
name: 'href',
type: 'filepicker',
filetype: 'file',
size: 40,
autofocus: true,
label: 'Url',
onchange: urlChange,
onkeyup: updateText
},
textListCtrl,
linkTitleCtrl,
buildAnchorListControl(data.href),
linkListCtrl,
relListCtrl,
targetListCtrl,
classListCtrl
],
onSubmit: function(e) {
/*eslint dot-notation: 0*/
var href;
data = tinymce.extend(data, e.data);
href = data.href;
// Delay confirm since onSubmit will move focus
function delayedConfirm(message, callback) {
var rng = editor.selection.getRng();
tinymce.util.Delay.setEditorTimeout(editor, function() {
editor.windowManager.confirm(message, function(state) {
editor.selection.setRng(rng);
callback(state);
});
});
}
function createLink() {
var linkAttrs = {
href: href,
target: data.target ? data.target : null,
rel: data.rel ? data.rel : null,
"class": data["class"] ? data["class"] : null,
title: data.title ? data.title : null
};
if (href === attachState.href) {
attachState.attach();
attachState = {};
}
if (anchorElm) {
editor.focus();
if (onlyText && data.text != initialText) {
if ("innerText" in anchorElm) {
anchorElm.innerText = data.text;
} else {
anchorElm.textContent = data.text;
}
}
dom.setAttribs(anchorElm, linkAttrs);
selection.select(anchorElm);
editor.undoManager.add();
} else {
if (onlyText) {
editor.insertContent(dom.createHTML('a', linkAttrs, dom.encode(data.text)));
} else {
editor.execCommand('mceInsertLink', false, linkAttrs);
}
}
}
function insertLink() {
editor.undoManager.transact(createLink);
}
if (!href) {
editor.execCommand('unlink');
return;
}
// Is email and not //user@domain.com
if (href.indexOf('@') > 0 && href.indexOf('//') == -1 && href.indexOf('mailto:') == -1) {
delayedConfirm(
'The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?',
function(state) {
if (state) {
href = 'mailto:' + href;
}
insertLink();
}
);
return;
}
// Is not protocol prefixed
if ((editor.settings.link_assume_external_targets && !/^\w+:/i.test(href)) ||
(!editor.settings.link_assume_external_targets && /^\s*www[\.|\d\.]/i.test(href))) {
delayedConfirm(
'The URL you entered seems to be an external link. Do you want to add the required http:// prefix?',
function(state) {
if (state) {
href = 'http://' + href;
}
insertLink();
}
);
return;
}
insertLink();
}
});
}
editor.addButton('link', {
icon: 'link',
tooltip: 'Insert/edit link',
shortcut: 'Meta+K',
onclick: createLinkList(showDialog),
stateSelector: 'a[href]'
});
editor.addButton('unlink', {
icon: 'unlink',
tooltip: 'Remove link',
cmd: 'unlink',
stateSelector: 'a[href]'
});
editor.addShortcut('Meta+K', '', createLinkList(showDialog));
editor.addCommand('mceLink', createLinkList(showDialog));
this.showDialog = showDialog;
editor.addMenuItem('link', {
icon: 'link',
text: 'Insert/edit link',
shortcut: 'Meta+K', | });
}); | onclick: createLinkList(showDialog),
stateSelector: 'a[href]',
context: 'insert',
prependToContext: true | random_line_split |
basic.rs | #![feature(proc_macro)]
extern crate fn_mut;
use fn_mut::fn_mut;
struct Test1(u64);
impl Test1 {
#[fn_mut]
fn test1(&self, text: &str) -> u64 |
#[fn_mut(enable_attrs = "text")]
fn test2(&self, text: &str) -> Option<&u64> {
if_mut! {
println!("This is mut fn: {}", text);
}
if_const! {
println!("This is const fn: {}", text);
}
Some(ptr!(self.0))
}
}
#[test]
fn test1() {
let mut t = Test1(1);
assert_eq!(t.test2("const"), Some(&1));
let mut s = String::from("mut");
assert_eq!(t.test2_mut(&mut s), Some(&mut 1));
assert_eq!(t.test1("const"), 21);
assert_eq!(t.test1_mut("const"), 11);
}
| {
if_mut! {
self.0 + 10
}
if_const! {
self.0 + 20
}
} | identifier_body |
basic.rs | #![feature(proc_macro)]
extern crate fn_mut;
use fn_mut::fn_mut;
struct Test1(u64);
impl Test1 {
#[fn_mut]
fn | (&self, text: &str) -> u64 {
if_mut! {
self.0 + 10
}
if_const! {
self.0 + 20
}
}
#[fn_mut(enable_attrs = "text")]
fn test2(&self, text: &str) -> Option<&u64> {
if_mut! {
println!("This is mut fn: {}", text);
}
if_const! {
println!("This is const fn: {}", text);
}
Some(ptr!(self.0))
}
}
#[test]
fn test1() {
let mut t = Test1(1);
assert_eq!(t.test2("const"), Some(&1));
let mut s = String::from("mut");
assert_eq!(t.test2_mut(&mut s), Some(&mut 1));
assert_eq!(t.test1("const"), 21);
assert_eq!(t.test1_mut("const"), 11);
}
| test1 | identifier_name |
basic.rs | struct Test1(u64);
impl Test1 {
#[fn_mut]
fn test1(&self, text: &str) -> u64 {
if_mut! {
self.0 + 10
}
if_const! {
self.0 + 20
}
}
#[fn_mut(enable_attrs = "text")]
fn test2(&self, text: &str) -> Option<&u64> {
if_mut! {
println!("This is mut fn: {}", text);
}
if_const! {
println!("This is const fn: {}", text);
}
Some(ptr!(self.0))
}
}
#[test]
fn test1() {
let mut t = Test1(1);
assert_eq!(t.test2("const"), Some(&1));
let mut s = String::from("mut");
assert_eq!(t.test2_mut(&mut s), Some(&mut 1));
assert_eq!(t.test1("const"), 21);
assert_eq!(t.test1_mut("const"), 11);
} | #![feature(proc_macro)]
extern crate fn_mut;
use fn_mut::fn_mut;
| random_line_split | |
revert_osiris.py | from __future__ import print_function
import httplib2
import io
import os
import sys
import time
import dateutil.parser
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaIoBaseDownload
import pprint
#Change these to the day of the osiris infestation
YEAR_OF_INFECTION=2017
MONTH_OF_INFECTION=01
DAY_OF_INFECTION=01
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/drive'
#YOU NEED TO SET UP AN APPLICATION ON GOOGLE AND GENERATE A KEY AND CREATE THIS FILE
CLIENT_SECRET_FILE = 'revert_osiris.json'
APPLICATION_NAME = 'Revert Osiris'
#copy pasta form gdrive API help examples
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'drive-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
pp = pprint.PrettyPrinter()
#grab first batch of possible infected files
results = service.files().list(pageSize=1,
fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
next_page = results.get('nextPageToken', None)
bad_files = []
done = False
next_page = None
while True:
results = service.files().list(pageToken=next_page, pageSize=100,
fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
break
else:
for item in items:
#Only act on files with osiris in the name.
if 'osiris' in item['name']:
bad_files.append(item)
next_page = results.get('nextPageToken', None)
print("Found {} bad files".format(len(bad_files)))
#Download a backup of all files just in case
for bad_item in bad_files:
|
count = 0
for bad_item in bad_files:
count = count + 1
#Do in batches just to be kind of safe.
if count > 50:
break
file_id = bad_item['id']
revisions = service.revisions().list(fileId=file_id, fields='*').execute()
if len(revisions['revisions']) < 2:
print("File has only 1 revision, skipping: {}".format(bad_item))
continue
file_meta = service.files().get(fileId=file_id, fields='*').execute()
dt_last = dateutil.parser.parse(revisions['revisions'][-1]['modifiedTime'])
dt_2nd_last = dateutil.parser.parse(revisions['revisions'][-2]['modifiedTime'])
if dt_last.day == DAY_OF_INFECTION and dt_last.month == MONTH_OF_INFECTION and dt_last.year == YEAR_OF_INFECTION:
print("Last revision dates from virus day")
else:
print("Skipping {}, datestamp on file isn't from virus day")
continue
orig_file_name = file_meta['originalFilename']
target_rev_name = revisions['revisions'][-2]['originalFilename']
#If the 2nd to last revision is also osiris, we can't simply revert
if 'osiris' in target_rev_name:
print("2nd to last rev filename has osiris in the name, skipping: ({})".format(target_rev_name))
#print out some debug info so we can figure out what we have multipe revisions with osiris
pp.pprint(file_meta)
print(' ')
pp.pprint(revisions)
continue
print("{}: {} revisions found".format(target_rev_name, len(revisions['revisions'])) )
#THESE ARE THE REALLY DANGEROUS STEPS, ONLY UNCOMMMENT IF YOU KNOW WHAT YOU ARE DOING!!!
rev_id_to_delete = revisions['revisions'][-1]['id']
print("service.revisions().delete(fileId={}, revisionId={}).execute()".format(file_id, rev_id_to_delete))
#del_rev = service.revisions().delete(fileId=file_id, revisionId=rev_id_to_delete).execute()
update_body = { 'name': target_rev_name }
print("service.files().update(fileId={}, body={}).execute()".format(file_id, update_body))
#update_name = service.files().update(fileId=file_id, body=update_body).execute()
if __name__ == '__main__':
main()
| revisions = service.revisions().list(fileId=bad_item['id'], fields='*').execute()
assert(len(revisions['revisions']) >= 2)
dt = dateutil.parser.parse(revisions['revisions'][-1]['modifiedTime'])
if dt.day == DAY_OF_INFECTION and dt.month = MONTH_OF_INFECTION and dt.year == YEAR_OF_INFECTION:
print("Last revision dates from virus day")
else:
print("Skipping {}, datastamp on file isn't from virus day")
continue
dt = dateutil.parser.parse(revisions['revisions'][-2]['modifiedTime'])
print("Date of second to last revision is: {}".format(dt))
request = service.revisions().get_media(fileId=bad_item['id'],
revisionId=revisions['revisions'][-2]['id'])
#Filenames are not unique in gdrive so append with file ID as well
new_filename = os.path.join('backup',
revisions['revisions'][-2]['originalFilename'] + '_' + bad_item['id'])
#If we are re-running script see if we already downloaded this file
if os.path.isfile(new_filename):
print("File {} already backed up, skipping".format(new_filename))
continue
fh = io.FileIO(new_filename, 'wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print("Download {}".format(int(status.progress() * 100)) ) | conditional_block |
revert_osiris.py | from __future__ import print_function
import httplib2
import io
import os
import sys
import time
import dateutil.parser
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaIoBaseDownload
import pprint
#Change these to the day of the osiris infestation
YEAR_OF_INFECTION=2017
MONTH_OF_INFECTION=01
DAY_OF_INFECTION=01
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/drive'
#YOU NEED TO SET UP AN APPLICATION ON GOOGLE AND GENERATE A KEY AND CREATE THIS FILE
CLIENT_SECRET_FILE = 'revert_osiris.json'
APPLICATION_NAME = 'Revert Osiris'
#copy pasta form gdrive API help examples
def get_credentials():
|
def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
pp = pprint.PrettyPrinter()
#grab first batch of possible infected files
results = service.files().list(pageSize=1,
fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
next_page = results.get('nextPageToken', None)
bad_files = []
done = False
next_page = None
while True:
results = service.files().list(pageToken=next_page, pageSize=100,
fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
break
else:
for item in items:
#Only act on files with osiris in the name.
if 'osiris' in item['name']:
bad_files.append(item)
next_page = results.get('nextPageToken', None)
print("Found {} bad files".format(len(bad_files)))
#Download a backup of all files just in case
for bad_item in bad_files:
revisions = service.revisions().list(fileId=bad_item['id'], fields='*').execute()
assert(len(revisions['revisions']) >= 2)
dt = dateutil.parser.parse(revisions['revisions'][-1]['modifiedTime'])
if dt.day == DAY_OF_INFECTION and dt.month = MONTH_OF_INFECTION and dt.year == YEAR_OF_INFECTION:
print("Last revision dates from virus day")
else:
print("Skipping {}, datastamp on file isn't from virus day")
continue
dt = dateutil.parser.parse(revisions['revisions'][-2]['modifiedTime'])
print("Date of second to last revision is: {}".format(dt))
request = service.revisions().get_media(fileId=bad_item['id'],
revisionId=revisions['revisions'][-2]['id'])
#Filenames are not unique in gdrive so append with file ID as well
new_filename = os.path.join('backup',
revisions['revisions'][-2]['originalFilename'] + '_' + bad_item['id'])
#If we are re-running script see if we already downloaded this file
if os.path.isfile(new_filename):
print("File {} already backed up, skipping".format(new_filename))
continue
fh = io.FileIO(new_filename, 'wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print("Download {}".format(int(status.progress() * 100)) )
count = 0
for bad_item in bad_files:
count = count + 1
#Do in batches just to be kind of safe.
if count > 50:
break
file_id = bad_item['id']
revisions = service.revisions().list(fileId=file_id, fields='*').execute()
if len(revisions['revisions']) < 2:
print("File has only 1 revision, skipping: {}".format(bad_item))
continue
file_meta = service.files().get(fileId=file_id, fields='*').execute()
dt_last = dateutil.parser.parse(revisions['revisions'][-1]['modifiedTime'])
dt_2nd_last = dateutil.parser.parse(revisions['revisions'][-2]['modifiedTime'])
if dt_last.day == DAY_OF_INFECTION and dt_last.month == MONTH_OF_INFECTION and dt_last.year == YEAR_OF_INFECTION:
print("Last revision dates from virus day")
else:
print("Skipping {}, datestamp on file isn't from virus day")
continue
orig_file_name = file_meta['originalFilename']
target_rev_name = revisions['revisions'][-2]['originalFilename']
#If the 2nd to last revision is also osiris, we can't simply revert
if 'osiris' in target_rev_name:
print("2nd to last rev filename has osiris in the name, skipping: ({})".format(target_rev_name))
#print out some debug info so we can figure out what we have multipe revisions with osiris
pp.pprint(file_meta)
print(' ')
pp.pprint(revisions)
continue
print("{}: {} revisions found".format(target_rev_name, len(revisions['revisions'])) )
#THESE ARE THE REALLY DANGEROUS STEPS, ONLY UNCOMMMENT IF YOU KNOW WHAT YOU ARE DOING!!!
rev_id_to_delete = revisions['revisions'][-1]['id']
print("service.revisions().delete(fileId={}, revisionId={}).execute()".format(file_id, rev_id_to_delete))
#del_rev = service.revisions().delete(fileId=file_id, revisionId=rev_id_to_delete).execute()
update_body = { 'name': target_rev_name }
print("service.files().update(fileId={}, body={}).execute()".format(file_id, update_body))
#update_name = service.files().update(fileId=file_id, body=update_body).execute()
if __name__ == '__main__':
main()
| """Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'drive-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials | identifier_body |
revert_osiris.py | from __future__ import print_function
import httplib2
import io
import os
import sys
import time
import dateutil.parser
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaIoBaseDownload
import pprint
#Change these to the day of the osiris infestation
YEAR_OF_INFECTION=2017
MONTH_OF_INFECTION=01
DAY_OF_INFECTION=01
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/drive'
#YOU NEED TO SET UP AN APPLICATION ON GOOGLE AND GENERATE A KEY AND CREATE THIS FILE
CLIENT_SECRET_FILE = 'revert_osiris.json'
APPLICATION_NAME = 'Revert Osiris'
#copy pasta form gdrive API help examples
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'drive-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
pp = pprint.PrettyPrinter()
#grab first batch of possible infected files
results = service.files().list(pageSize=1,
fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
next_page = results.get('nextPageToken', None)
bad_files = []
done = False
next_page = None
while True:
results = service.files().list(pageToken=next_page, pageSize=100,
fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
break
else:
for item in items:
#Only act on files with osiris in the name.
if 'osiris' in item['name']:
bad_files.append(item)
next_page = results.get('nextPageToken', None)
print("Found {} bad files".format(len(bad_files)))
#Download a backup of all files just in case
for bad_item in bad_files:
revisions = service.revisions().list(fileId=bad_item['id'], fields='*').execute()
assert(len(revisions['revisions']) >= 2)
dt = dateutil.parser.parse(revisions['revisions'][-1]['modifiedTime'])
if dt.day == DAY_OF_INFECTION and dt.month = MONTH_OF_INFECTION and dt.year == YEAR_OF_INFECTION:
print("Last revision dates from virus day")
else:
print("Skipping {}, datastamp on file isn't from virus day")
continue
dt = dateutil.parser.parse(revisions['revisions'][-2]['modifiedTime'])
print("Date of second to last revision is: {}".format(dt))
request = service.revisions().get_media(fileId=bad_item['id'],
revisionId=revisions['revisions'][-2]['id'])
#Filenames are not unique in gdrive so append with file ID as well
new_filename = os.path.join('backup',
revisions['revisions'][-2]['originalFilename'] + '_' + bad_item['id'])
#If we are re-running script see if we already downloaded this file
if os.path.isfile(new_filename):
print("File {} already backed up, skipping".format(new_filename))
continue
fh = io.FileIO(new_filename, 'wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print("Download {}".format(int(status.progress() * 100)) )
count = 0
for bad_item in bad_files:
count = count + 1
#Do in batches just to be kind of safe.
if count > 50:
break
file_id = bad_item['id']
revisions = service.revisions().list(fileId=file_id, fields='*').execute()
if len(revisions['revisions']) < 2:
print("File has only 1 revision, skipping: {}".format(bad_item))
continue
file_meta = service.files().get(fileId=file_id, fields='*').execute()
dt_last = dateutil.parser.parse(revisions['revisions'][-1]['modifiedTime'])
dt_2nd_last = dateutil.parser.parse(revisions['revisions'][-2]['modifiedTime'])
if dt_last.day == DAY_OF_INFECTION and dt_last.month == MONTH_OF_INFECTION and dt_last.year == YEAR_OF_INFECTION:
print("Last revision dates from virus day")
else:
print("Skipping {}, datestamp on file isn't from virus day")
continue
orig_file_name = file_meta['originalFilename']
target_rev_name = revisions['revisions'][-2]['originalFilename']
#If the 2nd to last revision is also osiris, we can't simply revert
if 'osiris' in target_rev_name:
print("2nd to last rev filename has osiris in the name, skipping: ({})".format(target_rev_name)) | pp.pprint(file_meta)
print(' ')
pp.pprint(revisions)
continue
print("{}: {} revisions found".format(target_rev_name, len(revisions['revisions'])) )
#THESE ARE THE REALLY DANGEROUS STEPS, ONLY UNCOMMMENT IF YOU KNOW WHAT YOU ARE DOING!!!
rev_id_to_delete = revisions['revisions'][-1]['id']
print("service.revisions().delete(fileId={}, revisionId={}).execute()".format(file_id, rev_id_to_delete))
#del_rev = service.revisions().delete(fileId=file_id, revisionId=rev_id_to_delete).execute()
update_body = { 'name': target_rev_name }
print("service.files().update(fileId={}, body={}).execute()".format(file_id, update_body))
#update_name = service.files().update(fileId=file_id, body=update_body).execute()
if __name__ == '__main__':
main() | #print out some debug info so we can figure out what we have multipe revisions with osiris | random_line_split |
revert_osiris.py | from __future__ import print_function
import httplib2
import io
import os
import sys
import time
import dateutil.parser
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaIoBaseDownload
import pprint
#Change these to the day of the osiris infestation
YEAR_OF_INFECTION=2017
MONTH_OF_INFECTION=01
DAY_OF_INFECTION=01
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
SCOPES = 'https://www.googleapis.com/auth/drive'
#YOU NEED TO SET UP AN APPLICATION ON GOOGLE AND GENERATE A KEY AND CREATE THIS FILE
CLIENT_SECRET_FILE = 'revert_osiris.json'
APPLICATION_NAME = 'Revert Osiris'
#copy pasta form gdrive API help examples
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'drive-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def | ():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
pp = pprint.PrettyPrinter()
#grab first batch of possible infected files
results = service.files().list(pageSize=1,
fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
next_page = results.get('nextPageToken', None)
bad_files = []
done = False
next_page = None
while True:
results = service.files().list(pageToken=next_page, pageSize=100,
fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
break
else:
for item in items:
#Only act on files with osiris in the name.
if 'osiris' in item['name']:
bad_files.append(item)
next_page = results.get('nextPageToken', None)
print("Found {} bad files".format(len(bad_files)))
#Download a backup of all files just in case
for bad_item in bad_files:
revisions = service.revisions().list(fileId=bad_item['id'], fields='*').execute()
assert(len(revisions['revisions']) >= 2)
dt = dateutil.parser.parse(revisions['revisions'][-1]['modifiedTime'])
if dt.day == DAY_OF_INFECTION and dt.month = MONTH_OF_INFECTION and dt.year == YEAR_OF_INFECTION:
print("Last revision dates from virus day")
else:
print("Skipping {}, datastamp on file isn't from virus day")
continue
dt = dateutil.parser.parse(revisions['revisions'][-2]['modifiedTime'])
print("Date of second to last revision is: {}".format(dt))
request = service.revisions().get_media(fileId=bad_item['id'],
revisionId=revisions['revisions'][-2]['id'])
#Filenames are not unique in gdrive so append with file ID as well
new_filename = os.path.join('backup',
revisions['revisions'][-2]['originalFilename'] + '_' + bad_item['id'])
#If we are re-running script see if we already downloaded this file
if os.path.isfile(new_filename):
print("File {} already backed up, skipping".format(new_filename))
continue
fh = io.FileIO(new_filename, 'wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print("Download {}".format(int(status.progress() * 100)) )
count = 0
for bad_item in bad_files:
count = count + 1
#Do in batches just to be kind of safe.
if count > 50:
break
file_id = bad_item['id']
revisions = service.revisions().list(fileId=file_id, fields='*').execute()
if len(revisions['revisions']) < 2:
print("File has only 1 revision, skipping: {}".format(bad_item))
continue
file_meta = service.files().get(fileId=file_id, fields='*').execute()
dt_last = dateutil.parser.parse(revisions['revisions'][-1]['modifiedTime'])
dt_2nd_last = dateutil.parser.parse(revisions['revisions'][-2]['modifiedTime'])
if dt_last.day == DAY_OF_INFECTION and dt_last.month == MONTH_OF_INFECTION and dt_last.year == YEAR_OF_INFECTION:
print("Last revision dates from virus day")
else:
print("Skipping {}, datestamp on file isn't from virus day")
continue
orig_file_name = file_meta['originalFilename']
target_rev_name = revisions['revisions'][-2]['originalFilename']
#If the 2nd to last revision is also osiris, we can't simply revert
if 'osiris' in target_rev_name:
print("2nd to last rev filename has osiris in the name, skipping: ({})".format(target_rev_name))
#print out some debug info so we can figure out what we have multipe revisions with osiris
pp.pprint(file_meta)
print(' ')
pp.pprint(revisions)
continue
print("{}: {} revisions found".format(target_rev_name, len(revisions['revisions'])) )
#THESE ARE THE REALLY DANGEROUS STEPS, ONLY UNCOMMMENT IF YOU KNOW WHAT YOU ARE DOING!!!
rev_id_to_delete = revisions['revisions'][-1]['id']
print("service.revisions().delete(fileId={}, revisionId={}).execute()".format(file_id, rev_id_to_delete))
#del_rev = service.revisions().delete(fileId=file_id, revisionId=rev_id_to_delete).execute()
update_body = { 'name': target_rev_name }
print("service.files().update(fileId={}, body={}).execute()".format(file_id, update_body))
#update_name = service.files().update(fileId=file_id, body=update_body).execute()
if __name__ == '__main__':
main()
| main | identifier_name |
rtc.rs | use core::intrinsics::{volatile_load, volatile_store};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, PhysicalAddress, Page, PageFlags, TableKind, VirtualAddress};
use crate::time;
static RTC_DR: u32 = 0x000;
static RTC_MR: u32 = 0x004;
static RTC_LR: u32 = 0x008;
static RTC_CR: u32 = 0x00c;
static RTC_IMSC: u32 = 0x010;
static RTC_RIS: u32 = 0x014;
static RTC_MIS: u32 = 0x018;
static RTC_ICR: u32 = 0x01c;
static mut PL031_RTC: Pl031rtc = Pl031rtc {
address: 0,
};
pub unsafe fn init() {
PL031_RTC.init();
time::START.lock().0 = PL031_RTC.time();
}
struct Pl031rtc {
pub address: usize,
}
impl Pl031rtc {
unsafe fn init(&mut self) {
let mut active_table = ActivePageTable::new(TableKind::Kernel);
let start_frame = Frame::containing_address(PhysicalAddress::new(0x09010000));
let end_frame = Frame::containing_address(PhysicalAddress::new(0x09010000 + 0x1000 - 1));
for frame in Frame::range_inclusive(start_frame, end_frame) {
let page = Page::containing_address(VirtualAddress::new(frame.start_address().data() + crate::KERNEL_DEVMAP_OFFSET));
let result = active_table.map_to(page, frame, PageFlags::new().write(true));
result.flush();
}
self.address = crate::KERNEL_DEVMAP_OFFSET + 0x09010000;
}
unsafe fn read(&self, reg: u32) -> u32 |
unsafe fn write(&mut self, reg: u32, value: u32) {
volatile_store((self.address + reg as usize) as *mut u32, value);
}
pub fn time(&mut self) -> u64 {
let seconds = unsafe { self.read(RTC_DR) } as u64;
seconds
}
}
| {
let val = volatile_load((self.address + reg as usize) as *const u32);
val
} | identifier_body |
rtc.rs | use core::intrinsics::{volatile_load, volatile_store};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, PhysicalAddress, Page, PageFlags, TableKind, VirtualAddress};
use crate::time;
static RTC_DR: u32 = 0x000;
static RTC_MR: u32 = 0x004;
static RTC_LR: u32 = 0x008;
static RTC_CR: u32 = 0x00c;
static RTC_IMSC: u32 = 0x010;
static RTC_RIS: u32 = 0x014;
static RTC_MIS: u32 = 0x018;
static RTC_ICR: u32 = 0x01c;
static mut PL031_RTC: Pl031rtc = Pl031rtc {
address: 0,
};
pub unsafe fn init() {
PL031_RTC.init();
time::START.lock().0 = PL031_RTC.time();
}
struct Pl031rtc {
pub address: usize,
}
impl Pl031rtc {
unsafe fn init(&mut self) {
let mut active_table = ActivePageTable::new(TableKind::Kernel);
let start_frame = Frame::containing_address(PhysicalAddress::new(0x09010000));
let end_frame = Frame::containing_address(PhysicalAddress::new(0x09010000 + 0x1000 - 1)); | let result = active_table.map_to(page, frame, PageFlags::new().write(true));
result.flush();
}
self.address = crate::KERNEL_DEVMAP_OFFSET + 0x09010000;
}
unsafe fn read(&self, reg: u32) -> u32 {
let val = volatile_load((self.address + reg as usize) as *const u32);
val
}
unsafe fn write(&mut self, reg: u32, value: u32) {
volatile_store((self.address + reg as usize) as *mut u32, value);
}
pub fn time(&mut self) -> u64 {
let seconds = unsafe { self.read(RTC_DR) } as u64;
seconds
}
} |
for frame in Frame::range_inclusive(start_frame, end_frame) {
let page = Page::containing_address(VirtualAddress::new(frame.start_address().data() + crate::KERNEL_DEVMAP_OFFSET)); | random_line_split |
rtc.rs | use core::intrinsics::{volatile_load, volatile_store};
use crate::memory::Frame;
use crate::paging::{ActivePageTable, PhysicalAddress, Page, PageFlags, TableKind, VirtualAddress};
use crate::time;
static RTC_DR: u32 = 0x000;
static RTC_MR: u32 = 0x004;
static RTC_LR: u32 = 0x008;
static RTC_CR: u32 = 0x00c;
static RTC_IMSC: u32 = 0x010;
static RTC_RIS: u32 = 0x014;
static RTC_MIS: u32 = 0x018;
static RTC_ICR: u32 = 0x01c;
static mut PL031_RTC: Pl031rtc = Pl031rtc {
address: 0,
};
pub unsafe fn init() {
PL031_RTC.init();
time::START.lock().0 = PL031_RTC.time();
}
struct Pl031rtc {
pub address: usize,
}
impl Pl031rtc {
unsafe fn | (&mut self) {
let mut active_table = ActivePageTable::new(TableKind::Kernel);
let start_frame = Frame::containing_address(PhysicalAddress::new(0x09010000));
let end_frame = Frame::containing_address(PhysicalAddress::new(0x09010000 + 0x1000 - 1));
for frame in Frame::range_inclusive(start_frame, end_frame) {
let page = Page::containing_address(VirtualAddress::new(frame.start_address().data() + crate::KERNEL_DEVMAP_OFFSET));
let result = active_table.map_to(page, frame, PageFlags::new().write(true));
result.flush();
}
self.address = crate::KERNEL_DEVMAP_OFFSET + 0x09010000;
}
unsafe fn read(&self, reg: u32) -> u32 {
let val = volatile_load((self.address + reg as usize) as *const u32);
val
}
unsafe fn write(&mut self, reg: u32, value: u32) {
volatile_store((self.address + reg as usize) as *mut u32, value);
}
pub fn time(&mut self) -> u64 {
let seconds = unsafe { self.read(RTC_DR) } as u64;
seconds
}
}
| init | identifier_name |
test_count_minimal_sketch_counter.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for checking transformation algorithms (the models package).
"""
import logging
import unittest
import os
import sys
import random
import itertools
from gensim.models.phrases import Phrases
if sys.version_info[0] >= 3:
unicode = str
module_path = os.path.dirname(__file__) # needed because sample data files are located in the same folder
datapath = lambda fname: os.path.join(module_path, 'test_data', fname)
WORDS = ['PHRASE%i' % i for i in range(10)] # selected words for phrases
class TestPhrasesModel(unittest.TestCase):
@staticmethod
def get_word():
"""Generate random word from letters A-Z."""
word_len = random.randint(1, 12)
return ''.join(chr(random.randint(65, 80)) for i in range(word_len))
@staticmethod
def get_sentence(size=10000):
"""Generator for random sentences.
10% probability to return sentence containing only preselected words"""
for i in range(size):
if random.random() > 0.9:
yield [WORDS[random.randint(0, len(WORDS) -1)] for i in range(random.randint(2, 10))] + ["."]
else:
yield [TestPhrasesModel.get_word() for i in range(random.randint(2, 10))] + ["."]
def testUpdate(self):
"""Test adding one token.
"""
special_token = 'non_present_token'
phrases = Phrases(TestPhrasesModel.get_sentence(), min_count=1)
present = special_token in phrases.vocab
freq = phrases.vocab[special_token]
phrases.add_vocab([[special_token]])
freq_after_change = phrases.vocab[special_token]
present_after_change = special_token in phrases.vocab
self.assertEqual(present, False, msg="Non-present token is marked as present.")
self.assertEqual(present_after_change, True, msg="Present token is marked as non-present.")
self.assertEqual(freq, 0, msg="Predicted non-zero freq for non-present token.")
self.assertEqual(freq_after_change, 1, msg="Predicted non 1 freq for token inserted once.")
def testFreqCount(self):
"""Test adding one token.
"""
special_token = 'non_present_token'
phrases = Phrases(None, min_count=1)
current = iter([])
for i in range(100):
current = itertools.chain(current, iter([[special_token]]), TestPhrasesModel.get_sentence(i))
phrases.add_vocab(current)
freq = phrases.vocab[special_token]
self.assertTrue(freq >= 100)
current = iter([])
for i in range(100):
current = itertools.chain(current, iter([[special_token]]), TestPhrasesModel.get_sentence(i))
phrases.add_vocab(current) | self.assertTrue(freq >= 200)
#endclass TestPhrasesModel
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG)
unittest.main() |
freq = phrases.vocab[special_token] | random_line_split |
test_count_minimal_sketch_counter.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for checking transformation algorithms (the models package).
"""
import logging
import unittest
import os
import sys
import random
import itertools
from gensim.models.phrases import Phrases
if sys.version_info[0] >= 3:
unicode = str
module_path = os.path.dirname(__file__) # needed because sample data files are located in the same folder
datapath = lambda fname: os.path.join(module_path, 'test_data', fname)
WORDS = ['PHRASE%i' % i for i in range(10)] # selected words for phrases
class TestPhrasesModel(unittest.TestCase):
@staticmethod
def get_word():
"""Generate random word from letters A-Z."""
word_len = random.randint(1, 12)
return ''.join(chr(random.randint(65, 80)) for i in range(word_len))
@staticmethod
def get_sentence(size=10000):
"""Generator for random sentences.
10% probability to return sentence containing only preselected words"""
for i in range(size):
if random.random() > 0.9:
yield [WORDS[random.randint(0, len(WORDS) -1)] for i in range(random.randint(2, 10))] + ["."]
else:
yield [TestPhrasesModel.get_word() for i in range(random.randint(2, 10))] + ["."]
def | (self):
"""Test adding one token.
"""
special_token = 'non_present_token'
phrases = Phrases(TestPhrasesModel.get_sentence(), min_count=1)
present = special_token in phrases.vocab
freq = phrases.vocab[special_token]
phrases.add_vocab([[special_token]])
freq_after_change = phrases.vocab[special_token]
present_after_change = special_token in phrases.vocab
self.assertEqual(present, False, msg="Non-present token is marked as present.")
self.assertEqual(present_after_change, True, msg="Present token is marked as non-present.")
self.assertEqual(freq, 0, msg="Predicted non-zero freq for non-present token.")
self.assertEqual(freq_after_change, 1, msg="Predicted non 1 freq for token inserted once.")
def testFreqCount(self):
"""Test adding one token.
"""
special_token = 'non_present_token'
phrases = Phrases(None, min_count=1)
current = iter([])
for i in range(100):
current = itertools.chain(current, iter([[special_token]]), TestPhrasesModel.get_sentence(i))
phrases.add_vocab(current)
freq = phrases.vocab[special_token]
self.assertTrue(freq >= 100)
current = iter([])
for i in range(100):
current = itertools.chain(current, iter([[special_token]]), TestPhrasesModel.get_sentence(i))
phrases.add_vocab(current)
freq = phrases.vocab[special_token]
self.assertTrue(freq >= 200)
#endclass TestPhrasesModel
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG)
unittest.main()
| testUpdate | identifier_name |
test_count_minimal_sketch_counter.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for checking transformation algorithms (the models package).
"""
import logging
import unittest
import os
import sys
import random
import itertools
from gensim.models.phrases import Phrases
if sys.version_info[0] >= 3:
unicode = str
module_path = os.path.dirname(__file__) # needed because sample data files are located in the same folder
datapath = lambda fname: os.path.join(module_path, 'test_data', fname)
WORDS = ['PHRASE%i' % i for i in range(10)] # selected words for phrases
class TestPhrasesModel(unittest.TestCase):
@staticmethod
def get_word():
"""Generate random word from letters A-Z."""
word_len = random.randint(1, 12)
return ''.join(chr(random.randint(65, 80)) for i in range(word_len))
@staticmethod
def get_sentence(size=10000):
"""Generator for random sentences.
10% probability to return sentence containing only preselected words"""
for i in range(size):
if random.random() > 0.9:
|
else:
yield [TestPhrasesModel.get_word() for i in range(random.randint(2, 10))] + ["."]
def testUpdate(self):
"""Test adding one token.
"""
special_token = 'non_present_token'
phrases = Phrases(TestPhrasesModel.get_sentence(), min_count=1)
present = special_token in phrases.vocab
freq = phrases.vocab[special_token]
phrases.add_vocab([[special_token]])
freq_after_change = phrases.vocab[special_token]
present_after_change = special_token in phrases.vocab
self.assertEqual(present, False, msg="Non-present token is marked as present.")
self.assertEqual(present_after_change, True, msg="Present token is marked as non-present.")
self.assertEqual(freq, 0, msg="Predicted non-zero freq for non-present token.")
self.assertEqual(freq_after_change, 1, msg="Predicted non 1 freq for token inserted once.")
def testFreqCount(self):
"""Test adding one token.
"""
special_token = 'non_present_token'
phrases = Phrases(None, min_count=1)
current = iter([])
for i in range(100):
current = itertools.chain(current, iter([[special_token]]), TestPhrasesModel.get_sentence(i))
phrases.add_vocab(current)
freq = phrases.vocab[special_token]
self.assertTrue(freq >= 100)
current = iter([])
for i in range(100):
current = itertools.chain(current, iter([[special_token]]), TestPhrasesModel.get_sentence(i))
phrases.add_vocab(current)
freq = phrases.vocab[special_token]
self.assertTrue(freq >= 200)
#endclass TestPhrasesModel
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG)
unittest.main()
| yield [WORDS[random.randint(0, len(WORDS) -1)] for i in range(random.randint(2, 10))] + ["."] | conditional_block |
test_count_minimal_sketch_counter.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for checking transformation algorithms (the models package).
"""
import logging
import unittest
import os
import sys
import random
import itertools
from gensim.models.phrases import Phrases
if sys.version_info[0] >= 3:
unicode = str
module_path = os.path.dirname(__file__) # needed because sample data files are located in the same folder
datapath = lambda fname: os.path.join(module_path, 'test_data', fname)
WORDS = ['PHRASE%i' % i for i in range(10)] # selected words for phrases
class TestPhrasesModel(unittest.TestCase):
@staticmethod
def get_word():
"""Generate random word from letters A-Z."""
word_len = random.randint(1, 12)
return ''.join(chr(random.randint(65, 80)) for i in range(word_len))
@staticmethod
def get_sentence(size=10000):
|
def testUpdate(self):
"""Test adding one token.
"""
special_token = 'non_present_token'
phrases = Phrases(TestPhrasesModel.get_sentence(), min_count=1)
present = special_token in phrases.vocab
freq = phrases.vocab[special_token]
phrases.add_vocab([[special_token]])
freq_after_change = phrases.vocab[special_token]
present_after_change = special_token in phrases.vocab
self.assertEqual(present, False, msg="Non-present token is marked as present.")
self.assertEqual(present_after_change, True, msg="Present token is marked as non-present.")
self.assertEqual(freq, 0, msg="Predicted non-zero freq for non-present token.")
self.assertEqual(freq_after_change, 1, msg="Predicted non 1 freq for token inserted once.")
def testFreqCount(self):
"""Test adding one token.
"""
special_token = 'non_present_token'
phrases = Phrases(None, min_count=1)
current = iter([])
for i in range(100):
current = itertools.chain(current, iter([[special_token]]), TestPhrasesModel.get_sentence(i))
phrases.add_vocab(current)
freq = phrases.vocab[special_token]
self.assertTrue(freq >= 100)
current = iter([])
for i in range(100):
current = itertools.chain(current, iter([[special_token]]), TestPhrasesModel.get_sentence(i))
phrases.add_vocab(current)
freq = phrases.vocab[special_token]
self.assertTrue(freq >= 200)
#endclass TestPhrasesModel
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG)
unittest.main()
| """Generator for random sentences.
10% probability to return sentence containing only preselected words"""
for i in range(size):
if random.random() > 0.9:
yield [WORDS[random.randint(0, len(WORDS) -1)] for i in range(random.randint(2, 10))] + ["."]
else:
yield [TestPhrasesModel.get_word() for i in range(random.randint(2, 10))] + ["."] | identifier_body |
SelectionAnchor.ts | import { Insert, Remove, SimRange, SimSelection, SugarElement, SugarNode, Traverse, WindowSelection } from '@ephox/sugar';
import * as Descend from '../../alien/Descend';
import { AlloyComponent } from '../../api/component/ComponentApi';
import * as Fields from '../../data/Fields';
import * as Origins from '../layout/Origins';
import { Anchoring, SelectionAnchor } from './Anchoring';
import * as AnchorLayouts from './AnchorLayouts';
import * as ContainerOffsets from './ContainerOffsets';
import * as ContentAnchorCommon from './ContentAnchorCommon';
// A range from (a, 1) to (body, end) was giving the wrong bounds.
const descendOnce = (element: SugarElement<Node>, offset: number): Descend.ElementAndOffset<Node> =>
SugarNode.isText(element) ? Descend.point(element, offset) : Descend.descendOnce(element, offset);
const getAnchorSelection = (win: Window, anchorInfo: SelectionAnchor): Optional<SimRange> => {
// FIX TEST Test both providing a getSelection and not providing a getSelection
const getSelection = anchorInfo.getSelection.getOrThunk(() => () => WindowSelection.getExact(win));
return getSelection().map((sel) => {
const modStart = descendOnce(sel.start, sel.soffset);
const modFinish = descendOnce(sel.finish, sel.foffset);
return SimSelection.range(modStart.element, modStart.offset, modFinish.element, modFinish.offset);
});
};
const placement = (component: AlloyComponent, anchorInfo: SelectionAnchor, origin: Origins.OriginAdt): Optional<Anchoring> => {
const win: Window = Traverse.defaultView(anchorInfo.root).dom;
const rootPoint = ContainerOffsets.getRootPoint(component, origin, anchorInfo);
const selectionBox = getAnchorSelection(win, anchorInfo).bind((sel) => {
// This represents the *visual* rectangle of the selection.
const optRect = WindowSelection.getBounds(win, SimSelection.exactFromRange(sel)).orThunk(() => {
const x = SugarElement.fromText(Unicode.zeroWidth);
Insert.before(sel.start, x);
// Certain things like <p><br/></p> with (p, 0) or <br>) as collapsed selection do not return a client rectangle
const rect = WindowSelection.getFirstRect(win, SimSelection.exact(x, 0, x, 1));
Remove.remove(x);
return rect;
});
return optRect.bind((rawRect) => ContentAnchorCommon.getBox(rawRect.left, rawRect.top, rawRect.width, rawRect.height));
});
const targetElement = getAnchorSelection(win, anchorInfo)
.bind((sel) => SugarNode.isElement(sel.start) ? Optional.some(sel.start) : Traverse.parentElement(sel.start));
const elem = targetElement.getOr(component.element);
return ContentAnchorCommon.calcNewAnchor(selectionBox, rootPoint, anchorInfo, origin, elem);
};
export default [
FieldSchema.option('getSelection'),
FieldSchema.required('root'),
FieldSchema.option('bubble'),
AnchorLayouts.schema(),
FieldSchema.defaulted('overrides', { }),
FieldSchema.defaulted('showAbove', false),
Fields.output('placement', placement)
]; | import { FieldSchema } from '@ephox/boulder';
import { Optional, Unicode } from '@ephox/katamari'; | random_line_split | |
setup.py | ###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Tavendo GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
###############################################################################
from setuptools import setup, find_packages
LONGDESC = """
A WebSocket echo service implemented as a Twisted service and
deployed as a twistd plugin.
"""
setup(
name='echows',
version='0.1.0',
description='Autobahn WebSocket Echo Service',
long_description=LONGDESC,
author='Tavendo GmbH',
url='http://crossbar.io/autobahn',
platforms=('Any'),
install_requires=['Twisted>=Twisted-12.2',
'Autobahn>=0.5.9'],
packages=find_packages() + ['twisted.plugins'],
# packages = ['echows', 'twisted.plugins'],
include_package_data=True,
zip_safe=False
) | #
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# | random_line_split |
see_service.py | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
from dace.util import getSite
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.view import BasicView
from lac.content.processes.services_processes.behaviors import (
SeeImportService)
from lac.content.service import ImportService
from lac.utilities.utils import (
ObjectRemovedException, generate_navbars)
@view_config(
name='',
context=ImportService,
renderer='pontus:templates/views_templates/grid.pt',
)
class SeeImportServiceView(BasicView):
title = ''
name = 'seeimportservice'
behaviors = [SeeImportService]
template = 'lac:views/services_processes/import_service/templates/see_import_service.pt'
viewid = 'seeimportservice'
def update(self):
|
DEFAULTMAPPING_ACTIONS_VIEWS.update({SeeImportService: SeeImportServiceView})
| self.execute(None)
result = {}
try:
navbars = generate_navbars(self, self.context, self.request)
except ObjectRemovedException:
return HTTPFound(self.request.resource_url(getSite(), ''))
values = {'object': self.context,
'navbar_body': navbars['navbar_body']}
body = self.content(args=values, template=self.template)['body']
item = self.adapt_item(body, self.viewid)
item['messages'] = navbars['messages']
item['isactive'] = navbars['isactive']
result.update(navbars['resources'])
result['coordinates'] = {self.coordinates: [item]}
return result | identifier_body |
see_service.py | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL
# author: Amen Souissi
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
from dace.util import getSite
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.view import BasicView
from lac.content.processes.services_processes.behaviors import (
SeeImportService)
from lac.content.service import ImportService
from lac.utilities.utils import (
ObjectRemovedException, generate_navbars)
@view_config(
name='',
context=ImportService,
renderer='pontus:templates/views_templates/grid.pt',
)
class SeeImportServiceView(BasicView):
title = ''
name = 'seeimportservice'
behaviors = [SeeImportService]
template = 'lac:views/services_processes/import_service/templates/see_import_service.pt'
viewid = 'seeimportservice'
def | (self):
self.execute(None)
result = {}
try:
navbars = generate_navbars(self, self.context, self.request)
except ObjectRemovedException:
return HTTPFound(self.request.resource_url(getSite(), ''))
values = {'object': self.context,
'navbar_body': navbars['navbar_body']}
body = self.content(args=values, template=self.template)['body']
item = self.adapt_item(body, self.viewid)
item['messages'] = navbars['messages']
item['isactive'] = navbars['isactive']
result.update(navbars['resources'])
result['coordinates'] = {self.coordinates: [item]}
return result
DEFAULTMAPPING_ACTIONS_VIEWS.update({SeeImportService: SeeImportServiceView})
| update | identifier_name |
see_service.py | # Copyright (c) 2014 by Ecreall under licence AGPL terms
# available on http://www.gnu.org/licenses/agpl.html
# licence: AGPL | from dace.util import getSite
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.view import BasicView
from lac.content.processes.services_processes.behaviors import (
SeeImportService)
from lac.content.service import ImportService
from lac.utilities.utils import (
ObjectRemovedException, generate_navbars)
@view_config(
name='',
context=ImportService,
renderer='pontus:templates/views_templates/grid.pt',
)
class SeeImportServiceView(BasicView):
title = ''
name = 'seeimportservice'
behaviors = [SeeImportService]
template = 'lac:views/services_processes/import_service/templates/see_import_service.pt'
viewid = 'seeimportservice'
def update(self):
self.execute(None)
result = {}
try:
navbars = generate_navbars(self, self.context, self.request)
except ObjectRemovedException:
return HTTPFound(self.request.resource_url(getSite(), ''))
values = {'object': self.context,
'navbar_body': navbars['navbar_body']}
body = self.content(args=values, template=self.template)['body']
item = self.adapt_item(body, self.viewid)
item['messages'] = navbars['messages']
item['isactive'] = navbars['isactive']
result.update(navbars['resources'])
result['coordinates'] = {self.coordinates: [item]}
return result
DEFAULTMAPPING_ACTIONS_VIEWS.update({SeeImportService: SeeImportServiceView}) | # author: Amen Souissi
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
| random_line_split |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn | (&mut self) -> Option<Self::Item> {
let ret;
loop {
let slot_opt = self.slots.get_index(self.index);
match slot_opt {
Some(slot) => match slot.state.get() {
SlotState::Alive | SlotState::Copying | SlotState::Copied => {
let key_ptr = slot.key.load(Ordering::Acquire);
let val = slot.value.load(Ordering::Relaxed);
if key_ptr.is_null() {
panic!("Iterator found an active slot with a null key");
}
let key = unsafe { hashkey_to_string(&(*key_ptr)) };
self.index += 1;
ret = Some((key, val));
break;
},
_ => {
self.index += 1;
}
},
None => {
self.slots.remove_thread();
ret = None;
break;
},
}
}
ret
}
}
| next | identifier_name |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn next(&mut self) -> Option<Self::Item> |
}
| {
let ret;
loop {
let slot_opt = self.slots.get_index(self.index);
match slot_opt {
Some(slot) => match slot.state.get() {
SlotState::Alive | SlotState::Copying | SlotState::Copied => {
let key_ptr = slot.key.load(Ordering::Acquire);
let val = slot.value.load(Ordering::Relaxed);
if key_ptr.is_null() {
panic!("Iterator found an active slot with a null key");
}
let key = unsafe { hashkey_to_string(&(*key_ptr)) };
self.index += 1;
ret = Some((key, val));
break;
},
_ => {
self.index += 1;
}
},
None => {
self.slots.remove_thread();
ret = None;
break;
},
}
}
ret
} | identifier_body |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn next(&mut self) -> Option<Self::Item> {
let ret;
loop {
let slot_opt = self.slots.get_index(self.index);
match slot_opt {
Some(slot) => match slot.state.get() {
SlotState::Alive | SlotState::Copying | SlotState::Copied => {
let key_ptr = slot.key.load(Ordering::Acquire);
let val = slot.value.load(Ordering::Relaxed);
if key_ptr.is_null() {
panic!("Iterator found an active slot with a null key");
}
let key = unsafe { hashkey_to_string(&(*key_ptr)) };
self.index += 1;
ret = Some((key, val));
break;
},
_ => |
},
None => {
self.slots.remove_thread();
ret = None;
break;
},
}
}
ret
}
}
| {
self.index += 1;
} | conditional_block |
iter.rs | use std::sync::atomic::Ordering;
use ::key::{hashkey_to_string};
use ::table::*;
use ::state::SlotState;
pub struct CounterIter<'a> {
pub slots: &'a VectorTable,
pub index: usize,
}
impl<'a> Iterator for CounterIter<'a> {
type Item = (String, usize);
fn next(&mut self) -> Option<Self::Item> {
let ret;
loop {
let slot_opt = self.slots.get_index(self.index);
match slot_opt {
Some(slot) => match slot.state.get() {
SlotState::Alive | SlotState::Copying | SlotState::Copied => {
let key_ptr = slot.key.load(Ordering::Acquire);
let val = slot.value.load(Ordering::Relaxed);
if key_ptr.is_null() {
panic!("Iterator found an active slot with a null key");
}
let key = unsafe { hashkey_to_string(&(*key_ptr)) };
self.index += 1;
ret = Some((key, val));
break;
},
_ => { | self.index += 1;
}
},
None => {
self.slots.remove_thread();
ret = None;
break;
},
}
}
ret
}
} | random_line_split | |
parser.py | #! /usr/bin/env python
class ParserError(Exception):
pass
class Sentence(object):
def __init__(self, subject, verb, object):
# remember we take ('noun', 'princess') tuples and convert them
self.subject = subject[1]
self.verb = verb[1]
self.object = object[1]
def get_sentence(self):
self.sentence = ' '.join([self.subject, self.verb, self.object])
return self.sentence
def | (word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None
def match(word_list, expecting):
if word_list:
word = word_list.pop(0)
if word[0] == expecting:
return word
else:
return None
else:
return None
def skip(word_list, word_type):
while peek(word_list) == word_type:
match(word_list, word_type)
def parse_verb(word_list):
skip(word_list, 'stop')
if peek(word_list) == 'verb':
return match(word_list, 'verb')
else:
raise ParserError("Expected a verb next.")
def parse_object(word_list):
skip(word_list, 'stop')
next = peek(word_list)
if next == 'noun':
return match(word_list, 'noun')
elif next == 'direction':
return match(word_list, 'direction')
else:
raise ParserError("Expected a noun or direction next.")
def parse_subject(word_list, subj):
verb = parse_verb(word_list)
obj = parse_object(word_list)
return Sentence(subj, verb, obj)
def parse_sentence(word_list):
skip(word_list, 'stop')
start = peek(word_list)
if start == 'noun':
subj = match(word_list, 'noun')
return parse_subject(word_list, subj)
elif start == 'verb':
# assume the subject is the player then
return parse_subject(word_list, ('noun', 'player'))
else:
raise ParserError("Must start with subject, object or verb not: %s" % start)
| peek | identifier_name |
parser.py | #! /usr/bin/env python
class ParserError(Exception):
pass
class Sentence(object):
def __init__(self, subject, verb, object):
# remember we take ('noun', 'princess') tuples and convert them
|
def get_sentence(self):
self.sentence = ' '.join([self.subject, self.verb, self.object])
return self.sentence
def peek(word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None
def match(word_list, expecting):
if word_list:
word = word_list.pop(0)
if word[0] == expecting:
return word
else:
return None
else:
return None
def skip(word_list, word_type):
while peek(word_list) == word_type:
match(word_list, word_type)
def parse_verb(word_list):
skip(word_list, 'stop')
if peek(word_list) == 'verb':
return match(word_list, 'verb')
else:
raise ParserError("Expected a verb next.")
def parse_object(word_list):
skip(word_list, 'stop')
next = peek(word_list)
if next == 'noun':
return match(word_list, 'noun')
elif next == 'direction':
return match(word_list, 'direction')
else:
raise ParserError("Expected a noun or direction next.")
def parse_subject(word_list, subj):
verb = parse_verb(word_list)
obj = parse_object(word_list)
return Sentence(subj, verb, obj)
def parse_sentence(word_list):
skip(word_list, 'stop')
start = peek(word_list)
if start == 'noun':
subj = match(word_list, 'noun')
return parse_subject(word_list, subj)
elif start == 'verb':
# assume the subject is the player then
return parse_subject(word_list, ('noun', 'player'))
else:
raise ParserError("Must start with subject, object or verb not: %s" % start)
| self.subject = subject[1]
self.verb = verb[1]
self.object = object[1] | identifier_body |
parser.py | #! /usr/bin/env python
class ParserError(Exception):
pass
class Sentence(object):
def __init__(self, subject, verb, object):
# remember we take ('noun', 'princess') tuples and convert them
self.subject = subject[1]
self.verb = verb[1]
self.object = object[1]
def get_sentence(self): | def peek(word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None
def match(word_list, expecting):
if word_list:
word = word_list.pop(0)
if word[0] == expecting:
return word
else:
return None
else:
return None
def skip(word_list, word_type):
while peek(word_list) == word_type:
match(word_list, word_type)
def parse_verb(word_list):
skip(word_list, 'stop')
if peek(word_list) == 'verb':
return match(word_list, 'verb')
else:
raise ParserError("Expected a verb next.")
def parse_object(word_list):
skip(word_list, 'stop')
next = peek(word_list)
if next == 'noun':
return match(word_list, 'noun')
elif next == 'direction':
return match(word_list, 'direction')
else:
raise ParserError("Expected a noun or direction next.")
def parse_subject(word_list, subj):
verb = parse_verb(word_list)
obj = parse_object(word_list)
return Sentence(subj, verb, obj)
def parse_sentence(word_list):
skip(word_list, 'stop')
start = peek(word_list)
if start == 'noun':
subj = match(word_list, 'noun')
return parse_subject(word_list, subj)
elif start == 'verb':
# assume the subject is the player then
return parse_subject(word_list, ('noun', 'player'))
else:
raise ParserError("Must start with subject, object or verb not: %s" % start) | self.sentence = ' '.join([self.subject, self.verb, self.object])
return self.sentence
| random_line_split |
parser.py | #! /usr/bin/env python
class ParserError(Exception):
pass
class Sentence(object):
def __init__(self, subject, verb, object):
# remember we take ('noun', 'princess') tuples and convert them
self.subject = subject[1]
self.verb = verb[1]
self.object = object[1]
def get_sentence(self):
self.sentence = ' '.join([self.subject, self.verb, self.object])
return self.sentence
def peek(word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None
def match(word_list, expecting):
if word_list:
word = word_list.pop(0)
if word[0] == expecting:
|
else:
return None
else:
return None
def skip(word_list, word_type):
while peek(word_list) == word_type:
match(word_list, word_type)
def parse_verb(word_list):
skip(word_list, 'stop')
if peek(word_list) == 'verb':
return match(word_list, 'verb')
else:
raise ParserError("Expected a verb next.")
def parse_object(word_list):
skip(word_list, 'stop')
next = peek(word_list)
if next == 'noun':
return match(word_list, 'noun')
elif next == 'direction':
return match(word_list, 'direction')
else:
raise ParserError("Expected a noun or direction next.")
def parse_subject(word_list, subj):
verb = parse_verb(word_list)
obj = parse_object(word_list)
return Sentence(subj, verb, obj)
def parse_sentence(word_list):
skip(word_list, 'stop')
start = peek(word_list)
if start == 'noun':
subj = match(word_list, 'noun')
return parse_subject(word_list, subj)
elif start == 'verb':
# assume the subject is the player then
return parse_subject(word_list, ('noun', 'player'))
else:
raise ParserError("Must start with subject, object or verb not: %s" % start)
| return word | conditional_block |
attach_debugger.py | import sublime, sublime_plugin
from .. import config
from .. import globals
from .. import logger
from ..debug_client import DebugClient
from ..clicks import Clicks
log = logger.get('cmd_attach_debugger')
def lookup_ref(id, refs):
for ref in refs:
if id == ref['handle']:
return ref
return None
def open_file(data):
if '/' not in data['script'].replace('\\', '/'):
print('[NDBG] Internal scripts (%s) doesn\'t supported for now. Sorry :(' % data['script'])
return
# TODO: fetch node's internal scripts with `scripts` request
window = sublime.active_window()
filename = '%s:%d:%d' % (data['script'], data['line'], 1) # it's better to use '1' instead of data['column']
src = window.open_file(filename, sublime.ENCODED_POSITION)
window.set_view_index(src, 0, 0)
if 'exception' in data:
src.set_status('node_error', data['exception'])
def trace_callback(data):
body = data['body']
refs = data['refs']
trace = []
funcLen = 0
for frame in body['frames']: | if funcLen < l:
funcLen = l
text = '%s\n' % globals.exception
globals.exception = None
for line in trace:
s = '\t%s (%s:%d:%d)\n' % (line['func'].ljust(funcLen), line['script'], line['line'], line['column'])
globals.clicks.add(sublime.Region(len(text), len(text + s)), open_file, line)
text = text + s
globals.st.run_command('node_debugger_insert_text', {'text': text})
def exception_callback(data):
log('exception', data)
body = data['body']
window = sublime.active_window()
if config.get('show_stacktrace'):
globals.exception = body['exception']['text']
window.set_layout(config.get('debug_layout'))
# Create new buffer for stacktrace
globals.st = st = window.new_file()
st.set_scratch(True)
st.set_name(config.get('stacktrace_name'))
st.settings().set('word_wrap', False)
st.settings().set('syntax', 'Packages/' + globals.prefix + '/node stacktrace.tmLanguage')
window.set_view_index(st, 1, 0)
# Request backtrace
globals.client.execute('backtrace', trace_callback, inlineRefs=True)
# Open file with error
open_file({'script': body['script']['name'], 'line': body['sourceLine'] + 1, 'column': body['sourceColumn'] + 1, 'exception': body['exception']['text']})
def after_compile_callback(data):
pass
def disconnect_handler(e):
log('disconnect_handler', e)
globals.client = None
class NodeDebuggerAttachCommand(sublime_plugin.ApplicationCommand):
def run(self):
if globals.client:
globals.client.close()
address = config.get('address')
try:
globals.original_layout = sublime.active_window().get_layout()
globals.clicks = Clicks()
globals.client = client = DebugClient(address)
client.on_disconnect(disconnect_handler)
# client.add_handler('break', exception_callback)
client.add_handler('exception', exception_callback)
client.add_handler('afterCompile', after_compile_callback)
client.execute_sync('setexceptionbreak', lambda data: client.execute('continue', lambda x: str(1)), type='uncaught', enabled=True)
except (IOError) as e:
log('Error connecting to %s' % address, e)
message = 'Error connecting to node.js instance at %s' % address
sublime.error_message(message) | func = frame['func']['name'] or frame['func']['inferredName'] or 'Anonymous'
script = lookup_ref(frame['script']['ref'], refs)
trace.append({'func': func, 'script': script['name'], 'line': int(frame['line']) + 1, 'column': int(frame['column']) + 1})
l = len(func) | random_line_split |
attach_debugger.py | import sublime, sublime_plugin
from .. import config
from .. import globals
from .. import logger
from ..debug_client import DebugClient
from ..clicks import Clicks
log = logger.get('cmd_attach_debugger')
def lookup_ref(id, refs):
for ref in refs:
|
return None
def open_file(data):
if '/' not in data['script'].replace('\\', '/'):
print('[NDBG] Internal scripts (%s) doesn\'t supported for now. Sorry :(' % data['script'])
return
# TODO: fetch node's internal scripts with `scripts` request
window = sublime.active_window()
filename = '%s:%d:%d' % (data['script'], data['line'], 1) # it's better to use '1' instead of data['column']
src = window.open_file(filename, sublime.ENCODED_POSITION)
window.set_view_index(src, 0, 0)
if 'exception' in data:
src.set_status('node_error', data['exception'])
def trace_callback(data):
body = data['body']
refs = data['refs']
trace = []
funcLen = 0
for frame in body['frames']:
func = frame['func']['name'] or frame['func']['inferredName'] or 'Anonymous'
script = lookup_ref(frame['script']['ref'], refs)
trace.append({'func': func, 'script': script['name'], 'line': int(frame['line']) + 1, 'column': int(frame['column']) + 1})
l = len(func)
if funcLen < l:
funcLen = l
text = '%s\n' % globals.exception
globals.exception = None
for line in trace:
s = '\t%s (%s:%d:%d)\n' % (line['func'].ljust(funcLen), line['script'], line['line'], line['column'])
globals.clicks.add(sublime.Region(len(text), len(text + s)), open_file, line)
text = text + s
globals.st.run_command('node_debugger_insert_text', {'text': text})
def exception_callback(data):
log('exception', data)
body = data['body']
window = sublime.active_window()
if config.get('show_stacktrace'):
globals.exception = body['exception']['text']
window.set_layout(config.get('debug_layout'))
# Create new buffer for stacktrace
globals.st = st = window.new_file()
st.set_scratch(True)
st.set_name(config.get('stacktrace_name'))
st.settings().set('word_wrap', False)
st.settings().set('syntax', 'Packages/' + globals.prefix + '/node stacktrace.tmLanguage')
window.set_view_index(st, 1, 0)
# Request backtrace
globals.client.execute('backtrace', trace_callback, inlineRefs=True)
# Open file with error
open_file({'script': body['script']['name'], 'line': body['sourceLine'] + 1, 'column': body['sourceColumn'] + 1, 'exception': body['exception']['text']})
def after_compile_callback(data):
pass
def disconnect_handler(e):
log('disconnect_handler', e)
globals.client = None
class NodeDebuggerAttachCommand(sublime_plugin.ApplicationCommand):
def run(self):
if globals.client:
globals.client.close()
address = config.get('address')
try:
globals.original_layout = sublime.active_window().get_layout()
globals.clicks = Clicks()
globals.client = client = DebugClient(address)
client.on_disconnect(disconnect_handler)
# client.add_handler('break', exception_callback)
client.add_handler('exception', exception_callback)
client.add_handler('afterCompile', after_compile_callback)
client.execute_sync('setexceptionbreak', lambda data: client.execute('continue', lambda x: str(1)), type='uncaught', enabled=True)
except (IOError) as e:
log('Error connecting to %s' % address, e)
message = 'Error connecting to node.js instance at %s' % address
sublime.error_message(message)
| if id == ref['handle']:
return ref | conditional_block |
attach_debugger.py | import sublime, sublime_plugin
from .. import config
from .. import globals
from .. import logger
from ..debug_client import DebugClient
from ..clicks import Clicks
log = logger.get('cmd_attach_debugger')
def lookup_ref(id, refs):
for ref in refs:
if id == ref['handle']:
return ref
return None
def open_file(data):
|
def trace_callback(data):
body = data['body']
refs = data['refs']
trace = []
funcLen = 0
for frame in body['frames']:
func = frame['func']['name'] or frame['func']['inferredName'] or 'Anonymous'
script = lookup_ref(frame['script']['ref'], refs)
trace.append({'func': func, 'script': script['name'], 'line': int(frame['line']) + 1, 'column': int(frame['column']) + 1})
l = len(func)
if funcLen < l:
funcLen = l
text = '%s\n' % globals.exception
globals.exception = None
for line in trace:
s = '\t%s (%s:%d:%d)\n' % (line['func'].ljust(funcLen), line['script'], line['line'], line['column'])
globals.clicks.add(sublime.Region(len(text), len(text + s)), open_file, line)
text = text + s
globals.st.run_command('node_debugger_insert_text', {'text': text})
def exception_callback(data):
log('exception', data)
body = data['body']
window = sublime.active_window()
if config.get('show_stacktrace'):
globals.exception = body['exception']['text']
window.set_layout(config.get('debug_layout'))
# Create new buffer for stacktrace
globals.st = st = window.new_file()
st.set_scratch(True)
st.set_name(config.get('stacktrace_name'))
st.settings().set('word_wrap', False)
st.settings().set('syntax', 'Packages/' + globals.prefix + '/node stacktrace.tmLanguage')
window.set_view_index(st, 1, 0)
# Request backtrace
globals.client.execute('backtrace', trace_callback, inlineRefs=True)
# Open file with error
open_file({'script': body['script']['name'], 'line': body['sourceLine'] + 1, 'column': body['sourceColumn'] + 1, 'exception': body['exception']['text']})
def after_compile_callback(data):
pass
def disconnect_handler(e):
log('disconnect_handler', e)
globals.client = None
class NodeDebuggerAttachCommand(sublime_plugin.ApplicationCommand):
def run(self):
if globals.client:
globals.client.close()
address = config.get('address')
try:
globals.original_layout = sublime.active_window().get_layout()
globals.clicks = Clicks()
globals.client = client = DebugClient(address)
client.on_disconnect(disconnect_handler)
# client.add_handler('break', exception_callback)
client.add_handler('exception', exception_callback)
client.add_handler('afterCompile', after_compile_callback)
client.execute_sync('setexceptionbreak', lambda data: client.execute('continue', lambda x: str(1)), type='uncaught', enabled=True)
except (IOError) as e:
log('Error connecting to %s' % address, e)
message = 'Error connecting to node.js instance at %s' % address
sublime.error_message(message)
| if '/' not in data['script'].replace('\\', '/'):
print('[NDBG] Internal scripts (%s) doesn\'t supported for now. Sorry :(' % data['script'])
return
# TODO: fetch node's internal scripts with `scripts` request
window = sublime.active_window()
filename = '%s:%d:%d' % (data['script'], data['line'], 1) # it's better to use '1' instead of data['column']
src = window.open_file(filename, sublime.ENCODED_POSITION)
window.set_view_index(src, 0, 0)
if 'exception' in data:
src.set_status('node_error', data['exception']) | identifier_body |
attach_debugger.py | import sublime, sublime_plugin
from .. import config
from .. import globals
from .. import logger
from ..debug_client import DebugClient
from ..clicks import Clicks
log = logger.get('cmd_attach_debugger')
def lookup_ref(id, refs):
for ref in refs:
if id == ref['handle']:
return ref
return None
def open_file(data):
if '/' not in data['script'].replace('\\', '/'):
print('[NDBG] Internal scripts (%s) doesn\'t supported for now. Sorry :(' % data['script'])
return
# TODO: fetch node's internal scripts with `scripts` request
window = sublime.active_window()
filename = '%s:%d:%d' % (data['script'], data['line'], 1) # it's better to use '1' instead of data['column']
src = window.open_file(filename, sublime.ENCODED_POSITION)
window.set_view_index(src, 0, 0)
if 'exception' in data:
src.set_status('node_error', data['exception'])
def trace_callback(data):
body = data['body']
refs = data['refs']
trace = []
funcLen = 0
for frame in body['frames']:
func = frame['func']['name'] or frame['func']['inferredName'] or 'Anonymous'
script = lookup_ref(frame['script']['ref'], refs)
trace.append({'func': func, 'script': script['name'], 'line': int(frame['line']) + 1, 'column': int(frame['column']) + 1})
l = len(func)
if funcLen < l:
funcLen = l
text = '%s\n' % globals.exception
globals.exception = None
for line in trace:
s = '\t%s (%s:%d:%d)\n' % (line['func'].ljust(funcLen), line['script'], line['line'], line['column'])
globals.clicks.add(sublime.Region(len(text), len(text + s)), open_file, line)
text = text + s
globals.st.run_command('node_debugger_insert_text', {'text': text})
def exception_callback(data):
log('exception', data)
body = data['body']
window = sublime.active_window()
if config.get('show_stacktrace'):
globals.exception = body['exception']['text']
window.set_layout(config.get('debug_layout'))
# Create new buffer for stacktrace
globals.st = st = window.new_file()
st.set_scratch(True)
st.set_name(config.get('stacktrace_name'))
st.settings().set('word_wrap', False)
st.settings().set('syntax', 'Packages/' + globals.prefix + '/node stacktrace.tmLanguage')
window.set_view_index(st, 1, 0)
# Request backtrace
globals.client.execute('backtrace', trace_callback, inlineRefs=True)
# Open file with error
open_file({'script': body['script']['name'], 'line': body['sourceLine'] + 1, 'column': body['sourceColumn'] + 1, 'exception': body['exception']['text']})
def after_compile_callback(data):
pass
def disconnect_handler(e):
log('disconnect_handler', e)
globals.client = None
class | (sublime_plugin.ApplicationCommand):
def run(self):
if globals.client:
globals.client.close()
address = config.get('address')
try:
globals.original_layout = sublime.active_window().get_layout()
globals.clicks = Clicks()
globals.client = client = DebugClient(address)
client.on_disconnect(disconnect_handler)
# client.add_handler('break', exception_callback)
client.add_handler('exception', exception_callback)
client.add_handler('afterCompile', after_compile_callback)
client.execute_sync('setexceptionbreak', lambda data: client.execute('continue', lambda x: str(1)), type='uncaught', enabled=True)
except (IOError) as e:
log('Error connecting to %s' % address, e)
message = 'Error connecting to node.js instance at %s' % address
sublime.error_message(message)
| NodeDebuggerAttachCommand | identifier_name |
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
use super::{ControlBase, ControlHandle};
use std::cell::RefCell;
const NOT_BOUND: &'static str = "Label is not yet bound to a winapi object";
const BAD_HANDLE: &'static str = "INTERNAL ERROR: Label handle is not HWND!";
bitflags! {
/**
The label flags
* NONE: No flags. Equivalent to a invisible blank label.
* VISIBLE: The label is immediatly visible after creation
* DISABLED: The label cannot be interacted with by the user. It also has a grayed out look.
*/
pub struct LabelFlags: u32 {
const NONE = 0;
const VISIBLE = WS_VISIBLE;
const DISABLED = WS_DISABLED;
/// Truncate the label if the text is too long. A label with this style CANNOT have multiple lines.
const ELIPSIS = SS_WORDELLIPSIS;
}
}
/**
A label is a single line of static text. Use `\r\n` to split the text on multiple lines.
Label is not behind any features.
**Builder parameters:**
* `parent`: **Required.** The label parent container.
* `text`: The label text.
* `size`: The label size.
* `position`: The label position.
* `enabled`: If the label is enabled. A disabled label won't trigger events
* `flags`: A combination of the LabelFlags values.
* `ex_flags`: A combination of win32 window extended flags. Unlike `flags`, ex_flags must be used straight from winapi
* `font`: The font used for the label text
* `background_color`: The background color of the label
* `h_align`: The horizontal aligment of the label
**Control events:**
* `OnLabelClick`: When the user click the label
* `OnLabelDoubleClick`: When the user double click a label
* `MousePress(_)`: Generic mouse press events on the label
* `OnMouseMove`: Generic mouse mouse event
* `OnMouseWheel`: Generic mouse wheel event
** Example **
```rust
use native_windows_gui as nwg;
fn build_label(label: &mut nwg::Label, window: &nwg::Window, font: &nwg::Font) {
nwg::Label::builder()
.text("Hello")
.font(Some(font))
.parent(window)
.build(label);
}
```
*/
#[derive(Default)]
pub struct Label {
pub handle: ControlHandle,
background_brush: Option<HBRUSH>,
handler0: RefCell<Option<RawEventHandler>>,
handler1: RefCell<Option<RawEventHandler>>,
}
impl Label {
pub fn builder<'a>() -> LabelBuilder<'a> {
LabelBuilder {
text: "A label",
size: (130, 25),
position: (0, 0),
flags: None,
ex_flags: 0,
font: None,
parent: None,
h_align: HTextAlign::Left,
v_align: VTextAlign::Center,
background_color: None
}
}
/// Return the font of the control
pub fn font(&self) -> Option<Font> {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let font_handle = wh::get_window_font(handle);
if font_handle.is_null() {
None
} else {
Some(Font { handle: font_handle })
}
}
/// Set the font of the control
pub fn set_font(&self, font: Option<&Font>) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_font(handle, font.map(|f| f.handle), true); }
}
/// Return true if the control currently has the keyboard focus
pub fn focus(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_focus(handle) }
}
/// Set the keyboard focus on the button.
pub fn set_focus(&self) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_focus(handle); }
}
/// Return true if the control user can interact with the control, return false otherwise
pub fn enabled(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_enabled(handle) }
}
/// Enable or disable the control
pub fn set_enabled(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_enabled(handle, v) }
}
/// Return true if the control is visible to the user. Will return true even if the
/// control is outside of the parent client view (ex: at the position (10000, 10000))
pub fn visible(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_visibility(handle) }
}
/// Show or hide the control to the user
pub fn set_visible(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_visibility(handle, v) }
}
/// Return the size of the label in the parent window
pub fn size(&self) -> (u32, u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_size(handle) }
}
/// Set the size of the label in the parent window
pub fn set_size(&self, x: u32, y: u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_size(handle, x, y, false) }
}
/// Return the position of the label in the parent window
pub fn position(&self) -> (i32, i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_position(handle) }
}
/// Set the position of the label in the parent window
pub fn set_position(&self, x: i32, y: i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_position(handle, x, y) }
}
/// Return the label text
pub fn text(&self) -> String {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_text(handle) }
}
/// Set the label text
pub fn set_text<'a>(&self, v: &'a str) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_text(handle, v) }
}
/// Winapi class name used during control creation
pub fn class_name(&self) -> &'static str {
"STATIC"
}
/// Winapi base flags used during window creation
pub fn flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOPREFIX, SS_LEFT};
WS_VISIBLE | SS_NOPREFIX | SS_LEFT
}
/// Winapi flags required by the control
pub fn forced_flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOTIFY, WS_CHILD};
WS_CHILD | SS_NOTIFY
}
/// Center the text vertically.
fn hook_non_client_size(&mut self, bg: Option<[u8; 3]>, v_align: VTextAlign) {
use crate::bind_raw_event_handler_inner;
use winapi::shared::windef::{HWND, HGDIOBJ, RECT, POINT};
use winapi::shared::{basetsd::UINT_PTR, minwindef::LRESULT};
use winapi::um::winuser::{WM_CTLCOLORSTATIC, WM_NCCALCSIZE, WM_NCPAINT, WM_SIZE, DT_CALCRECT, DT_LEFT, NCCALCSIZE_PARAMS, COLOR_WINDOW};
use winapi::um::winuser::{SWP_NOOWNERZORDER, SWP_NOSIZE, SWP_NOMOVE, SWP_FRAMECHANGED};
use winapi::um::winuser::{GetDC, DrawTextW, ReleaseDC, GetClientRect, GetWindowRect, FillRect, ScreenToClient, SetWindowPos, GetWindowTextW, GetWindowTextLengthW};
use winapi::um::wingdi::{SelectObject, CreateSolidBrush, RGB};
use std::{mem, ptr};
if self.handle.blank() { panic!("{}", NOT_BOUND); }
let handle = self.handle.hwnd().expect(BAD_HANDLE);
let parent_handle = ControlHandle::Hwnd(wh::get_window_parent(handle));
let brush = match bg {
Some(c) => {
let b = unsafe { CreateSolidBrush(RGB(c[0], c[1], c[2])) };
self.background_brush = Some(b);
b
},
None => COLOR_WINDOW as HBRUSH
};
unsafe {
if bg.is_some() {
let handler0 = bind_raw_event_handler_inner(&parent_handle, handle as UINT_PTR, move |_hwnd, msg, _w, l| {
match msg {
WM_CTLCOLORSTATIC => {
let child = l as HWND;
if child == handle {
return Some(brush as LRESULT);
}
},
_ => {}
}
None
});
*self.handler0.borrow_mut() = Some(handler0.unwrap());
}
let handler1 = bind_raw_event_handler_inner(&self.handle, 0, move |hwnd, msg, w, l| {
match msg {
WM_NCCALCSIZE => {
if w == 0 { return None }
// Calculate client area height needed for a font
let font_handle = wh::get_window_font(hwnd);
let mut r: RECT = mem::zeroed();
let dc = GetDC(hwnd);
let old = SelectObject(dc, font_handle as HGDIOBJ);
let mut newline_count = 1;
let buffer_size = GetWindowTextLengthW(handle) as usize;
match buffer_size == 0 {
true => {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
},
false => {
let mut buffer: Vec<u16> = vec![0; buffer_size + 1];
if GetWindowTextW(handle, buffer.as_mut_ptr(), buffer_size as _) == 0 {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
} else {
for &c in buffer.iter() {
if c == b'\n' as u16 {
newline_count += 1;
}
}
DrawTextW(dc, buffer.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
}
}
}
|
// Calculate NC area to center text.
let mut client: RECT = mem::zeroed();
let mut window: RECT = mem::zeroed();
GetClientRect(hwnd, &mut client);
GetWindowRect(hwnd, &mut window);
let window_height = window.bottom - window.top;
let info_ptr: *mut NCCALCSIZE_PARAMS = l as *mut NCCALCSIZE_PARAMS;
let info = &mut *info_ptr;
match v_align {
VTextAlign::Top => {
info.rgrc[0].bottom -= window_height - client_height;
},
VTextAlign::Center => {
let center = ((window_height - client_height) / 2) - 1;
info.rgrc[0].top += center;
info.rgrc[0].bottom -= center;
},
VTextAlign::Bottom => {
info.rgrc[0].top += window_height - client_height;
},
}
},
WM_NCPAINT => {
let mut window: RECT = mem::zeroed();
let mut client: RECT = mem::zeroed();
GetWindowRect(hwnd, &mut window);
GetClientRect(hwnd, &mut client);
let mut pt1 = POINT {x: window.left, y: window.top};
ScreenToClient(hwnd, &mut pt1);
let mut pt2 = POINT {x: window.right, y: window.bottom};
ScreenToClient(hwnd, &mut pt2);
let top = RECT {
left: 0,
top: pt1.y,
right: client.right,
bottom: client.top
};
let bottom = RECT {
left: 0,
top: client.bottom,
right: client.right,
bottom: pt2.y
};
let dc = GetDC(hwnd);
FillRect(dc, &top, brush);
FillRect(dc, &bottom, brush);
ReleaseDC(hwnd, dc);
},
WM_SIZE => {
SetWindowPos(hwnd, ptr::null_mut(), 0, 0, 0, 0, SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
},
_ => {}
}
None
});
*self.handler1.borrow_mut() = Some(handler1.unwrap());
}
}
}
impl PartialEq for Label {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
}
}
impl Drop for Label {
fn drop(&mut self) {
let handler = self.handler0.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
let handler = self.handler1.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
if let Some(bg) = self.background_brush {
unsafe { DeleteObject(bg as _); }
}
self.handle.destroy();
}
}
pub struct LabelBuilder<'a> {
text: &'a str,
size: (i32, i32),
position: (i32, i32),
background_color: Option<[u8; 3]>,
flags: Option<LabelFlags>,
ex_flags: u32,
font: Option<&'a Font>,
h_align: HTextAlign,
v_align: VTextAlign,
parent: Option<ControlHandle>
}
impl<'a> LabelBuilder<'a> {
pub fn flags(mut self, flags: LabelFlags) -> LabelBuilder<'a> {
self.flags = Some(flags);
self
}
pub fn ex_flags(mut self, flags: u32) -> LabelBuilder<'a> {
self.ex_flags = flags;
self
}
pub fn text(mut self, text: &'a str) -> LabelBuilder<'a> {
self.text = text;
self
}
pub fn size(mut self, size: (i32, i32)) -> LabelBuilder<'a> {
self.size = size;
self
}
pub fn position(mut self, pos: (i32, i32)) -> LabelBuilder<'a> {
self.position = pos;
self
}
pub fn font(mut self, font: Option<&'a Font>) -> LabelBuilder<'a> {
self.font = font;
self
}
pub fn background_color(mut self, color: Option<[u8;3]>) -> LabelBuilder<'a> {
self.background_color = color;
self
}
pub fn h_align(mut self, align: HTextAlign) -> LabelBuilder<'a> {
self.h_align = align;
self
}
pub fn v_align(mut self, align: VTextAlign) -> LabelBuilder<'a> {
self.v_align = align;
self
}
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> LabelBuilder<'a> {
self.parent = Some(p.into());
self
}
pub fn build(self, out: &mut Label) -> Result<(), NwgError> {
use winapi::um::winuser::{SS_LEFT, SS_RIGHT, SS_CENTER};
let mut flags = self.flags.map(|f| f.bits()).unwrap_or(out.flags());
match self.h_align {
HTextAlign::Left => { flags |= SS_LEFT; },
HTextAlign::Right => { flags |= SS_RIGHT; },
HTextAlign::Center => { flags |= SS_CENTER; },
}
let parent = match self.parent {
Some(p) => Ok(p),
None => Err(NwgError::no_parent("Label"))
}?;
// Drop the old object
*out = Label::default();
out.handle = ControlBase::build_hwnd()
.class_name(out.class_name())
.forced_flags(out.forced_flags())
.flags(flags)
.ex_flags(self.ex_flags)
.size(self.size)
.position(self.position)
.text(self.text)
.parent(Some(parent))
.build()?;
if self.font.is_some() {
out.set_font(self.font);
} else {
out.set_font(Font::global_default().as_ref());
}
out.hook_non_client_size(self.background_color, self.v_align);
Ok(())
}
} | let client_height = r.bottom * newline_count;
SelectObject(dc, old);
ReleaseDC(hwnd, dc); | random_line_split |
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
use super::{ControlBase, ControlHandle};
use std::cell::RefCell;
const NOT_BOUND: &'static str = "Label is not yet bound to a winapi object";
const BAD_HANDLE: &'static str = "INTERNAL ERROR: Label handle is not HWND!";
bitflags! {
/**
The label flags
* NONE: No flags. Equivalent to a invisible blank label.
* VISIBLE: The label is immediatly visible after creation
* DISABLED: The label cannot be interacted with by the user. It also has a grayed out look.
*/
pub struct LabelFlags: u32 {
const NONE = 0;
const VISIBLE = WS_VISIBLE;
const DISABLED = WS_DISABLED;
/// Truncate the label if the text is too long. A label with this style CANNOT have multiple lines.
const ELIPSIS = SS_WORDELLIPSIS;
}
}
/**
A label is a single line of static text. Use `\r\n` to split the text on multiple lines.
Label is not behind any features.
**Builder parameters:**
* `parent`: **Required.** The label parent container.
* `text`: The label text.
* `size`: The label size.
* `position`: The label position.
* `enabled`: If the label is enabled. A disabled label won't trigger events
* `flags`: A combination of the LabelFlags values.
* `ex_flags`: A combination of win32 window extended flags. Unlike `flags`, ex_flags must be used straight from winapi
* `font`: The font used for the label text
* `background_color`: The background color of the label
* `h_align`: The horizontal aligment of the label
**Control events:**
* `OnLabelClick`: When the user click the label
* `OnLabelDoubleClick`: When the user double click a label
* `MousePress(_)`: Generic mouse press events on the label
* `OnMouseMove`: Generic mouse mouse event
* `OnMouseWheel`: Generic mouse wheel event
** Example **
```rust
use native_windows_gui as nwg;
fn build_label(label: &mut nwg::Label, window: &nwg::Window, font: &nwg::Font) {
nwg::Label::builder()
.text("Hello")
.font(Some(font))
.parent(window)
.build(label);
}
```
*/
#[derive(Default)]
pub struct Label {
pub handle: ControlHandle,
background_brush: Option<HBRUSH>,
handler0: RefCell<Option<RawEventHandler>>,
handler1: RefCell<Option<RawEventHandler>>,
}
impl Label {
pub fn builder<'a>() -> LabelBuilder<'a> {
LabelBuilder {
text: "A label",
size: (130, 25),
position: (0, 0),
flags: None,
ex_flags: 0,
font: None,
parent: None,
h_align: HTextAlign::Left,
v_align: VTextAlign::Center,
background_color: None
}
}
/// Return the font of the control
pub fn font(&self) -> Option<Font> {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let font_handle = wh::get_window_font(handle);
if font_handle.is_null() {
None
} else {
Some(Font { handle: font_handle })
}
}
/// Set the font of the control
pub fn set_font(&self, font: Option<&Font>) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_font(handle, font.map(|f| f.handle), true); }
}
/// Return true if the control currently has the keyboard focus
pub fn focus(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_focus(handle) }
}
/// Set the keyboard focus on the button.
pub fn set_focus(&self) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_focus(handle); }
}
/// Return true if the control user can interact with the control, return false otherwise
pub fn enabled(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_enabled(handle) }
}
/// Enable or disable the control
pub fn set_enabled(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_enabled(handle, v) }
}
/// Return true if the control is visible to the user. Will return true even if the
/// control is outside of the parent client view (ex: at the position (10000, 10000))
pub fn visible(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_visibility(handle) }
}
/// Show or hide the control to the user
pub fn set_visible(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_visibility(handle, v) }
}
/// Return the size of the label in the parent window
pub fn size(&self) -> (u32, u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_size(handle) }
}
/// Set the size of the label in the parent window
pub fn set_size(&self, x: u32, y: u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_size(handle, x, y, false) }
}
/// Return the position of the label in the parent window
pub fn position(&self) -> (i32, i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_position(handle) }
}
/// Set the position of the label in the parent window
pub fn set_position(&self, x: i32, y: i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_position(handle, x, y) }
}
/// Return the label text
pub fn text(&self) -> String {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_text(handle) }
}
/// Set the label text
pub fn set_text<'a>(&self, v: &'a str) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_text(handle, v) }
}
/// Winapi class name used during control creation
pub fn class_name(&self) -> &'static str {
"STATIC"
}
/// Winapi base flags used during window creation
pub fn flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOPREFIX, SS_LEFT};
WS_VISIBLE | SS_NOPREFIX | SS_LEFT
}
/// Winapi flags required by the control
pub fn forced_flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOTIFY, WS_CHILD};
WS_CHILD | SS_NOTIFY
}
/// Center the text vertically.
fn hook_non_client_size(&mut self, bg: Option<[u8; 3]>, v_align: VTextAlign) {
use crate::bind_raw_event_handler_inner;
use winapi::shared::windef::{HWND, HGDIOBJ, RECT, POINT};
use winapi::shared::{basetsd::UINT_PTR, minwindef::LRESULT};
use winapi::um::winuser::{WM_CTLCOLORSTATIC, WM_NCCALCSIZE, WM_NCPAINT, WM_SIZE, DT_CALCRECT, DT_LEFT, NCCALCSIZE_PARAMS, COLOR_WINDOW};
use winapi::um::winuser::{SWP_NOOWNERZORDER, SWP_NOSIZE, SWP_NOMOVE, SWP_FRAMECHANGED};
use winapi::um::winuser::{GetDC, DrawTextW, ReleaseDC, GetClientRect, GetWindowRect, FillRect, ScreenToClient, SetWindowPos, GetWindowTextW, GetWindowTextLengthW};
use winapi::um::wingdi::{SelectObject, CreateSolidBrush, RGB};
use std::{mem, ptr};
if self.handle.blank() { panic!("{}", NOT_BOUND); }
let handle = self.handle.hwnd().expect(BAD_HANDLE);
let parent_handle = ControlHandle::Hwnd(wh::get_window_parent(handle));
let brush = match bg {
Some(c) => {
let b = unsafe { CreateSolidBrush(RGB(c[0], c[1], c[2])) };
self.background_brush = Some(b);
b
},
None => COLOR_WINDOW as HBRUSH
};
unsafe {
if bg.is_some() {
let handler0 = bind_raw_event_handler_inner(&parent_handle, handle as UINT_PTR, move |_hwnd, msg, _w, l| {
match msg {
WM_CTLCOLORSTATIC => {
let child = l as HWND;
if child == handle {
return Some(brush as LRESULT);
}
},
_ => {}
}
None
});
*self.handler0.borrow_mut() = Some(handler0.unwrap());
}
let handler1 = bind_raw_event_handler_inner(&self.handle, 0, move |hwnd, msg, w, l| {
match msg {
WM_NCCALCSIZE => {
if w == 0 { return None }
// Calculate client area height needed for a font
let font_handle = wh::get_window_font(hwnd);
let mut r: RECT = mem::zeroed();
let dc = GetDC(hwnd);
let old = SelectObject(dc, font_handle as HGDIOBJ);
let mut newline_count = 1;
let buffer_size = GetWindowTextLengthW(handle) as usize;
match buffer_size == 0 {
true => {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
},
false => {
let mut buffer: Vec<u16> = vec![0; buffer_size + 1];
if GetWindowTextW(handle, buffer.as_mut_ptr(), buffer_size as _) == 0 {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
} else {
for &c in buffer.iter() {
if c == b'\n' as u16 {
newline_count += 1;
}
}
DrawTextW(dc, buffer.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
}
}
}
let client_height = r.bottom * newline_count;
SelectObject(dc, old);
ReleaseDC(hwnd, dc);
// Calculate NC area to center text.
let mut client: RECT = mem::zeroed();
let mut window: RECT = mem::zeroed();
GetClientRect(hwnd, &mut client);
GetWindowRect(hwnd, &mut window);
let window_height = window.bottom - window.top;
let info_ptr: *mut NCCALCSIZE_PARAMS = l as *mut NCCALCSIZE_PARAMS;
let info = &mut *info_ptr;
match v_align {
VTextAlign::Top => {
info.rgrc[0].bottom -= window_height - client_height;
},
VTextAlign::Center => {
let center = ((window_height - client_height) / 2) - 1;
info.rgrc[0].top += center;
info.rgrc[0].bottom -= center;
},
VTextAlign::Bottom => {
info.rgrc[0].top += window_height - client_height;
},
}
},
WM_NCPAINT => {
let mut window: RECT = mem::zeroed();
let mut client: RECT = mem::zeroed();
GetWindowRect(hwnd, &mut window);
GetClientRect(hwnd, &mut client);
let mut pt1 = POINT {x: window.left, y: window.top};
ScreenToClient(hwnd, &mut pt1);
let mut pt2 = POINT {x: window.right, y: window.bottom};
ScreenToClient(hwnd, &mut pt2);
let top = RECT {
left: 0,
top: pt1.y,
right: client.right,
bottom: client.top
};
let bottom = RECT {
left: 0,
top: client.bottom,
right: client.right,
bottom: pt2.y
};
let dc = GetDC(hwnd);
FillRect(dc, &top, brush);
FillRect(dc, &bottom, brush);
ReleaseDC(hwnd, dc);
},
WM_SIZE => {
SetWindowPos(hwnd, ptr::null_mut(), 0, 0, 0, 0, SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
},
_ => {}
}
None
});
*self.handler1.borrow_mut() = Some(handler1.unwrap());
}
}
}
impl PartialEq for Label {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
}
}
impl Drop for Label {
fn drop(&mut self) {
let handler = self.handler0.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
let handler = self.handler1.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
if let Some(bg) = self.background_brush {
unsafe { DeleteObject(bg as _); }
}
self.handle.destroy();
}
}
pub struct LabelBuilder<'a> {
text: &'a str,
size: (i32, i32),
position: (i32, i32),
background_color: Option<[u8; 3]>,
flags: Option<LabelFlags>,
ex_flags: u32,
font: Option<&'a Font>,
h_align: HTextAlign,
v_align: VTextAlign,
parent: Option<ControlHandle>
}
impl<'a> LabelBuilder<'a> {
pub fn flags(mut self, flags: LabelFlags) -> LabelBuilder<'a> {
self.flags = Some(flags);
self
}
pub fn ex_flags(mut self, flags: u32) -> LabelBuilder<'a> {
self.ex_flags = flags;
self
}
pub fn text(mut self, text: &'a str) -> LabelBuilder<'a> {
self.text = text;
self
}
pub fn size(mut self, size: (i32, i32)) -> LabelBuilder<'a> {
self.size = size;
self
}
pub fn position(mut self, pos: (i32, i32)) -> LabelBuilder<'a> {
self.position = pos;
self
}
pub fn font(mut self, font: Option<&'a Font>) -> LabelBuilder<'a> {
self.font = font;
self
}
pub fn background_color(mut self, color: Option<[u8;3]>) -> LabelBuilder<'a> {
self.background_color = color;
self
}
pub fn h_align(mut self, align: HTextAlign) -> LabelBuilder<'a> {
self.h_align = align;
self
}
pub fn | (mut self, align: VTextAlign) -> LabelBuilder<'a> {
self.v_align = align;
self
}
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> LabelBuilder<'a> {
self.parent = Some(p.into());
self
}
pub fn build(self, out: &mut Label) -> Result<(), NwgError> {
use winapi::um::winuser::{SS_LEFT, SS_RIGHT, SS_CENTER};
let mut flags = self.flags.map(|f| f.bits()).unwrap_or(out.flags());
match self.h_align {
HTextAlign::Left => { flags |= SS_LEFT; },
HTextAlign::Right => { flags |= SS_RIGHT; },
HTextAlign::Center => { flags |= SS_CENTER; },
}
let parent = match self.parent {
Some(p) => Ok(p),
None => Err(NwgError::no_parent("Label"))
}?;
// Drop the old object
*out = Label::default();
out.handle = ControlBase::build_hwnd()
.class_name(out.class_name())
.forced_flags(out.forced_flags())
.flags(flags)
.ex_flags(self.ex_flags)
.size(self.size)
.position(self.position)
.text(self.text)
.parent(Some(parent))
.build()?;
if self.font.is_some() {
out.set_font(self.font);
} else {
out.set_font(Font::global_default().as_ref());
}
out.hook_non_client_size(self.background_color, self.v_align);
Ok(())
}
}
| v_align | identifier_name |
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
use super::{ControlBase, ControlHandle};
use std::cell::RefCell;
const NOT_BOUND: &'static str = "Label is not yet bound to a winapi object";
const BAD_HANDLE: &'static str = "INTERNAL ERROR: Label handle is not HWND!";
bitflags! {
/**
The label flags
* NONE: No flags. Equivalent to a invisible blank label.
* VISIBLE: The label is immediatly visible after creation
* DISABLED: The label cannot be interacted with by the user. It also has a grayed out look.
*/
pub struct LabelFlags: u32 {
const NONE = 0;
const VISIBLE = WS_VISIBLE;
const DISABLED = WS_DISABLED;
/// Truncate the label if the text is too long. A label with this style CANNOT have multiple lines.
const ELIPSIS = SS_WORDELLIPSIS;
}
}
/**
A label is a single line of static text. Use `\r\n` to split the text on multiple lines.
Label is not behind any features.
**Builder parameters:**
* `parent`: **Required.** The label parent container.
* `text`: The label text.
* `size`: The label size.
* `position`: The label position.
* `enabled`: If the label is enabled. A disabled label won't trigger events
* `flags`: A combination of the LabelFlags values.
* `ex_flags`: A combination of win32 window extended flags. Unlike `flags`, ex_flags must be used straight from winapi
* `font`: The font used for the label text
* `background_color`: The background color of the label
* `h_align`: The horizontal aligment of the label
**Control events:**
* `OnLabelClick`: When the user click the label
* `OnLabelDoubleClick`: When the user double click a label
* `MousePress(_)`: Generic mouse press events on the label
* `OnMouseMove`: Generic mouse mouse event
* `OnMouseWheel`: Generic mouse wheel event
** Example **
```rust
use native_windows_gui as nwg;
fn build_label(label: &mut nwg::Label, window: &nwg::Window, font: &nwg::Font) {
nwg::Label::builder()
.text("Hello")
.font(Some(font))
.parent(window)
.build(label);
}
```
*/
#[derive(Default)]
pub struct Label {
pub handle: ControlHandle,
background_brush: Option<HBRUSH>,
handler0: RefCell<Option<RawEventHandler>>,
handler1: RefCell<Option<RawEventHandler>>,
}
impl Label {
pub fn builder<'a>() -> LabelBuilder<'a> {
LabelBuilder {
text: "A label",
size: (130, 25),
position: (0, 0),
flags: None,
ex_flags: 0,
font: None,
parent: None,
h_align: HTextAlign::Left,
v_align: VTextAlign::Center,
background_color: None
}
}
/// Return the font of the control
pub fn font(&self) -> Option<Font> {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let font_handle = wh::get_window_font(handle);
if font_handle.is_null() {
None
} else {
Some(Font { handle: font_handle })
}
}
/// Set the font of the control
pub fn set_font(&self, font: Option<&Font>) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_font(handle, font.map(|f| f.handle), true); }
}
/// Return true if the control currently has the keyboard focus
pub fn focus(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_focus(handle) }
}
/// Set the keyboard focus on the button.
pub fn set_focus(&self) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_focus(handle); }
}
/// Return true if the control user can interact with the control, return false otherwise
pub fn enabled(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_enabled(handle) }
}
/// Enable or disable the control
pub fn set_enabled(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_enabled(handle, v) }
}
/// Return true if the control is visible to the user. Will return true even if the
/// control is outside of the parent client view (ex: at the position (10000, 10000))
pub fn visible(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_visibility(handle) }
}
/// Show or hide the control to the user
pub fn set_visible(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_visibility(handle, v) }
}
/// Return the size of the label in the parent window
pub fn size(&self) -> (u32, u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_size(handle) }
}
/// Set the size of the label in the parent window
pub fn set_size(&self, x: u32, y: u32) |
/// Return the position of the label in the parent window
pub fn position(&self) -> (i32, i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_position(handle) }
}
/// Set the position of the label in the parent window
pub fn set_position(&self, x: i32, y: i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_position(handle, x, y) }
}
/// Return the label text
pub fn text(&self) -> String {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_text(handle) }
}
/// Set the label text
pub fn set_text<'a>(&self, v: &'a str) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_text(handle, v) }
}
/// Winapi class name used during control creation
pub fn class_name(&self) -> &'static str {
"STATIC"
}
/// Winapi base flags used during window creation
pub fn flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOPREFIX, SS_LEFT};
WS_VISIBLE | SS_NOPREFIX | SS_LEFT
}
/// Winapi flags required by the control
pub fn forced_flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOTIFY, WS_CHILD};
WS_CHILD | SS_NOTIFY
}
/// Center the text vertically.
fn hook_non_client_size(&mut self, bg: Option<[u8; 3]>, v_align: VTextAlign) {
use crate::bind_raw_event_handler_inner;
use winapi::shared::windef::{HWND, HGDIOBJ, RECT, POINT};
use winapi::shared::{basetsd::UINT_PTR, minwindef::LRESULT};
use winapi::um::winuser::{WM_CTLCOLORSTATIC, WM_NCCALCSIZE, WM_NCPAINT, WM_SIZE, DT_CALCRECT, DT_LEFT, NCCALCSIZE_PARAMS, COLOR_WINDOW};
use winapi::um::winuser::{SWP_NOOWNERZORDER, SWP_NOSIZE, SWP_NOMOVE, SWP_FRAMECHANGED};
use winapi::um::winuser::{GetDC, DrawTextW, ReleaseDC, GetClientRect, GetWindowRect, FillRect, ScreenToClient, SetWindowPos, GetWindowTextW, GetWindowTextLengthW};
use winapi::um::wingdi::{SelectObject, CreateSolidBrush, RGB};
use std::{mem, ptr};
if self.handle.blank() { panic!("{}", NOT_BOUND); }
let handle = self.handle.hwnd().expect(BAD_HANDLE);
let parent_handle = ControlHandle::Hwnd(wh::get_window_parent(handle));
let brush = match bg {
Some(c) => {
let b = unsafe { CreateSolidBrush(RGB(c[0], c[1], c[2])) };
self.background_brush = Some(b);
b
},
None => COLOR_WINDOW as HBRUSH
};
unsafe {
if bg.is_some() {
let handler0 = bind_raw_event_handler_inner(&parent_handle, handle as UINT_PTR, move |_hwnd, msg, _w, l| {
match msg {
WM_CTLCOLORSTATIC => {
let child = l as HWND;
if child == handle {
return Some(brush as LRESULT);
}
},
_ => {}
}
None
});
*self.handler0.borrow_mut() = Some(handler0.unwrap());
}
let handler1 = bind_raw_event_handler_inner(&self.handle, 0, move |hwnd, msg, w, l| {
match msg {
WM_NCCALCSIZE => {
if w == 0 { return None }
// Calculate client area height needed for a font
let font_handle = wh::get_window_font(hwnd);
let mut r: RECT = mem::zeroed();
let dc = GetDC(hwnd);
let old = SelectObject(dc, font_handle as HGDIOBJ);
let mut newline_count = 1;
let buffer_size = GetWindowTextLengthW(handle) as usize;
match buffer_size == 0 {
true => {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
},
false => {
let mut buffer: Vec<u16> = vec![0; buffer_size + 1];
if GetWindowTextW(handle, buffer.as_mut_ptr(), buffer_size as _) == 0 {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
} else {
for &c in buffer.iter() {
if c == b'\n' as u16 {
newline_count += 1;
}
}
DrawTextW(dc, buffer.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
}
}
}
let client_height = r.bottom * newline_count;
SelectObject(dc, old);
ReleaseDC(hwnd, dc);
// Calculate NC area to center text.
let mut client: RECT = mem::zeroed();
let mut window: RECT = mem::zeroed();
GetClientRect(hwnd, &mut client);
GetWindowRect(hwnd, &mut window);
let window_height = window.bottom - window.top;
let info_ptr: *mut NCCALCSIZE_PARAMS = l as *mut NCCALCSIZE_PARAMS;
let info = &mut *info_ptr;
match v_align {
VTextAlign::Top => {
info.rgrc[0].bottom -= window_height - client_height;
},
VTextAlign::Center => {
let center = ((window_height - client_height) / 2) - 1;
info.rgrc[0].top += center;
info.rgrc[0].bottom -= center;
},
VTextAlign::Bottom => {
info.rgrc[0].top += window_height - client_height;
},
}
},
WM_NCPAINT => {
let mut window: RECT = mem::zeroed();
let mut client: RECT = mem::zeroed();
GetWindowRect(hwnd, &mut window);
GetClientRect(hwnd, &mut client);
let mut pt1 = POINT {x: window.left, y: window.top};
ScreenToClient(hwnd, &mut pt1);
let mut pt2 = POINT {x: window.right, y: window.bottom};
ScreenToClient(hwnd, &mut pt2);
let top = RECT {
left: 0,
top: pt1.y,
right: client.right,
bottom: client.top
};
let bottom = RECT {
left: 0,
top: client.bottom,
right: client.right,
bottom: pt2.y
};
let dc = GetDC(hwnd);
FillRect(dc, &top, brush);
FillRect(dc, &bottom, brush);
ReleaseDC(hwnd, dc);
},
WM_SIZE => {
SetWindowPos(hwnd, ptr::null_mut(), 0, 0, 0, 0, SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
},
_ => {}
}
None
});
*self.handler1.borrow_mut() = Some(handler1.unwrap());
}
}
}
impl PartialEq for Label {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
}
}
impl Drop for Label {
fn drop(&mut self) {
let handler = self.handler0.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
let handler = self.handler1.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
if let Some(bg) = self.background_brush {
unsafe { DeleteObject(bg as _); }
}
self.handle.destroy();
}
}
pub struct LabelBuilder<'a> {
text: &'a str,
size: (i32, i32),
position: (i32, i32),
background_color: Option<[u8; 3]>,
flags: Option<LabelFlags>,
ex_flags: u32,
font: Option<&'a Font>,
h_align: HTextAlign,
v_align: VTextAlign,
parent: Option<ControlHandle>
}
impl<'a> LabelBuilder<'a> {
pub fn flags(mut self, flags: LabelFlags) -> LabelBuilder<'a> {
self.flags = Some(flags);
self
}
pub fn ex_flags(mut self, flags: u32) -> LabelBuilder<'a> {
self.ex_flags = flags;
self
}
pub fn text(mut self, text: &'a str) -> LabelBuilder<'a> {
self.text = text;
self
}
pub fn size(mut self, size: (i32, i32)) -> LabelBuilder<'a> {
self.size = size;
self
}
pub fn position(mut self, pos: (i32, i32)) -> LabelBuilder<'a> {
self.position = pos;
self
}
pub fn font(mut self, font: Option<&'a Font>) -> LabelBuilder<'a> {
self.font = font;
self
}
pub fn background_color(mut self, color: Option<[u8;3]>) -> LabelBuilder<'a> {
self.background_color = color;
self
}
pub fn h_align(mut self, align: HTextAlign) -> LabelBuilder<'a> {
self.h_align = align;
self
}
pub fn v_align(mut self, align: VTextAlign) -> LabelBuilder<'a> {
self.v_align = align;
self
}
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> LabelBuilder<'a> {
self.parent = Some(p.into());
self
}
pub fn build(self, out: &mut Label) -> Result<(), NwgError> {
use winapi::um::winuser::{SS_LEFT, SS_RIGHT, SS_CENTER};
let mut flags = self.flags.map(|f| f.bits()).unwrap_or(out.flags());
match self.h_align {
HTextAlign::Left => { flags |= SS_LEFT; },
HTextAlign::Right => { flags |= SS_RIGHT; },
HTextAlign::Center => { flags |= SS_CENTER; },
}
let parent = match self.parent {
Some(p) => Ok(p),
None => Err(NwgError::no_parent("Label"))
}?;
// Drop the old object
*out = Label::default();
out.handle = ControlBase::build_hwnd()
.class_name(out.class_name())
.forced_flags(out.forced_flags())
.flags(flags)
.ex_flags(self.ex_flags)
.size(self.size)
.position(self.position)
.text(self.text)
.parent(Some(parent))
.build()?;
if self.font.is_some() {
out.set_font(self.font);
} else {
out.set_font(Font::global_default().as_ref());
}
out.hook_non_client_size(self.background_color, self.v_align);
Ok(())
}
}
| {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_size(handle, x, y, false) }
} | identifier_body |
label.rs | use winapi::um::{
winuser::{WS_VISIBLE, WS_DISABLED, SS_WORDELLIPSIS},
wingdi::DeleteObject
};
use winapi::shared::windef::HBRUSH;
use crate::win32::window_helper as wh;
use crate::win32::base_helper::check_hwnd;
use crate::{Font, NwgError, HTextAlign, VTextAlign, RawEventHandler, unbind_raw_event_handler};
use super::{ControlBase, ControlHandle};
use std::cell::RefCell;
const NOT_BOUND: &'static str = "Label is not yet bound to a winapi object";
const BAD_HANDLE: &'static str = "INTERNAL ERROR: Label handle is not HWND!";
bitflags! {
/**
The label flags
* NONE: No flags. Equivalent to a invisible blank label.
* VISIBLE: The label is immediatly visible after creation
* DISABLED: The label cannot be interacted with by the user. It also has a grayed out look.
*/
pub struct LabelFlags: u32 {
const NONE = 0;
const VISIBLE = WS_VISIBLE;
const DISABLED = WS_DISABLED;
/// Truncate the label if the text is too long. A label with this style CANNOT have multiple lines.
const ELIPSIS = SS_WORDELLIPSIS;
}
}
/**
A label is a single line of static text. Use `\r\n` to split the text on multiple lines.
Label is not behind any features.
**Builder parameters:**
* `parent`: **Required.** The label parent container.
* `text`: The label text.
* `size`: The label size.
* `position`: The label position.
* `enabled`: If the label is enabled. A disabled label won't trigger events
* `flags`: A combination of the LabelFlags values.
* `ex_flags`: A combination of win32 window extended flags. Unlike `flags`, ex_flags must be used straight from winapi
* `font`: The font used for the label text
* `background_color`: The background color of the label
* `h_align`: The horizontal aligment of the label
**Control events:**
* `OnLabelClick`: When the user click the label
* `OnLabelDoubleClick`: When the user double click a label
* `MousePress(_)`: Generic mouse press events on the label
* `OnMouseMove`: Generic mouse mouse event
* `OnMouseWheel`: Generic mouse wheel event
** Example **
```rust
use native_windows_gui as nwg;
fn build_label(label: &mut nwg::Label, window: &nwg::Window, font: &nwg::Font) {
nwg::Label::builder()
.text("Hello")
.font(Some(font))
.parent(window)
.build(label);
}
```
*/
#[derive(Default)]
pub struct Label {
pub handle: ControlHandle,
background_brush: Option<HBRUSH>,
handler0: RefCell<Option<RawEventHandler>>,
handler1: RefCell<Option<RawEventHandler>>,
}
impl Label {
pub fn builder<'a>() -> LabelBuilder<'a> {
LabelBuilder {
text: "A label",
size: (130, 25),
position: (0, 0),
flags: None,
ex_flags: 0,
font: None,
parent: None,
h_align: HTextAlign::Left,
v_align: VTextAlign::Center,
background_color: None
}
}
/// Return the font of the control
pub fn font(&self) -> Option<Font> {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
let font_handle = wh::get_window_font(handle);
if font_handle.is_null() {
None
} else {
Some(Font { handle: font_handle })
}
}
/// Set the font of the control
pub fn set_font(&self, font: Option<&Font>) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_font(handle, font.map(|f| f.handle), true); }
}
/// Return true if the control currently has the keyboard focus
pub fn focus(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_focus(handle) }
}
/// Set the keyboard focus on the button.
pub fn set_focus(&self) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_focus(handle); }
}
/// Return true if the control user can interact with the control, return false otherwise
pub fn enabled(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_enabled(handle) }
}
/// Enable or disable the control
pub fn set_enabled(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_enabled(handle, v) }
}
/// Return true if the control is visible to the user. Will return true even if the
/// control is outside of the parent client view (ex: at the position (10000, 10000))
pub fn visible(&self) -> bool {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_visibility(handle) }
}
/// Show or hide the control to the user
pub fn set_visible(&self, v: bool) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_visibility(handle, v) }
}
/// Return the size of the label in the parent window
pub fn size(&self) -> (u32, u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_size(handle) }
}
/// Set the size of the label in the parent window
pub fn set_size(&self, x: u32, y: u32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_size(handle, x, y, false) }
}
/// Return the position of the label in the parent window
pub fn position(&self) -> (i32, i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_position(handle) }
}
/// Set the position of the label in the parent window
pub fn set_position(&self, x: i32, y: i32) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_position(handle, x, y) }
}
/// Return the label text
pub fn text(&self) -> String {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::get_window_text(handle) }
}
/// Set the label text
pub fn set_text<'a>(&self, v: &'a str) {
let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE);
unsafe { wh::set_window_text(handle, v) }
}
/// Winapi class name used during control creation
pub fn class_name(&self) -> &'static str {
"STATIC"
}
/// Winapi base flags used during window creation
pub fn flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOPREFIX, SS_LEFT};
WS_VISIBLE | SS_NOPREFIX | SS_LEFT
}
/// Winapi flags required by the control
pub fn forced_flags(&self) -> u32 {
use winapi::um::winuser::{SS_NOTIFY, WS_CHILD};
WS_CHILD | SS_NOTIFY
}
/// Center the text vertically.
fn hook_non_client_size(&mut self, bg: Option<[u8; 3]>, v_align: VTextAlign) {
use crate::bind_raw_event_handler_inner;
use winapi::shared::windef::{HWND, HGDIOBJ, RECT, POINT};
use winapi::shared::{basetsd::UINT_PTR, minwindef::LRESULT};
use winapi::um::winuser::{WM_CTLCOLORSTATIC, WM_NCCALCSIZE, WM_NCPAINT, WM_SIZE, DT_CALCRECT, DT_LEFT, NCCALCSIZE_PARAMS, COLOR_WINDOW};
use winapi::um::winuser::{SWP_NOOWNERZORDER, SWP_NOSIZE, SWP_NOMOVE, SWP_FRAMECHANGED};
use winapi::um::winuser::{GetDC, DrawTextW, ReleaseDC, GetClientRect, GetWindowRect, FillRect, ScreenToClient, SetWindowPos, GetWindowTextW, GetWindowTextLengthW};
use winapi::um::wingdi::{SelectObject, CreateSolidBrush, RGB};
use std::{mem, ptr};
if self.handle.blank() { panic!("{}", NOT_BOUND); }
let handle = self.handle.hwnd().expect(BAD_HANDLE);
let parent_handle = ControlHandle::Hwnd(wh::get_window_parent(handle));
let brush = match bg {
Some(c) => {
let b = unsafe { CreateSolidBrush(RGB(c[0], c[1], c[2])) };
self.background_brush = Some(b);
b
},
None => COLOR_WINDOW as HBRUSH
};
unsafe {
if bg.is_some() {
let handler0 = bind_raw_event_handler_inner(&parent_handle, handle as UINT_PTR, move |_hwnd, msg, _w, l| {
match msg {
WM_CTLCOLORSTATIC => {
let child = l as HWND;
if child == handle {
return Some(brush as LRESULT);
}
},
_ => {}
}
None
});
*self.handler0.borrow_mut() = Some(handler0.unwrap());
}
let handler1 = bind_raw_event_handler_inner(&self.handle, 0, move |hwnd, msg, w, l| {
match msg {
WM_NCCALCSIZE => {
if w == 0 { return None }
// Calculate client area height needed for a font
let font_handle = wh::get_window_font(hwnd);
let mut r: RECT = mem::zeroed();
let dc = GetDC(hwnd);
let old = SelectObject(dc, font_handle as HGDIOBJ);
let mut newline_count = 1;
let buffer_size = GetWindowTextLengthW(handle) as usize;
match buffer_size == 0 {
true => {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
},
false => {
let mut buffer: Vec<u16> = vec![0; buffer_size + 1];
if GetWindowTextW(handle, buffer.as_mut_ptr(), buffer_size as _) == 0 | else {
for &c in buffer.iter() {
if c == b'\n' as u16 {
newline_count += 1;
}
}
DrawTextW(dc, buffer.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
}
}
}
let client_height = r.bottom * newline_count;
SelectObject(dc, old);
ReleaseDC(hwnd, dc);
// Calculate NC area to center text.
let mut client: RECT = mem::zeroed();
let mut window: RECT = mem::zeroed();
GetClientRect(hwnd, &mut client);
GetWindowRect(hwnd, &mut window);
let window_height = window.bottom - window.top;
let info_ptr: *mut NCCALCSIZE_PARAMS = l as *mut NCCALCSIZE_PARAMS;
let info = &mut *info_ptr;
match v_align {
VTextAlign::Top => {
info.rgrc[0].bottom -= window_height - client_height;
},
VTextAlign::Center => {
let center = ((window_height - client_height) / 2) - 1;
info.rgrc[0].top += center;
info.rgrc[0].bottom -= center;
},
VTextAlign::Bottom => {
info.rgrc[0].top += window_height - client_height;
},
}
},
WM_NCPAINT => {
let mut window: RECT = mem::zeroed();
let mut client: RECT = mem::zeroed();
GetWindowRect(hwnd, &mut window);
GetClientRect(hwnd, &mut client);
let mut pt1 = POINT {x: window.left, y: window.top};
ScreenToClient(hwnd, &mut pt1);
let mut pt2 = POINT {x: window.right, y: window.bottom};
ScreenToClient(hwnd, &mut pt2);
let top = RECT {
left: 0,
top: pt1.y,
right: client.right,
bottom: client.top
};
let bottom = RECT {
left: 0,
top: client.bottom,
right: client.right,
bottom: pt2.y
};
let dc = GetDC(hwnd);
FillRect(dc, &top, brush);
FillRect(dc, &bottom, brush);
ReleaseDC(hwnd, dc);
},
WM_SIZE => {
SetWindowPos(hwnd, ptr::null_mut(), 0, 0, 0, 0, SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
},
_ => {}
}
None
});
*self.handler1.borrow_mut() = Some(handler1.unwrap());
}
}
}
impl PartialEq for Label {
fn eq(&self, other: &Self) -> bool {
self.handle == other.handle
}
}
impl Drop for Label {
fn drop(&mut self) {
let handler = self.handler0.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
let handler = self.handler1.borrow();
if let Some(h) = handler.as_ref() {
drop(unbind_raw_event_handler(h));
}
if let Some(bg) = self.background_brush {
unsafe { DeleteObject(bg as _); }
}
self.handle.destroy();
}
}
pub struct LabelBuilder<'a> {
text: &'a str,
size: (i32, i32),
position: (i32, i32),
background_color: Option<[u8; 3]>,
flags: Option<LabelFlags>,
ex_flags: u32,
font: Option<&'a Font>,
h_align: HTextAlign,
v_align: VTextAlign,
parent: Option<ControlHandle>
}
impl<'a> LabelBuilder<'a> {
pub fn flags(mut self, flags: LabelFlags) -> LabelBuilder<'a> {
self.flags = Some(flags);
self
}
pub fn ex_flags(mut self, flags: u32) -> LabelBuilder<'a> {
self.ex_flags = flags;
self
}
pub fn text(mut self, text: &'a str) -> LabelBuilder<'a> {
self.text = text;
self
}
pub fn size(mut self, size: (i32, i32)) -> LabelBuilder<'a> {
self.size = size;
self
}
pub fn position(mut self, pos: (i32, i32)) -> LabelBuilder<'a> {
self.position = pos;
self
}
pub fn font(mut self, font: Option<&'a Font>) -> LabelBuilder<'a> {
self.font = font;
self
}
pub fn background_color(mut self, color: Option<[u8;3]>) -> LabelBuilder<'a> {
self.background_color = color;
self
}
pub fn h_align(mut self, align: HTextAlign) -> LabelBuilder<'a> {
self.h_align = align;
self
}
pub fn v_align(mut self, align: VTextAlign) -> LabelBuilder<'a> {
self.v_align = align;
self
}
pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> LabelBuilder<'a> {
self.parent = Some(p.into());
self
}
pub fn build(self, out: &mut Label) -> Result<(), NwgError> {
use winapi::um::winuser::{SS_LEFT, SS_RIGHT, SS_CENTER};
let mut flags = self.flags.map(|f| f.bits()).unwrap_or(out.flags());
match self.h_align {
HTextAlign::Left => { flags |= SS_LEFT; },
HTextAlign::Right => { flags |= SS_RIGHT; },
HTextAlign::Center => { flags |= SS_CENTER; },
}
let parent = match self.parent {
Some(p) => Ok(p),
None => Err(NwgError::no_parent("Label"))
}?;
// Drop the old object
*out = Label::default();
out.handle = ControlBase::build_hwnd()
.class_name(out.class_name())
.forced_flags(out.forced_flags())
.flags(flags)
.ex_flags(self.ex_flags)
.size(self.size)
.position(self.position)
.text(self.text)
.parent(Some(parent))
.build()?;
if self.font.is_some() {
out.set_font(self.font);
} else {
out.set_font(Font::global_default().as_ref());
}
out.hook_non_client_size(self.background_color, self.v_align);
Ok(())
}
}
| {
let calc: [u16;2] = [75, 121];
DrawTextW(dc, calc.as_ptr(), 2, &mut r, DT_CALCRECT | DT_LEFT);
} | conditional_block |
complex_types_macros.rs | extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate rusted_cypher;
use rusted_cypher::GraphClient;
use rusted_cypher::cypher::result::Row;
const URI: &'static str = "http://neo4j:neo4j@127.0.0.1:7474/db/data";
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Language {
name: String,
level: String,
safe: bool,
}
#[test]
fn without_params() {
let graph = GraphClient::connect(URI).unwrap();
let stmt = cypher_stmt!("MATCH (n:NTLY_INTG_TEST_MACROS_1) RETURN n").unwrap();
let result = graph.exec(stmt);
assert!(result.is_ok());
}
#[test]
fn save_retrive_struct() {
let rust = Language {
name: "Rust".to_owned(),
level: "low".to_owned(),
safe: true,
};
let graph = GraphClient::connect(URI).unwrap();
let stmt = cypher_stmt!("CREATE (n:NTLY_INTG_TEST_MACROS_2 {lang}) RETURN n", {
"lang" => &rust
}).unwrap();
let results = graph.exec(stmt).unwrap();
let rows: Vec<Row> = results.rows().take(1).collect();
let row = rows.first().unwrap();
| let lang: Language = row.get("n").unwrap();
assert_eq!(rust, lang);
graph.exec("MATCH (n:NTLY_INTG_TEST_MACROS_2) DELETE n").unwrap();
} | random_line_split | |
complex_types_macros.rs | extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate rusted_cypher;
use rusted_cypher::GraphClient;
use rusted_cypher::cypher::result::Row;
const URI: &'static str = "http://neo4j:neo4j@127.0.0.1:7474/db/data";
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Language {
name: String,
level: String,
safe: bool,
}
#[test]
fn | () {
let graph = GraphClient::connect(URI).unwrap();
let stmt = cypher_stmt!("MATCH (n:NTLY_INTG_TEST_MACROS_1) RETURN n").unwrap();
let result = graph.exec(stmt);
assert!(result.is_ok());
}
#[test]
fn save_retrive_struct() {
let rust = Language {
name: "Rust".to_owned(),
level: "low".to_owned(),
safe: true,
};
let graph = GraphClient::connect(URI).unwrap();
let stmt = cypher_stmt!("CREATE (n:NTLY_INTG_TEST_MACROS_2 {lang}) RETURN n", {
"lang" => &rust
}).unwrap();
let results = graph.exec(stmt).unwrap();
let rows: Vec<Row> = results.rows().take(1).collect();
let row = rows.first().unwrap();
let lang: Language = row.get("n").unwrap();
assert_eq!(rust, lang);
graph.exec("MATCH (n:NTLY_INTG_TEST_MACROS_2) DELETE n").unwrap();
}
| without_params | identifier_name |
eew.rs | use chrono::{DateTime, Utc};
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum IssuePattern { Cancel, IntensityOnly, LowAccuracy, HighAccuracy }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Source { Tokyo, Osaka }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Kind { Normal, Drill, Cancel, DrillCancel, Reference, Trial }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Status { Normal, Correction, CancelCorrection, LastWithCorrection, Last, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum EpicenterAccuracy {
Single, Territory, GridSearchLow, GridSearchHigh,
NIEDLow, NIEDHigh, EPOSLow, EPOSHigh, Unknown
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum DepthAccuracy {
Single, Territory, GridSearchLow, GridSearchHigh,
NIEDLow, NIEDHigh, EPOSLow, EPOSHigh, Unknown
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum MagnitudeAccuracy {
NIED, PWave, PSMixed, SWave, EPOS, Level, Unknown
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum EpicenterCategory { Land, Sea, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum WarningStatus { Forecast, Alert, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum IntensityChange { Same, Up, Down, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum ChangeReason { Nothing, Magnitude, Epicenter, Mixed, Depth, Plum, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum WaveStatus { Unreached, Reached, Plum, Unknown }
#[derive(Ord, PartialOrd, Eq, PartialEq, Debug, Clone, Copy)]
pub enum IntensityClass {
Zero, One, Two, Three, Four, FiveLower, FiveUpper, SixLower, SixUpper, Seven
}
impl IntensityClass {
pub fn new(intensity: f32) -> IntensityClass
{
match intensity {
x if x < 0.5 => IntensityClass::Zero,
x if x < 1.5 => IntensityClass::One,
x if x < 2.5 => IntensityClass::Two,
x if x < 3.5 => IntensityClass::Three,
x if x < 4.5 => IntensityClass::Four,
x if x < 5.0 => IntensityClass::FiveLower,
x if x < 5.5 => IntensityClass::FiveUpper,
x if x < 6.0 => IntensityClass::SixLower,
x if x < 6.5 => IntensityClass::SixUpper,
_ => IntensityClass::Seven,
}
}
}
#[derive(PartialEq, Debug, Clone)]
pub struct AreaEEW {
pub area_name: String,
pub minimum_intensity: IntensityClass,
pub maximum_intensity: Option<IntensityClass>,
pub reach_at: Option<DateTime<Utc>>,
pub warning_status: WarningStatus,
pub wave_status: WaveStatus,
}
#[derive(PartialEq, Debug, Clone)]
pub struct | {
pub issue_pattern: IssuePattern,
pub source: Source,
pub kind: Kind,
pub issued_at: DateTime<Utc>,
pub occurred_at: DateTime<Utc>,
pub id: String,
pub status: Status,
pub number: u32, // we don't accept an EEW which has no telegram number
pub detail: Option<EEWDetail>,
}
#[derive(PartialEq, Debug, Clone)]
pub struct EEWDetail {
pub epicenter_name: String,
pub epicenter: (f32, f32),
pub depth: Option<f32>,
pub magnitude: Option<f32>,
pub maximum_intensity: Option<IntensityClass>,
pub epicenter_accuracy: EpicenterAccuracy,
pub depth_accuracy: DepthAccuracy,
pub magnitude_accuracy: MagnitudeAccuracy,
pub epicenter_category: EpicenterCategory,
pub warning_status: WarningStatus,
pub intensity_change: IntensityChange,
pub change_reason: ChangeReason,
pub plum: bool,
pub area_info: Vec<AreaEEW>,
}
| EEW | identifier_name |
eew.rs | use chrono::{DateTime, Utc};
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum IssuePattern { Cancel, IntensityOnly, LowAccuracy, HighAccuracy }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Source { Tokyo, Osaka }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Kind { Normal, Drill, Cancel, DrillCancel, Reference, Trial }
| #[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Status { Normal, Correction, CancelCorrection, LastWithCorrection, Last, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum EpicenterAccuracy {
Single, Territory, GridSearchLow, GridSearchHigh,
NIEDLow, NIEDHigh, EPOSLow, EPOSHigh, Unknown
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum DepthAccuracy {
Single, Territory, GridSearchLow, GridSearchHigh,
NIEDLow, NIEDHigh, EPOSLow, EPOSHigh, Unknown
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum MagnitudeAccuracy {
NIED, PWave, PSMixed, SWave, EPOS, Level, Unknown
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum EpicenterCategory { Land, Sea, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum WarningStatus { Forecast, Alert, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum IntensityChange { Same, Up, Down, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum ChangeReason { Nothing, Magnitude, Epicenter, Mixed, Depth, Plum, Unknown }
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum WaveStatus { Unreached, Reached, Plum, Unknown }
#[derive(Ord, PartialOrd, Eq, PartialEq, Debug, Clone, Copy)]
pub enum IntensityClass {
Zero, One, Two, Three, Four, FiveLower, FiveUpper, SixLower, SixUpper, Seven
}
impl IntensityClass {
pub fn new(intensity: f32) -> IntensityClass
{
match intensity {
x if x < 0.5 => IntensityClass::Zero,
x if x < 1.5 => IntensityClass::One,
x if x < 2.5 => IntensityClass::Two,
x if x < 3.5 => IntensityClass::Three,
x if x < 4.5 => IntensityClass::Four,
x if x < 5.0 => IntensityClass::FiveLower,
x if x < 5.5 => IntensityClass::FiveUpper,
x if x < 6.0 => IntensityClass::SixLower,
x if x < 6.5 => IntensityClass::SixUpper,
_ => IntensityClass::Seven,
}
}
}
#[derive(PartialEq, Debug, Clone)]
pub struct AreaEEW {
pub area_name: String,
pub minimum_intensity: IntensityClass,
pub maximum_intensity: Option<IntensityClass>,
pub reach_at: Option<DateTime<Utc>>,
pub warning_status: WarningStatus,
pub wave_status: WaveStatus,
}
#[derive(PartialEq, Debug, Clone)]
pub struct EEW {
pub issue_pattern: IssuePattern,
pub source: Source,
pub kind: Kind,
pub issued_at: DateTime<Utc>,
pub occurred_at: DateTime<Utc>,
pub id: String,
pub status: Status,
pub number: u32, // we don't accept an EEW which has no telegram number
pub detail: Option<EEWDetail>,
}
#[derive(PartialEq, Debug, Clone)]
pub struct EEWDetail {
pub epicenter_name: String,
pub epicenter: (f32, f32),
pub depth: Option<f32>,
pub magnitude: Option<f32>,
pub maximum_intensity: Option<IntensityClass>,
pub epicenter_accuracy: EpicenterAccuracy,
pub depth_accuracy: DepthAccuracy,
pub magnitude_accuracy: MagnitudeAccuracy,
pub epicenter_category: EpicenterCategory,
pub warning_status: WarningStatus,
pub intensity_change: IntensityChange,
pub change_reason: ChangeReason,
pub plum: bool,
pub area_info: Vec<AreaEEW>,
} | random_line_split | |
service_callback_api_schema.py | from app.schema_validation.definitions import https_url, uuid
create_service_callback_api_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "POST service callback/inbound api schema", | "updated_by_id": uuid
},
"required": ["url", "bearer_token", "updated_by_id"]
}
update_service_callback_api_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "POST service callback/inbound api schema",
"type": "object",
"title": "Create service callback/inbound api",
"properties": {
"url": https_url,
"bearer_token": {"type": "string", "minLength": 10},
"updated_by_id": uuid
},
"required": ["updated_by_id"]
} | "type": "object",
"title": "Create service callback/inbound api",
"properties": {
"url": https_url,
"bearer_token": {"type": "string", "minLength": 10}, | random_line_split |
vault-keyring.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2014, Matt Martz <matt@sivel.net>
# (c) 2016, Justin Mayer <https://justinmayer.com/>
#
# This file is part of Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
# =============================================================================
#
# This script is to be used with vault_password_file or --vault-password-file
# to retrieve the vault password via your OS's native keyring application.
#
# This file *MUST* be saved with executable permissions. Otherwise, Ansible
# will try to parse as a password file and display: "ERROR! Decryption failed"
#
# The `keyring` Python module is required: https://pypi.python.org/pypi/keyring
#
# By default, this script will store the specified password in the keyring of
# the user that invokes the script. To specify a user keyring, add a [vault]
# section to your ansible.cfg file with a 'username' option. Example:
#
# [vault]
# username = 'ansible-vault'
#
# Another optional setting is for the key name, which allows you to use this
# script to handle multiple project vaults with different passwords:
#
# [vault]
# keyname = 'ansible-vault-yourproject'
#
# You can configure the `vault_password_file` option in ansible.cfg:
#
# [defaults]
# ...
# vault_password_file = /path/to/vault-keyring.py
# ...
#
# To set your password, `cd` to your project directory and run:
#
# python /path/to/vault-keyring.py set
#
# If you choose not to configure the path to `vault_password_file` in
# ansible.cfg, your `ansible-playbook` command might look like:
#
# ansible-playbook --vault-password-file=/path/to/vault-keyring.py site.yml
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import sys
import getpass
import keyring
import ansible.constants as C
def | ():
(parser, config_path) = C.load_config_file()
if parser.has_option('vault', 'username'):
username = parser.get('vault', 'username')
else:
username = getpass.getuser()
if parser.has_option('vault', 'keyname'):
keyname = parser.get('vault', 'keyname')
else:
keyname = 'ansible'
if len(sys.argv) == 2 and sys.argv[1] == 'set':
intro = 'Storing password in "{}" user keyring using key name: {}\n'
sys.stdout.write(intro.format(username, keyname))
password = getpass.getpass()
confirm = getpass.getpass('Confirm password: ')
if password == confirm:
keyring.set_password(keyname, username, password)
else:
sys.stderr.write('Passwords do not match\n')
sys.exit(1)
else:
sys.stdout.write('{}\n'.format(keyring.get_password(keyname,
username)))
sys.exit(0)
if __name__ == '__main__':
main()
| main | identifier_name |
vault-keyring.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2014, Matt Martz <matt@sivel.net>
# (c) 2016, Justin Mayer <https://justinmayer.com/>
#
# This file is part of Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
# =============================================================================
#
# This script is to be used with vault_password_file or --vault-password-file
# to retrieve the vault password via your OS's native keyring application.
#
# This file *MUST* be saved with executable permissions. Otherwise, Ansible
# will try to parse as a password file and display: "ERROR! Decryption failed"
#
# The `keyring` Python module is required: https://pypi.python.org/pypi/keyring
#
# By default, this script will store the specified password in the keyring of
# the user that invokes the script. To specify a user keyring, add a [vault]
# section to your ansible.cfg file with a 'username' option. Example:
#
# [vault]
# username = 'ansible-vault'
#
# Another optional setting is for the key name, which allows you to use this
# script to handle multiple project vaults with different passwords:
#
# [vault]
# keyname = 'ansible-vault-yourproject'
#
# You can configure the `vault_password_file` option in ansible.cfg:
#
# [defaults]
# ...
# vault_password_file = /path/to/vault-keyring.py
# ...
#
# To set your password, `cd` to your project directory and run:
#
# python /path/to/vault-keyring.py set
#
# If you choose not to configure the path to `vault_password_file` in
# ansible.cfg, your `ansible-playbook` command might look like:
#
# ansible-playbook --vault-password-file=/path/to/vault-keyring.py site.yml
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import sys
import getpass
import keyring
import ansible.constants as C
def main():
(parser, config_path) = C.load_config_file()
if parser.has_option('vault', 'username'):
username = parser.get('vault', 'username')
else:
username = getpass.getuser()
if parser.has_option('vault', 'keyname'):
keyname = parser.get('vault', 'keyname')
else:
|
if len(sys.argv) == 2 and sys.argv[1] == 'set':
intro = 'Storing password in "{}" user keyring using key name: {}\n'
sys.stdout.write(intro.format(username, keyname))
password = getpass.getpass()
confirm = getpass.getpass('Confirm password: ')
if password == confirm:
keyring.set_password(keyname, username, password)
else:
sys.stderr.write('Passwords do not match\n')
sys.exit(1)
else:
sys.stdout.write('{}\n'.format(keyring.get_password(keyname,
username)))
sys.exit(0)
if __name__ == '__main__':
main()
| keyname = 'ansible' | conditional_block |
vault-keyring.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2014, Matt Martz <matt@sivel.net>
# (c) 2016, Justin Mayer <https://justinmayer.com/>
#
# This file is part of Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
# =============================================================================
#
# This script is to be used with vault_password_file or --vault-password-file
# to retrieve the vault password via your OS's native keyring application.
#
# This file *MUST* be saved with executable permissions. Otherwise, Ansible
# will try to parse as a password file and display: "ERROR! Decryption failed"
#
# The `keyring` Python module is required: https://pypi.python.org/pypi/keyring
#
# By default, this script will store the specified password in the keyring of
# the user that invokes the script. To specify a user keyring, add a [vault]
# section to your ansible.cfg file with a 'username' option. Example:
#
# [vault]
# username = 'ansible-vault'
#
# Another optional setting is for the key name, which allows you to use this
# script to handle multiple project vaults with different passwords:
#
# [vault]
# keyname = 'ansible-vault-yourproject'
#
# You can configure the `vault_password_file` option in ansible.cfg:
#
# [defaults]
# ...
# vault_password_file = /path/to/vault-keyring.py
# ...
#
# To set your password, `cd` to your project directory and run:
#
# python /path/to/vault-keyring.py set
#
# If you choose not to configure the path to `vault_password_file` in
# ansible.cfg, your `ansible-playbook` command might look like:
#
# ansible-playbook --vault-password-file=/path/to/vault-keyring.py site.yml
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import sys
import getpass
import keyring
import ansible.constants as C
def main():
|
if __name__ == '__main__':
main()
| (parser, config_path) = C.load_config_file()
if parser.has_option('vault', 'username'):
username = parser.get('vault', 'username')
else:
username = getpass.getuser()
if parser.has_option('vault', 'keyname'):
keyname = parser.get('vault', 'keyname')
else:
keyname = 'ansible'
if len(sys.argv) == 2 and sys.argv[1] == 'set':
intro = 'Storing password in "{}" user keyring using key name: {}\n'
sys.stdout.write(intro.format(username, keyname))
password = getpass.getpass()
confirm = getpass.getpass('Confirm password: ')
if password == confirm:
keyring.set_password(keyname, username, password)
else:
sys.stderr.write('Passwords do not match\n')
sys.exit(1)
else:
sys.stdout.write('{}\n'.format(keyring.get_password(keyname,
username)))
sys.exit(0) | identifier_body |
vault-keyring.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2014, Matt Martz <matt@sivel.net>
# (c) 2016, Justin Mayer <https://justinmayer.com/>
#
# This file is part of Ansible.
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
# =============================================================================
#
# This script is to be used with vault_password_file or --vault-password-file
# to retrieve the vault password via your OS's native keyring application.
#
# This file *MUST* be saved with executable permissions. Otherwise, Ansible
# will try to parse as a password file and display: "ERROR! Decryption failed"
#
# The `keyring` Python module is required: https://pypi.python.org/pypi/keyring
#
# By default, this script will store the specified password in the keyring of
# the user that invokes the script. To specify a user keyring, add a [vault]
# section to your ansible.cfg file with a 'username' option. Example:
#
# [vault]
# username = 'ansible-vault'
#
# Another optional setting is for the key name, which allows you to use this
# script to handle multiple project vaults with different passwords:
#
# [vault]
# keyname = 'ansible-vault-yourproject'
#
# You can configure the `vault_password_file` option in ansible.cfg:
#
# [defaults]
# ...
# vault_password_file = /path/to/vault-keyring.py
# ...
#
# To set your password, `cd` to your project directory and run:
#
# python /path/to/vault-keyring.py set
#
# If you choose not to configure the path to `vault_password_file` in
# ansible.cfg, your `ansible-playbook` command might look like:
#
# ansible-playbook --vault-password-file=/path/to/vault-keyring.py site.yml
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import sys
import getpass
import keyring
import ansible.constants as C
| if parser.has_option('vault', 'username'):
username = parser.get('vault', 'username')
else:
username = getpass.getuser()
if parser.has_option('vault', 'keyname'):
keyname = parser.get('vault', 'keyname')
else:
keyname = 'ansible'
if len(sys.argv) == 2 and sys.argv[1] == 'set':
intro = 'Storing password in "{}" user keyring using key name: {}\n'
sys.stdout.write(intro.format(username, keyname))
password = getpass.getpass()
confirm = getpass.getpass('Confirm password: ')
if password == confirm:
keyring.set_password(keyname, username, password)
else:
sys.stderr.write('Passwords do not match\n')
sys.exit(1)
else:
sys.stdout.write('{}\n'.format(keyring.get_password(keyname,
username)))
sys.exit(0)
if __name__ == '__main__':
main() | def main():
(parser, config_path) = C.load_config_file() | random_line_split |
fn_must_use.rs | // check-pass
#![warn(unused_must_use)]
#[derive(PartialEq, Eq)]
struct MyStruct {
n: usize,
}
impl MyStruct {
#[must_use]
fn need_to_use_this_method_value(&self) -> usize {
self.n
}
#[must_use]
fn need_to_use_this_associated_function_value() -> isize {
-1
}
}
trait EvenNature {
#[must_use = "no side effects"]
fn is_even(&self) -> bool;
}
impl EvenNature for MyStruct {
fn is_even(&self) -> bool {
self.n % 2 == 0
}
}
trait Replaceable {
fn replace(&mut self, substitute: usize) -> usize;
}
impl Replaceable for MyStruct {
// ↓ N.b.: `#[must_use]` attribute on a particular trait implementation
// method won't work; the attribute should be on the method signature in
// the trait's definition.
#[must_use]
fn replace(&mut self, substitute: usize) -> usize {
let previously = self.n;
self.n = substitute;
previously
}
}
#[must_use = "it's important"]
fn need_to_use_this_value() -> bool {
false
}
fn main() {
| need_to_use_this_value(); //~ WARN unused return value
let mut m = MyStruct { n: 2 };
let n = MyStruct { n: 3 };
m.need_to_use_this_method_value(); //~ WARN unused return value
m.is_even(); // trait method!
//~^ WARN unused return value
MyStruct::need_to_use_this_associated_function_value();
//~^ WARN unused return value
m.replace(3); // won't warn (annotation needs to be in trait definition)
// comparison methods are `must_use`
2.eq(&3); //~ WARN unused return value
m.eq(&n); //~ WARN unused return value
// lint includes comparison operators
2 == 3; //~ WARN unused comparison
m == n; //~ WARN unused comparison
}
| identifier_body | |
fn_must_use.rs | // check-pass
#![warn(unused_must_use)]
#[derive(PartialEq, Eq)]
struct MyStruct {
n: usize,
}
impl MyStruct {
#[must_use]
fn need_to_use_this_method_value(&self) -> usize { | }
#[must_use]
fn need_to_use_this_associated_function_value() -> isize {
-1
}
}
trait EvenNature {
#[must_use = "no side effects"]
fn is_even(&self) -> bool;
}
impl EvenNature for MyStruct {
fn is_even(&self) -> bool {
self.n % 2 == 0
}
}
trait Replaceable {
fn replace(&mut self, substitute: usize) -> usize;
}
impl Replaceable for MyStruct {
// ↓ N.b.: `#[must_use]` attribute on a particular trait implementation
// method won't work; the attribute should be on the method signature in
// the trait's definition.
#[must_use]
fn replace(&mut self, substitute: usize) -> usize {
let previously = self.n;
self.n = substitute;
previously
}
}
#[must_use = "it's important"]
fn need_to_use_this_value() -> bool {
false
}
fn main() {
need_to_use_this_value(); //~ WARN unused return value
let mut m = MyStruct { n: 2 };
let n = MyStruct { n: 3 };
m.need_to_use_this_method_value(); //~ WARN unused return value
m.is_even(); // trait method!
//~^ WARN unused return value
MyStruct::need_to_use_this_associated_function_value();
//~^ WARN unused return value
m.replace(3); // won't warn (annotation needs to be in trait definition)
// comparison methods are `must_use`
2.eq(&3); //~ WARN unused return value
m.eq(&n); //~ WARN unused return value
// lint includes comparison operators
2 == 3; //~ WARN unused comparison
m == n; //~ WARN unused comparison
} | self.n | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.