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 | // Copyright 2014-2015 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.
//! The Rust compiler.
//!
//! # Note
//!
//! This API is completely unstable and subject to change.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_driver"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(box_syntax)]
#![feature(libc)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(set_stdio)]
#![feature(staged_api)]
#![feature(vec_push_all)]
extern crate arena;
extern crate flate;
extern crate getopts;
extern crate graphviz;
extern crate libc;
extern crate rustc;
extern crate rustc_back;
extern crate rustc_borrowck;
extern crate rustc_lint;
extern crate rustc_privacy;
extern crate rustc_resolve;
extern crate rustc_trans;
extern crate rustc_typeck;
extern crate serialize;
extern crate rustc_llvm as llvm;
#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
pub use syntax::diagnostic;
use driver::CompileController;
use pretty::{PpMode, UserIdentifiedItem};
use rustc_resolve as resolve;
use rustc_trans::back::link;
use rustc_trans::save;
use rustc::session::{config, Session, build_session};
use rustc::session::config::{Input, PrintRequest};
use rustc::lint::Lint;
use rustc::lint;
use rustc::metadata;
use rustc::util::common::time;
use std::cmp::Ordering::Equal;
use std::env;
use std::io::{self, Read, Write};
use std::iter::repeat;
use std::path::PathBuf;
use std::process;
use std::str;
use std::sync::{Arc, Mutex};
use std::thread;
use rustc::session::early_error;
use syntax::ast;
use syntax::parse;
use syntax::diagnostic::Emitter;
use syntax::diagnostics;
#[cfg(test)]
pub mod test;
pub mod driver;
pub mod pretty;
const BUG_REPORT_URL: &'static str =
"https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.md#bug-reports";
pub fn run(args: Vec<String>) -> isize {
monitor(move || run_compiler(&args, &mut RustcDefaultCalls));
0
}
// Parse args and run the compiler. This is the primary entry point for rustc.
// See comments on CompilerCalls below for details about the callbacks argument.
pub fn run_compiler<'a>(args: &[String],
callbacks: &mut CompilerCalls<'a>) {
macro_rules! do_or_return {($expr: expr) => {
match $expr {
Compilation::Stop => return,
Compilation::Continue => {}
}
}}
let matches = match handle_options(args.to_vec()) {
Some(matches) => matches,
None => return
};
let descriptions = diagnostics_registry();
do_or_return!(callbacks.early_callback(&matches, &descriptions));
let sopts = config::build_session_options(&matches);
let (odir, ofile) = make_output(&matches);
let (input, input_file_path) = match make_input(&matches.free) {
Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) {
Some((input, input_file_path)) => (input, input_file_path),
None => return
}
};
let mut sess = build_session(sopts, input_file_path, descriptions);
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
if sess.unstable_options() {
sess.opts.show_span = matches.opt_str("show-span");
}
let cfg = config::build_configuration(&sess);
do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile));
// It is somewhat unfortunate that this is hardwired in - this is forced by
// the fact that pretty_print_input requires the session by value.
let pretty = callbacks.parse_pretty(&sess, &matches);
match pretty {
Some((ppm, opt_uii)) => {
pretty::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
return;
}
None => {/* continue */ }
}
let plugins = sess.opts.debugging_opts.extra_plugins.clone();
let control = callbacks.build_controller(&sess);
driver::compile_input(sess, cfg, &input, &odir, &ofile, Some(plugins), control);
}
// Extract output directory and file from matches.
fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
(odir, ofile)
}
// Extract input (string or file and optional path) from matches.
fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
if free_matches.len() == 1 {
let ifile = &free_matches[0][..];
if ifile == "-" {
let mut src = String::new();
io::stdin().read_to_string(&mut src).unwrap();
Some((Input::Str(src), None))
} else {
Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile))))
}
} else {
None
}
}
// Whether to stop or continue compilation.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum | {
Stop,
Continue,
}
impl Compilation {
pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
match self {
Compilation::Stop => Compilation::Stop,
Compilation::Continue => next()
}
}
}
// A trait for customising the compilation process. Offers a number of hooks for
// executing custom code or customising input.
pub trait CompilerCalls<'a> {
// Hook for a callback early in the process of handling arguments. This will
// be called straight after options have been parsed but before anything
// else (e.g., selecting input and output).
fn early_callback(&mut self,
&getopts::Matches,
&diagnostics::registry::Registry)
-> Compilation;
// Hook for a callback late in the process of handling arguments. This will
// be called just before actual compilation starts (and before build_controller
// is called), after all arguments etc. have been completely handled.
fn late_callback(&mut self,
&getopts::Matches,
&Session,
&Input,
&Option<PathBuf>,
&Option<PathBuf>)
-> Compilation;
// Called after we extract the input from the arguments. Gives the implementer
// an opportunity to change the inputs or to add some custom input handling.
// The default behaviour is to simply pass through the inputs.
fn some_input(&mut self, input: Input, input_path: Option<PathBuf>)
-> (Input, Option<PathBuf>) {
(input, input_path)
}
// Called after we extract the input from the arguments if there is no valid
// input. Gives the implementer an opportunity to supply alternate input (by
// returning a Some value) or to add custom behaviour for this error such as
// emitting error messages. Returning None will cause compilation to stop
// at this point.
fn no_input(&mut self,
&getopts::Matches,
&config::Options,
&Option<PathBuf>,
&Option<PathBuf>,
&diagnostics::registry::Registry)
-> Option<(Input, Option<PathBuf>)>;
// Parse pretty printing information from the arguments. The implementer can
// choose to ignore this (the default will return None) which will skip pretty
// printing. If you do want to pretty print, it is recommended to use the
// implementation of this method from RustcDefaultCalls.
// FIXME, this is a terrible bit of API. Parsing of pretty printing stuff
// should be done as part of the framework and the implementor should customise
// handling of it. However, that is not possible atm because pretty printing
// essentially goes off and takes another path through the compiler which
// means the session is either moved or not depending on what parse_pretty
// returns (we could fix this by cloning, but it's another hack). The proper
// solution is to handle pretty printing as if it were a compiler extension,
// extending CompileController to make this work (see for example the treatment
// of save-analysis in RustcDefaultCalls::build_controller).
fn parse_pretty(&mut self,
_sess: &Session,
_matches: &getopts::Matches)
-> Option<(PpMode, Option<UserIdentifiedItem>)> {
None
}
// Create a CompilController struct for controlling the behaviour of compilation.
fn build_controller(&mut self, &Session) -> CompileController<'a>;
}
// CompilerCalls instance for a regular rustc build.
#[derive(Copy, Clone)]
pub struct RustcDefaultCalls;
impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
fn early_callback(&mut self,
matches: &getopts::Matches,
descriptions: &diagnostics::registry::Registry)
-> Compilation {
match matches.opt_str("explain") {
Some(ref code) => {
match descriptions.find_description(&code[..]) {
Some(ref description) => {
// Slice off the leading newline and print.
print!("{}", &description[1..]);
}
None => {
early_error(&format!("no extended information for {}", code));
}
}
return Compilation::Stop;
},
None => ()
}
return Compilation::Continue;
}
fn no_input(&mut self,
matches: &getopts::Matches,
sopts: &config::Options,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>,
descriptions: &diagnostics::registry::Registry)
-> Option<(Input, Option<PathBuf>)> {
match matches.free.len() {
0 => {
if sopts.describe_lints {
let mut ls = lint::LintStore::new();
rustc_lint::register_builtins(&mut ls, None);
describe_lints(&ls, false);
return None;
}
let sess = build_session(sopts.clone(), None, descriptions.clone());
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
let should_stop = RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
if should_stop == Compilation::Stop {
return None;
}
early_error("no input filename given");
}
1 => panic!("make_input should have provided valid inputs"),
_ => early_error("multiple input filenames provided")
}
None
}
fn parse_pretty(&mut self,
sess: &Session,
matches: &getopts::Matches)
-> Option<(PpMode, Option<UserIdentifiedItem>)> {
let pretty = if sess.opts.debugging_opts.unstable_options {
matches.opt_default("pretty", "normal").map(|a| {
// stable pretty-print variants only
pretty::parse_pretty(sess, &a, false)
})
} else {
None
};
if pretty.is_none() && sess.unstable_options() {
matches.opt_str("xpretty").map(|a| {
// extended with unstable pretty-print variants
pretty::parse_pretty(sess, &a, true)
})
} else {
pretty
}
}
fn late_callback(&mut self,
matches: &getopts::Matches,
sess: &Session,
input: &Input,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>)
-> Compilation {
RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile).and_then(
|| RustcDefaultCalls::list_metadata(sess, matches, input))
}
fn build_controller(&mut self, sess: &Session) -> CompileController<'a> {
let mut control = CompileController::basic();
if sess.opts.parse_only ||
sess.opts.show_span.is_some() ||
sess.opts.debugging_opts.ast_json_noexpand {
control.after_parse.stop = Compilation::Stop;
}
if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
control.after_write_deps.stop = Compilation::Stop;
}
if sess.opts.no_trans {
control.after_analysis.stop = Compilation::Stop;
}
if !sess.opts.output_types.iter().any(|&i| i == config::OutputTypeExe) {
control.after_llvm.stop = Compilation::Stop;
}
if sess.opts.debugging_opts.save_analysis {
control.after_analysis.callback = box |state| {
time(state.session.time_passes(),
"save analysis", (),
|_| save::process_crate(state.tcx.unwrap(),
state.analysis.unwrap(),
state.out_dir));
};
control.make_glob_map = resolve::MakeGlobMap::Yes;
}
control
}
}
impl RustcDefaultCalls {
pub fn list_metadata(sess: &Session,
matches: &getopts::Matches,
input: &Input)
-> Compilation {
let r = matches.opt_strs("Z");
if r.contains(&("ls".to_string())) {
match input {
&Input::File(ref ifile) => {
let path = &(*ifile);
let mut v = Vec::new();
metadata::loader::list_file_metadata(&sess.target.target,
path,
&mut v).unwrap();
println!("{}", String::from_utf8(v).unwrap());
}
&Input::Str(_) => {
early_error("cannot list metadata for stdin");
}
}
return Compilation::Stop;
}
return Compilation::Continue;
}
fn print_crate_info(sess: &Session,
input: Option<&Input>,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>)
-> Compilation {
if sess.opts.prints.is_empty() {
return Compilation::Continue;
}
let attrs = input.map(|input| parse_crate_attrs(sess, input));
for req in &sess.opts.prints {
match *req {
PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
PrintRequest::FileNames |
PrintRequest::CrateName => {
let input = match input {
Some(input) => input,
None => early_error("no input file provided"),
};
let attrs = attrs.as_ref().unwrap();
let t_outputs = driver::build_output_filenames(input,
odir,
ofile,
attrs,
sess);
let id = link::find_crate_name(Some(sess),
attrs,
input);
if *req == PrintRequest::CrateName {
println!("{}", id);
continue
}
let crate_types = driver::collect_crate_types(sess, attrs);
let metadata = driver::collect_crate_metadata(sess, attrs);
*sess.crate_metadata.borrow_mut() = metadata;
for &style in &crate_types {
let fname = link::filename_for_input(sess,
style,
&id,
&t_outputs.with_extension(""));
println!("{}", fname.file_name().unwrap()
.to_string_lossy());
}
}
}
}
return Compilation::Stop;
}
}
/// Returns a version string such as "0.12.0-dev".
pub fn release_str() -> Option<&'static str> {
option_env!("CFG_RELEASE")
}
/// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
pub fn commit_hash_str() -> Option<&'static str> {
option_env!("CFG_VER_HASH")
}
/// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
pub fn commit_date_str() -> Option<&'static str> {
option_env!("CFG_VER_DATE")
}
/// Prints version information and returns None on success or an error
/// message on panic.
pub fn version(binary: &str, matches: &getopts::Matches) {
let verbose = matches.opt_present("verbose");
println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
if verbose {
fn unw(x: Option<&str>) -> &str { x.unwrap_or("unknown") }
println!("binary: {}", binary);
println!("commit-hash: {}", unw(commit_hash_str()));
println!("commit-date: {}", unw(commit_date_str()));
println!("host: {}", config::host_triple());
println!("release: {}", unw(release_str()));
}
}
fn usage(verbose: bool, include_unstable_options: bool) {
let groups = if verbose {
config::rustc_optgroups()
} else {
config::rustc_short_optgroups()
};
let groups : Vec<_> = groups.into_iter()
.filter(|x| include_unstable_options || x.is_stable())
.map(|x|x.opt_group)
.collect();
let message = format!("Usage: rustc [OPTIONS] INPUT");
let extra_help = if verbose {
""
} else {
"\n --help -v Print the full set of options rustc accepts"
};
println!("{}\n\
Additional help:
-C help Print codegen options
-W help Print 'lint' options and default settings
-Z help Print internal options for debugging rustc{}\n",
getopts::usage(&message, &groups),
extra_help);
}
fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
println!("
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny, and deny all overrides)
");
fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
lints.sort_by(|x: &&Lint, y: &&Lint| {
match x.default_level.cmp(&y.default_level) {
// The sort doesn't case-fold but it's doubtful we care.
Equal => x.name.cmp(y.name),
r => r,
}
});
lints
}
fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
-> Vec<(&'static str, Vec<lint::LintId>)> {
let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
&(y, _): &(&'static str, Vec<lint::LintId>)| {
x.cmp(y)
});
lints
}
let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
.iter().cloned().partition(|&(_, p)| p);
let plugin = sort_lints(plugin);
let builtin = sort_lints(builtin);
let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
.iter().cloned().partition(|&(_, _, p)| p);
let plugin_groups = sort_lint_groups(plugin_groups);
let builtin_groups = sort_lint_groups(builtin_groups);
let max_name_len = plugin.iter().chain(&builtin)
.map(|&s| s.name.chars().count())
.max().unwrap_or(0);
let padded = |x: &str| {
let mut s = repeat(" ").take(max_name_len - x.chars().count())
.collect::<String>();
s.push_str(x);
s
};
println!("Lint checks provided by rustc:\n");
println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
let print_lints = |lints: Vec<&Lint>| {
for lint in lints {
let name = lint.name_lower().replace("_", "-");
println!(" {} {:7.7} {}",
padded(&name[..]), lint.default_level.as_str(), lint.desc);
}
println!("\n");
};
print_lints(builtin);
let max_name_len = plugin_groups.iter().chain(&builtin_groups)
.map(|&(s, _)| s.chars().count())
.max().unwrap_or(0);
let padded = |x: &str| {
let mut s = repeat(" ").take(max_name_len - x.chars().count())
.collect::<String>();
s.push_str(x);
s
};
println!("Lint groups provided by rustc:\n");
println!(" {} {}", padded("name"), "sub-lints");
println!(" {} {}", padded("----"), "---------");
let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
for (name, to) in lints {
let name = name.to_lowercase().replace("_", "-");
let desc = to.into_iter().map(|x| x.as_str().replace("_", "-"))
.collect::<Vec<String>>().connect(", ");
println!(" {} {}",
padded(&name[..]), desc);
}
println!("\n");
};
print_lint_groups(builtin_groups);
match (loaded_plugins, plugin.len(), plugin_groups.len()) {
(false, 0, _) | (false, _, 0) => {
println!("Compiler plugins can provide additional lints and lint groups. To see a \
listing of these, re-run `rustc -W help` with a crate filename.");
}
(false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
(true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
(true, l, g) => {
if l > 0 {
println!("Lint checks provided by plugins loaded by this crate:\n");
print_lints(plugin);
}
if g > 0 {
println!("Lint groups provided by plugins loaded by this crate:\n");
print_lint_groups(plugin_groups);
}
}
}
}
fn describe_debug_flags() {
println!("\nAvailable debug options:\n");
for &(name, _, opt_type_desc, desc) in config::DB_OPTIONS {
let (width, extra) = match opt_type_desc {
Some(..) => (21, "=val"),
None => (25, "")
};
println!(" -Z {:>width$}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
fn describe_codegen_flags() {
println!("\nAvailable codegen options:\n");
for &(name, _, opt_type_desc, desc) in config::CG_OPTIONS {
let (width, extra) = match opt_type_desc {
Some(..) => (21, "=val"),
None => (25, "")
};
println!(" -C {:>width$}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
/// Process command line options. Emits messages as appropriate. If compilation
/// should continue, returns a getopts::Matches object parsed from args, otherwise
/// returns None.
pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
// Throw away the first argument, the name of the binary
let _binary = args.remove(0);
if args.is_empty() {
// user did not write `-v` nor `-Z unstable-options`, so do not
// include that extra information.
usage(false, false);
return None;
}
fn allows_unstable_options(matches: &getopts::Matches) -> bool {
let r = matches.opt_strs("Z");
r.iter().any(|x| *x == "unstable-options")
}
fn parse_all_options(args: &Vec<String>) -> getopts::Matches {
let all_groups : Vec<getopts::OptGroup>
= config::rustc_optgroups().into_iter().map(|x|x.opt_group).collect();
match getopts::getopts(&args[..], &all_groups) {
Ok(m) => {
if !allows_unstable_options(&m) {
// If -Z unstable-options was not specified, verify that
// no unstable options were present.
for opt in config::rustc_optgroups().into_iter().filter(|x| !x.is_stable()) {
let opt_name = if !opt.opt_group.long_name.is_empty() {
&opt.opt_group.long_name
} else {
&opt.opt_group.short_name
};
if m.opt_present(opt_name) {
early_error(&format!("use of unstable option '{}' requires \
-Z unstable-options", opt_name));
}
}
}
m
}
Err(f) => early_error(&f.to_string())
}
}
// As a speed optimization, first try to parse the command-line using just
// the stable options.
let matches = match getopts::getopts(&args[..], &config::optgroups()) {
Ok(ref m) if allows_unstable_options(m) => {
// If -Z unstable-options was specified, redo parsing with the
// unstable options to ensure that unstable options are defined
// in the returned getopts::Matches.
parse_all_options(&args)
}
Ok(m) => m,
Err(_) => {
// redo option parsing, including unstable options this time,
// in anticipation that the mishandled option was one of the
// unstable ones.
parse_all_options(&args)
}
};
if matches.opt_present("h") || matches.opt_present("help") {
usage(matches.opt_present("verbose"), allows_unstable_options(&matches));
return None;
}
// Don't handle -W help here, because we might first load plugins.
let r = matches.opt_strs("Z");
if r.iter().any(|x| *x == "help") {
describe_debug_flags();
return None;
}
let cg_flags = matches.opt_strs("C");
if cg_flags.iter().any(|x| *x == "help") {
describe_codegen_flags();
return None;
}
if cg_flags.contains(&"passes=list".to_string()) {
unsafe { ::llvm::LLVMRustPrintPasses(); }
return None;
}
if matches.opt_present("version") {
version("rustc", &matches);
return None;
}
Some(matches)
}
fn parse_crate_attrs(sess: &Session, input: &Input) ->
Vec<ast::Attribute> {
let result = match *input {
Input::File(ref ifile) => {
parse::parse_crate_attrs_from_file(ifile,
Vec::new(),
&sess.parse_sess)
}
Input::Str(ref src) => {
parse::parse_crate_attrs_from_source_str(
driver::anon_src().to_string(),
src.to_string(),
Vec::new(),
&sess.parse_sess)
}
};
result.into_iter().collect()
}
/// Run a procedure which will detect panics in the compiler and print nicer
/// error messages rather than just failing the test.
///
/// The diagnostic emitter yielded to the procedure should be used for reporting
/// errors of the compiler.
pub fn monitor<F:FnOnce()+Send+'static>(f: F) {
const STACK_SIZE: usize = 8 * 1024 * 1024; // 8MB
struct Sink(Arc<Mutex<Vec<u8>>>);
impl Write for Sink {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
Write::write(&mut *self.0.lock().unwrap(), data)
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
let data = Arc::new(Mutex::new(Vec::new()));
let err = Sink(data.clone());
let mut cfg = thread::Builder::new().name("rustc".to_string());
// FIXME: Hacks on hacks. If the env is trying to override the stack size
// then *don't* set it explicitly.
if env::var_os("RUST_MIN_STACK").is_none() {
cfg = cfg.stack_size(STACK_SIZE);
}
match cfg.spawn(move || { io::set_panic(box err); f() }).unwrap().join() {
Ok(()) => { /* fallthrough */ }
Err(value) => {
// Thread panicked without emitting a fatal diagnostic
if !value.is::<diagnostic::FatalError>() {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
// a .span_bug or .bug call has already printed what
// it wants to print.
if !value.is::<diagnostic::ExplicitBug>() {
emitter.emit(
None,
"unexpected panic",
None,
diagnostic::Bug);
}
let xs = [
"the compiler unexpectedly panicked. this is a bug.".to_string(),
format!("we would appreciate a bug report: {}",
BUG_REPORT_URL),
];
for note in &xs {
emitter.emit(None, ¬e[..], None, diagnostic::Note)
}
if let None = env::var_os("RUST_BACKTRACE") {
emitter.emit(None, "run with `RUST_BACKTRACE=1` for a backtrace",
None, diagnostic::Note);
}
println!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
}
// Panic so the process returns a failure code, but don't pollute the
// output with some unnecessary panic messages, we've already
// printed everything that we needed to.
io::set_panic(box io::sink());
panic!();
}
}
}
pub fn diagnostics_registry() -> diagnostics::registry::Registry {
use syntax::diagnostics::registry::Registry;
let mut all_errors = Vec::new();
all_errors.push_all(&rustc::DIAGNOSTICS);
all_errors.push_all(&rustc_typeck::DIAGNOSTICS);
all_errors.push_all(&rustc_borrowck::DIAGNOSTICS);
all_errors.push_all(&rustc_resolve::DIAGNOSTICS);
Registry::new(&*all_errors)
}
pub fn main() {
let result = run(env::args().collect());
process::exit(result as i32);
}
| Compilation | identifier_name |
lib.rs | // Copyright 2014-2015 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.
//! The Rust compiler.
//!
//! # Note
//!
//! This API is completely unstable and subject to change.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_driver"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(box_syntax)]
#![feature(libc)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(set_stdio)]
#![feature(staged_api)]
#![feature(vec_push_all)]
extern crate arena;
extern crate flate;
extern crate getopts;
extern crate graphviz;
extern crate libc;
extern crate rustc;
extern crate rustc_back;
extern crate rustc_borrowck;
extern crate rustc_lint;
extern crate rustc_privacy;
extern crate rustc_resolve;
extern crate rustc_trans;
extern crate rustc_typeck;
extern crate serialize;
extern crate rustc_llvm as llvm;
#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
pub use syntax::diagnostic;
use driver::CompileController;
use pretty::{PpMode, UserIdentifiedItem};
use rustc_resolve as resolve;
use rustc_trans::back::link;
use rustc_trans::save;
use rustc::session::{config, Session, build_session};
use rustc::session::config::{Input, PrintRequest};
use rustc::lint::Lint;
use rustc::lint;
use rustc::metadata;
use rustc::util::common::time;
use std::cmp::Ordering::Equal;
use std::env;
use std::io::{self, Read, Write};
use std::iter::repeat;
use std::path::PathBuf;
use std::process;
use std::str;
use std::sync::{Arc, Mutex};
use std::thread;
use rustc::session::early_error;
use syntax::ast;
use syntax::parse;
use syntax::diagnostic::Emitter;
use syntax::diagnostics;
#[cfg(test)]
pub mod test;
pub mod driver;
pub mod pretty;
const BUG_REPORT_URL: &'static str =
"https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.md#bug-reports";
pub fn run(args: Vec<String>) -> isize {
monitor(move || run_compiler(&args, &mut RustcDefaultCalls));
0
}
// Parse args and run the compiler. This is the primary entry point for rustc.
// See comments on CompilerCalls below for details about the callbacks argument.
pub fn run_compiler<'a>(args: &[String],
callbacks: &mut CompilerCalls<'a>) {
macro_rules! do_or_return {($expr: expr) => {
match $expr {
Compilation::Stop => return,
Compilation::Continue => {}
}
}}
let matches = match handle_options(args.to_vec()) {
Some(matches) => matches,
None => return
};
let descriptions = diagnostics_registry();
do_or_return!(callbacks.early_callback(&matches, &descriptions));
let sopts = config::build_session_options(&matches);
let (odir, ofile) = make_output(&matches);
let (input, input_file_path) = match make_input(&matches.free) {
Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) {
Some((input, input_file_path)) => (input, input_file_path),
None => return
}
};
let mut sess = build_session(sopts, input_file_path, descriptions);
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
if sess.unstable_options() {
sess.opts.show_span = matches.opt_str("show-span");
}
let cfg = config::build_configuration(&sess);
do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile));
// It is somewhat unfortunate that this is hardwired in - this is forced by
// the fact that pretty_print_input requires the session by value.
let pretty = callbacks.parse_pretty(&sess, &matches);
match pretty {
Some((ppm, opt_uii)) => {
pretty::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
return;
}
None => {/* continue */ }
}
let plugins = sess.opts.debugging_opts.extra_plugins.clone();
let control = callbacks.build_controller(&sess);
driver::compile_input(sess, cfg, &input, &odir, &ofile, Some(plugins), control);
}
// Extract output directory and file from matches.
fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
(odir, ofile)
}
// Extract input (string or file and optional path) from matches.
fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
if free_matches.len() == 1 {
let ifile = &free_matches[0][..];
if ifile == "-" {
let mut src = String::new();
io::stdin().read_to_string(&mut src).unwrap();
Some((Input::Str(src), None))
} else {
Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile))))
}
} else {
None
}
}
// Whether to stop or continue compilation.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Compilation {
Stop,
Continue,
}
impl Compilation {
pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
match self {
Compilation::Stop => Compilation::Stop,
Compilation::Continue => next()
}
}
}
// A trait for customising the compilation process. Offers a number of hooks for
// executing custom code or customising input.
pub trait CompilerCalls<'a> {
// Hook for a callback early in the process of handling arguments. This will
// be called straight after options have been parsed but before anything
// else (e.g., selecting input and output).
fn early_callback(&mut self,
&getopts::Matches,
&diagnostics::registry::Registry)
-> Compilation;
// Hook for a callback late in the process of handling arguments. This will
// be called just before actual compilation starts (and before build_controller
// is called), after all arguments etc. have been completely handled.
fn late_callback(&mut self,
&getopts::Matches,
&Session,
&Input,
&Option<PathBuf>,
&Option<PathBuf>)
-> Compilation;
// Called after we extract the input from the arguments. Gives the implementer
// an opportunity to change the inputs or to add some custom input handling.
// The default behaviour is to simply pass through the inputs.
fn some_input(&mut self, input: Input, input_path: Option<PathBuf>)
-> (Input, Option<PathBuf>) {
(input, input_path)
}
// Called after we extract the input from the arguments if there is no valid
// input. Gives the implementer an opportunity to supply alternate input (by
// returning a Some value) or to add custom behaviour for this error such as
// emitting error messages. Returning None will cause compilation to stop
// at this point.
fn no_input(&mut self,
&getopts::Matches,
&config::Options,
&Option<PathBuf>,
&Option<PathBuf>,
&diagnostics::registry::Registry)
-> Option<(Input, Option<PathBuf>)>;
// Parse pretty printing information from the arguments. The implementer can
// choose to ignore this (the default will return None) which will skip pretty
// printing. If you do want to pretty print, it is recommended to use the
// implementation of this method from RustcDefaultCalls.
// FIXME, this is a terrible bit of API. Parsing of pretty printing stuff
// should be done as part of the framework and the implementor should customise
// handling of it. However, that is not possible atm because pretty printing
// essentially goes off and takes another path through the compiler which
// means the session is either moved or not depending on what parse_pretty
// returns (we could fix this by cloning, but it's another hack). The proper
// solution is to handle pretty printing as if it were a compiler extension,
// extending CompileController to make this work (see for example the treatment
// of save-analysis in RustcDefaultCalls::build_controller).
fn parse_pretty(&mut self,
_sess: &Session,
_matches: &getopts::Matches)
-> Option<(PpMode, Option<UserIdentifiedItem>)> {
None
}
// Create a CompilController struct for controlling the behaviour of compilation.
fn build_controller(&mut self, &Session) -> CompileController<'a>;
}
// CompilerCalls instance for a regular rustc build.
#[derive(Copy, Clone)]
pub struct RustcDefaultCalls;
impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
fn early_callback(&mut self,
matches: &getopts::Matches,
descriptions: &diagnostics::registry::Registry)
-> Compilation {
match matches.opt_str("explain") {
Some(ref code) => {
match descriptions.find_description(&code[..]) {
Some(ref description) => {
// Slice off the leading newline and print.
print!("{}", &description[1..]);
}
None => {
early_error(&format!("no extended information for {}", code));
}
}
return Compilation::Stop;
},
None => ()
}
return Compilation::Continue;
}
fn no_input(&mut self,
matches: &getopts::Matches,
sopts: &config::Options,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>,
descriptions: &diagnostics::registry::Registry)
-> Option<(Input, Option<PathBuf>)> {
match matches.free.len() {
0 => {
if sopts.describe_lints {
let mut ls = lint::LintStore::new();
rustc_lint::register_builtins(&mut ls, None);
describe_lints(&ls, false);
return None;
}
let sess = build_session(sopts.clone(), None, descriptions.clone());
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
let should_stop = RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
if should_stop == Compilation::Stop {
return None;
}
early_error("no input filename given");
}
1 => panic!("make_input should have provided valid inputs"),
_ => early_error("multiple input filenames provided")
}
None
}
fn parse_pretty(&mut self,
sess: &Session,
matches: &getopts::Matches)
-> Option<(PpMode, Option<UserIdentifiedItem>)> {
let pretty = if sess.opts.debugging_opts.unstable_options {
matches.opt_default("pretty", "normal").map(|a| {
// stable pretty-print variants only
pretty::parse_pretty(sess, &a, false)
})
} else {
None
};
if pretty.is_none() && sess.unstable_options() {
matches.opt_str("xpretty").map(|a| {
// extended with unstable pretty-print variants
pretty::parse_pretty(sess, &a, true)
})
} else {
pretty
}
}
fn late_callback(&mut self,
matches: &getopts::Matches,
sess: &Session,
input: &Input,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>)
-> Compilation {
RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile).and_then(
|| RustcDefaultCalls::list_metadata(sess, matches, input))
} |
if sess.opts.parse_only ||
sess.opts.show_span.is_some() ||
sess.opts.debugging_opts.ast_json_noexpand {
control.after_parse.stop = Compilation::Stop;
}
if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
control.after_write_deps.stop = Compilation::Stop;
}
if sess.opts.no_trans {
control.after_analysis.stop = Compilation::Stop;
}
if !sess.opts.output_types.iter().any(|&i| i == config::OutputTypeExe) {
control.after_llvm.stop = Compilation::Stop;
}
if sess.opts.debugging_opts.save_analysis {
control.after_analysis.callback = box |state| {
time(state.session.time_passes(),
"save analysis", (),
|_| save::process_crate(state.tcx.unwrap(),
state.analysis.unwrap(),
state.out_dir));
};
control.make_glob_map = resolve::MakeGlobMap::Yes;
}
control
}
}
impl RustcDefaultCalls {
pub fn list_metadata(sess: &Session,
matches: &getopts::Matches,
input: &Input)
-> Compilation {
let r = matches.opt_strs("Z");
if r.contains(&("ls".to_string())) {
match input {
&Input::File(ref ifile) => {
let path = &(*ifile);
let mut v = Vec::new();
metadata::loader::list_file_metadata(&sess.target.target,
path,
&mut v).unwrap();
println!("{}", String::from_utf8(v).unwrap());
}
&Input::Str(_) => {
early_error("cannot list metadata for stdin");
}
}
return Compilation::Stop;
}
return Compilation::Continue;
}
fn print_crate_info(sess: &Session,
input: Option<&Input>,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>)
-> Compilation {
if sess.opts.prints.is_empty() {
return Compilation::Continue;
}
let attrs = input.map(|input| parse_crate_attrs(sess, input));
for req in &sess.opts.prints {
match *req {
PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
PrintRequest::FileNames |
PrintRequest::CrateName => {
let input = match input {
Some(input) => input,
None => early_error("no input file provided"),
};
let attrs = attrs.as_ref().unwrap();
let t_outputs = driver::build_output_filenames(input,
odir,
ofile,
attrs,
sess);
let id = link::find_crate_name(Some(sess),
attrs,
input);
if *req == PrintRequest::CrateName {
println!("{}", id);
continue
}
let crate_types = driver::collect_crate_types(sess, attrs);
let metadata = driver::collect_crate_metadata(sess, attrs);
*sess.crate_metadata.borrow_mut() = metadata;
for &style in &crate_types {
let fname = link::filename_for_input(sess,
style,
&id,
&t_outputs.with_extension(""));
println!("{}", fname.file_name().unwrap()
.to_string_lossy());
}
}
}
}
return Compilation::Stop;
}
}
/// Returns a version string such as "0.12.0-dev".
pub fn release_str() -> Option<&'static str> {
option_env!("CFG_RELEASE")
}
/// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
pub fn commit_hash_str() -> Option<&'static str> {
option_env!("CFG_VER_HASH")
}
/// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
pub fn commit_date_str() -> Option<&'static str> {
option_env!("CFG_VER_DATE")
}
/// Prints version information and returns None on success or an error
/// message on panic.
pub fn version(binary: &str, matches: &getopts::Matches) {
let verbose = matches.opt_present("verbose");
println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
if verbose {
fn unw(x: Option<&str>) -> &str { x.unwrap_or("unknown") }
println!("binary: {}", binary);
println!("commit-hash: {}", unw(commit_hash_str()));
println!("commit-date: {}", unw(commit_date_str()));
println!("host: {}", config::host_triple());
println!("release: {}", unw(release_str()));
}
}
fn usage(verbose: bool, include_unstable_options: bool) {
let groups = if verbose {
config::rustc_optgroups()
} else {
config::rustc_short_optgroups()
};
let groups : Vec<_> = groups.into_iter()
.filter(|x| include_unstable_options || x.is_stable())
.map(|x|x.opt_group)
.collect();
let message = format!("Usage: rustc [OPTIONS] INPUT");
let extra_help = if verbose {
""
} else {
"\n --help -v Print the full set of options rustc accepts"
};
println!("{}\n\
Additional help:
-C help Print codegen options
-W help Print 'lint' options and default settings
-Z help Print internal options for debugging rustc{}\n",
getopts::usage(&message, &groups),
extra_help);
}
fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
println!("
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny, and deny all overrides)
");
fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
lints.sort_by(|x: &&Lint, y: &&Lint| {
match x.default_level.cmp(&y.default_level) {
// The sort doesn't case-fold but it's doubtful we care.
Equal => x.name.cmp(y.name),
r => r,
}
});
lints
}
fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
-> Vec<(&'static str, Vec<lint::LintId>)> {
let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
&(y, _): &(&'static str, Vec<lint::LintId>)| {
x.cmp(y)
});
lints
}
let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
.iter().cloned().partition(|&(_, p)| p);
let plugin = sort_lints(plugin);
let builtin = sort_lints(builtin);
let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
.iter().cloned().partition(|&(_, _, p)| p);
let plugin_groups = sort_lint_groups(plugin_groups);
let builtin_groups = sort_lint_groups(builtin_groups);
let max_name_len = plugin.iter().chain(&builtin)
.map(|&s| s.name.chars().count())
.max().unwrap_or(0);
let padded = |x: &str| {
let mut s = repeat(" ").take(max_name_len - x.chars().count())
.collect::<String>();
s.push_str(x);
s
};
println!("Lint checks provided by rustc:\n");
println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
let print_lints = |lints: Vec<&Lint>| {
for lint in lints {
let name = lint.name_lower().replace("_", "-");
println!(" {} {:7.7} {}",
padded(&name[..]), lint.default_level.as_str(), lint.desc);
}
println!("\n");
};
print_lints(builtin);
let max_name_len = plugin_groups.iter().chain(&builtin_groups)
.map(|&(s, _)| s.chars().count())
.max().unwrap_or(0);
let padded = |x: &str| {
let mut s = repeat(" ").take(max_name_len - x.chars().count())
.collect::<String>();
s.push_str(x);
s
};
println!("Lint groups provided by rustc:\n");
println!(" {} {}", padded("name"), "sub-lints");
println!(" {} {}", padded("----"), "---------");
let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
for (name, to) in lints {
let name = name.to_lowercase().replace("_", "-");
let desc = to.into_iter().map(|x| x.as_str().replace("_", "-"))
.collect::<Vec<String>>().connect(", ");
println!(" {} {}",
padded(&name[..]), desc);
}
println!("\n");
};
print_lint_groups(builtin_groups);
match (loaded_plugins, plugin.len(), plugin_groups.len()) {
(false, 0, _) | (false, _, 0) => {
println!("Compiler plugins can provide additional lints and lint groups. To see a \
listing of these, re-run `rustc -W help` with a crate filename.");
}
(false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
(true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
(true, l, g) => {
if l > 0 {
println!("Lint checks provided by plugins loaded by this crate:\n");
print_lints(plugin);
}
if g > 0 {
println!("Lint groups provided by plugins loaded by this crate:\n");
print_lint_groups(plugin_groups);
}
}
}
}
fn describe_debug_flags() {
println!("\nAvailable debug options:\n");
for &(name, _, opt_type_desc, desc) in config::DB_OPTIONS {
let (width, extra) = match opt_type_desc {
Some(..) => (21, "=val"),
None => (25, "")
};
println!(" -Z {:>width$}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
fn describe_codegen_flags() {
println!("\nAvailable codegen options:\n");
for &(name, _, opt_type_desc, desc) in config::CG_OPTIONS {
let (width, extra) = match opt_type_desc {
Some(..) => (21, "=val"),
None => (25, "")
};
println!(" -C {:>width$}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
/// Process command line options. Emits messages as appropriate. If compilation
/// should continue, returns a getopts::Matches object parsed from args, otherwise
/// returns None.
pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
// Throw away the first argument, the name of the binary
let _binary = args.remove(0);
if args.is_empty() {
// user did not write `-v` nor `-Z unstable-options`, so do not
// include that extra information.
usage(false, false);
return None;
}
fn allows_unstable_options(matches: &getopts::Matches) -> bool {
let r = matches.opt_strs("Z");
r.iter().any(|x| *x == "unstable-options")
}
fn parse_all_options(args: &Vec<String>) -> getopts::Matches {
let all_groups : Vec<getopts::OptGroup>
= config::rustc_optgroups().into_iter().map(|x|x.opt_group).collect();
match getopts::getopts(&args[..], &all_groups) {
Ok(m) => {
if !allows_unstable_options(&m) {
// If -Z unstable-options was not specified, verify that
// no unstable options were present.
for opt in config::rustc_optgroups().into_iter().filter(|x| !x.is_stable()) {
let opt_name = if !opt.opt_group.long_name.is_empty() {
&opt.opt_group.long_name
} else {
&opt.opt_group.short_name
};
if m.opt_present(opt_name) {
early_error(&format!("use of unstable option '{}' requires \
-Z unstable-options", opt_name));
}
}
}
m
}
Err(f) => early_error(&f.to_string())
}
}
// As a speed optimization, first try to parse the command-line using just
// the stable options.
let matches = match getopts::getopts(&args[..], &config::optgroups()) {
Ok(ref m) if allows_unstable_options(m) => {
// If -Z unstable-options was specified, redo parsing with the
// unstable options to ensure that unstable options are defined
// in the returned getopts::Matches.
parse_all_options(&args)
}
Ok(m) => m,
Err(_) => {
// redo option parsing, including unstable options this time,
// in anticipation that the mishandled option was one of the
// unstable ones.
parse_all_options(&args)
}
};
if matches.opt_present("h") || matches.opt_present("help") {
usage(matches.opt_present("verbose"), allows_unstable_options(&matches));
return None;
}
// Don't handle -W help here, because we might first load plugins.
let r = matches.opt_strs("Z");
if r.iter().any(|x| *x == "help") {
describe_debug_flags();
return None;
}
let cg_flags = matches.opt_strs("C");
if cg_flags.iter().any(|x| *x == "help") {
describe_codegen_flags();
return None;
}
if cg_flags.contains(&"passes=list".to_string()) {
unsafe { ::llvm::LLVMRustPrintPasses(); }
return None;
}
if matches.opt_present("version") {
version("rustc", &matches);
return None;
}
Some(matches)
}
fn parse_crate_attrs(sess: &Session, input: &Input) ->
Vec<ast::Attribute> {
let result = match *input {
Input::File(ref ifile) => {
parse::parse_crate_attrs_from_file(ifile,
Vec::new(),
&sess.parse_sess)
}
Input::Str(ref src) => {
parse::parse_crate_attrs_from_source_str(
driver::anon_src().to_string(),
src.to_string(),
Vec::new(),
&sess.parse_sess)
}
};
result.into_iter().collect()
}
/// Run a procedure which will detect panics in the compiler and print nicer
/// error messages rather than just failing the test.
///
/// The diagnostic emitter yielded to the procedure should be used for reporting
/// errors of the compiler.
pub fn monitor<F:FnOnce()+Send+'static>(f: F) {
const STACK_SIZE: usize = 8 * 1024 * 1024; // 8MB
struct Sink(Arc<Mutex<Vec<u8>>>);
impl Write for Sink {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
Write::write(&mut *self.0.lock().unwrap(), data)
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
let data = Arc::new(Mutex::new(Vec::new()));
let err = Sink(data.clone());
let mut cfg = thread::Builder::new().name("rustc".to_string());
// FIXME: Hacks on hacks. If the env is trying to override the stack size
// then *don't* set it explicitly.
if env::var_os("RUST_MIN_STACK").is_none() {
cfg = cfg.stack_size(STACK_SIZE);
}
match cfg.spawn(move || { io::set_panic(box err); f() }).unwrap().join() {
Ok(()) => { /* fallthrough */ }
Err(value) => {
// Thread panicked without emitting a fatal diagnostic
if !value.is::<diagnostic::FatalError>() {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
// a .span_bug or .bug call has already printed what
// it wants to print.
if !value.is::<diagnostic::ExplicitBug>() {
emitter.emit(
None,
"unexpected panic",
None,
diagnostic::Bug);
}
let xs = [
"the compiler unexpectedly panicked. this is a bug.".to_string(),
format!("we would appreciate a bug report: {}",
BUG_REPORT_URL),
];
for note in &xs {
emitter.emit(None, ¬e[..], None, diagnostic::Note)
}
if let None = env::var_os("RUST_BACKTRACE") {
emitter.emit(None, "run with `RUST_BACKTRACE=1` for a backtrace",
None, diagnostic::Note);
}
println!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
}
// Panic so the process returns a failure code, but don't pollute the
// output with some unnecessary panic messages, we've already
// printed everything that we needed to.
io::set_panic(box io::sink());
panic!();
}
}
}
pub fn diagnostics_registry() -> diagnostics::registry::Registry {
use syntax::diagnostics::registry::Registry;
let mut all_errors = Vec::new();
all_errors.push_all(&rustc::DIAGNOSTICS);
all_errors.push_all(&rustc_typeck::DIAGNOSTICS);
all_errors.push_all(&rustc_borrowck::DIAGNOSTICS);
all_errors.push_all(&rustc_resolve::DIAGNOSTICS);
Registry::new(&*all_errors)
}
pub fn main() {
let result = run(env::args().collect());
process::exit(result as i32);
} |
fn build_controller(&mut self, sess: &Session) -> CompileController<'a> {
let mut control = CompileController::basic(); | random_line_split |
lib.rs | // Copyright 2014-2015 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.
//! The Rust compiler.
//!
//! # Note
//!
//! This API is completely unstable and subject to change.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_driver"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(box_syntax)]
#![feature(libc)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(set_stdio)]
#![feature(staged_api)]
#![feature(vec_push_all)]
extern crate arena;
extern crate flate;
extern crate getopts;
extern crate graphviz;
extern crate libc;
extern crate rustc;
extern crate rustc_back;
extern crate rustc_borrowck;
extern crate rustc_lint;
extern crate rustc_privacy;
extern crate rustc_resolve;
extern crate rustc_trans;
extern crate rustc_typeck;
extern crate serialize;
extern crate rustc_llvm as llvm;
#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
pub use syntax::diagnostic;
use driver::CompileController;
use pretty::{PpMode, UserIdentifiedItem};
use rustc_resolve as resolve;
use rustc_trans::back::link;
use rustc_trans::save;
use rustc::session::{config, Session, build_session};
use rustc::session::config::{Input, PrintRequest};
use rustc::lint::Lint;
use rustc::lint;
use rustc::metadata;
use rustc::util::common::time;
use std::cmp::Ordering::Equal;
use std::env;
use std::io::{self, Read, Write};
use std::iter::repeat;
use std::path::PathBuf;
use std::process;
use std::str;
use std::sync::{Arc, Mutex};
use std::thread;
use rustc::session::early_error;
use syntax::ast;
use syntax::parse;
use syntax::diagnostic::Emitter;
use syntax::diagnostics;
#[cfg(test)]
pub mod test;
pub mod driver;
pub mod pretty;
const BUG_REPORT_URL: &'static str =
"https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.md#bug-reports";
pub fn run(args: Vec<String>) -> isize {
monitor(move || run_compiler(&args, &mut RustcDefaultCalls));
0
}
// Parse args and run the compiler. This is the primary entry point for rustc.
// See comments on CompilerCalls below for details about the callbacks argument.
pub fn run_compiler<'a>(args: &[String],
callbacks: &mut CompilerCalls<'a>) {
macro_rules! do_or_return {($expr: expr) => {
match $expr {
Compilation::Stop => return,
Compilation::Continue => {}
}
}}
let matches = match handle_options(args.to_vec()) {
Some(matches) => matches,
None => return
};
let descriptions = diagnostics_registry();
do_or_return!(callbacks.early_callback(&matches, &descriptions));
let sopts = config::build_session_options(&matches);
let (odir, ofile) = make_output(&matches);
let (input, input_file_path) = match make_input(&matches.free) {
Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) {
Some((input, input_file_path)) => (input, input_file_path),
None => return
}
};
let mut sess = build_session(sopts, input_file_path, descriptions);
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
if sess.unstable_options() {
sess.opts.show_span = matches.opt_str("show-span");
}
let cfg = config::build_configuration(&sess);
do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile));
// It is somewhat unfortunate that this is hardwired in - this is forced by
// the fact that pretty_print_input requires the session by value.
let pretty = callbacks.parse_pretty(&sess, &matches);
match pretty {
Some((ppm, opt_uii)) => {
pretty::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
return;
}
None => {/* continue */ }
}
let plugins = sess.opts.debugging_opts.extra_plugins.clone();
let control = callbacks.build_controller(&sess);
driver::compile_input(sess, cfg, &input, &odir, &ofile, Some(plugins), control);
}
// Extract output directory and file from matches.
fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
(odir, ofile)
}
// Extract input (string or file and optional path) from matches.
fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
if free_matches.len() == 1 {
let ifile = &free_matches[0][..];
if ifile == "-" {
let mut src = String::new();
io::stdin().read_to_string(&mut src).unwrap();
Some((Input::Str(src), None))
} else {
Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile))))
}
} else {
None
}
}
// Whether to stop or continue compilation.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Compilation {
Stop,
Continue,
}
impl Compilation {
pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
match self {
Compilation::Stop => Compilation::Stop,
Compilation::Continue => next()
}
}
}
// A trait for customising the compilation process. Offers a number of hooks for
// executing custom code or customising input.
pub trait CompilerCalls<'a> {
// Hook for a callback early in the process of handling arguments. This will
// be called straight after options have been parsed but before anything
// else (e.g., selecting input and output).
fn early_callback(&mut self,
&getopts::Matches,
&diagnostics::registry::Registry)
-> Compilation;
// Hook for a callback late in the process of handling arguments. This will
// be called just before actual compilation starts (and before build_controller
// is called), after all arguments etc. have been completely handled.
fn late_callback(&mut self,
&getopts::Matches,
&Session,
&Input,
&Option<PathBuf>,
&Option<PathBuf>)
-> Compilation;
// Called after we extract the input from the arguments. Gives the implementer
// an opportunity to change the inputs or to add some custom input handling.
// The default behaviour is to simply pass through the inputs.
fn some_input(&mut self, input: Input, input_path: Option<PathBuf>)
-> (Input, Option<PathBuf>) {
(input, input_path)
}
// Called after we extract the input from the arguments if there is no valid
// input. Gives the implementer an opportunity to supply alternate input (by
// returning a Some value) or to add custom behaviour for this error such as
// emitting error messages. Returning None will cause compilation to stop
// at this point.
fn no_input(&mut self,
&getopts::Matches,
&config::Options,
&Option<PathBuf>,
&Option<PathBuf>,
&diagnostics::registry::Registry)
-> Option<(Input, Option<PathBuf>)>;
// Parse pretty printing information from the arguments. The implementer can
// choose to ignore this (the default will return None) which will skip pretty
// printing. If you do want to pretty print, it is recommended to use the
// implementation of this method from RustcDefaultCalls.
// FIXME, this is a terrible bit of API. Parsing of pretty printing stuff
// should be done as part of the framework and the implementor should customise
// handling of it. However, that is not possible atm because pretty printing
// essentially goes off and takes another path through the compiler which
// means the session is either moved or not depending on what parse_pretty
// returns (we could fix this by cloning, but it's another hack). The proper
// solution is to handle pretty printing as if it were a compiler extension,
// extending CompileController to make this work (see for example the treatment
// of save-analysis in RustcDefaultCalls::build_controller).
fn parse_pretty(&mut self,
_sess: &Session,
_matches: &getopts::Matches)
-> Option<(PpMode, Option<UserIdentifiedItem>)> {
None
}
// Create a CompilController struct for controlling the behaviour of compilation.
fn build_controller(&mut self, &Session) -> CompileController<'a>;
}
// CompilerCalls instance for a regular rustc build.
#[derive(Copy, Clone)]
pub struct RustcDefaultCalls;
impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
fn early_callback(&mut self,
matches: &getopts::Matches,
descriptions: &diagnostics::registry::Registry)
-> Compilation {
match matches.opt_str("explain") {
Some(ref code) => {
match descriptions.find_description(&code[..]) {
Some(ref description) => {
// Slice off the leading newline and print.
print!("{}", &description[1..]);
}
None => {
early_error(&format!("no extended information for {}", code));
}
}
return Compilation::Stop;
},
None => ()
}
return Compilation::Continue;
}
fn no_input(&mut self,
matches: &getopts::Matches,
sopts: &config::Options,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>,
descriptions: &diagnostics::registry::Registry)
-> Option<(Input, Option<PathBuf>)> {
match matches.free.len() {
0 => {
if sopts.describe_lints {
let mut ls = lint::LintStore::new();
rustc_lint::register_builtins(&mut ls, None);
describe_lints(&ls, false);
return None;
}
let sess = build_session(sopts.clone(), None, descriptions.clone());
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
let should_stop = RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
if should_stop == Compilation::Stop {
return None;
}
early_error("no input filename given");
}
1 => panic!("make_input should have provided valid inputs"),
_ => early_error("multiple input filenames provided")
}
None
}
fn parse_pretty(&mut self,
sess: &Session,
matches: &getopts::Matches)
-> Option<(PpMode, Option<UserIdentifiedItem>)> {
let pretty = if sess.opts.debugging_opts.unstable_options {
matches.opt_default("pretty", "normal").map(|a| {
// stable pretty-print variants only
pretty::parse_pretty(sess, &a, false)
})
} else {
None
};
if pretty.is_none() && sess.unstable_options() {
matches.opt_str("xpretty").map(|a| {
// extended with unstable pretty-print variants
pretty::parse_pretty(sess, &a, true)
})
} else {
pretty
}
}
fn late_callback(&mut self,
matches: &getopts::Matches,
sess: &Session,
input: &Input,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>)
-> Compilation {
RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile).and_then(
|| RustcDefaultCalls::list_metadata(sess, matches, input))
}
fn build_controller(&mut self, sess: &Session) -> CompileController<'a> {
let mut control = CompileController::basic();
if sess.opts.parse_only ||
sess.opts.show_span.is_some() ||
sess.opts.debugging_opts.ast_json_noexpand {
control.after_parse.stop = Compilation::Stop;
}
if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
control.after_write_deps.stop = Compilation::Stop;
}
if sess.opts.no_trans {
control.after_analysis.stop = Compilation::Stop;
}
if !sess.opts.output_types.iter().any(|&i| i == config::OutputTypeExe) {
control.after_llvm.stop = Compilation::Stop;
}
if sess.opts.debugging_opts.save_analysis {
control.after_analysis.callback = box |state| {
time(state.session.time_passes(),
"save analysis", (),
|_| save::process_crate(state.tcx.unwrap(),
state.analysis.unwrap(),
state.out_dir));
};
control.make_glob_map = resolve::MakeGlobMap::Yes;
}
control
}
}
impl RustcDefaultCalls {
pub fn list_metadata(sess: &Session,
matches: &getopts::Matches,
input: &Input)
-> Compilation {
let r = matches.opt_strs("Z");
if r.contains(&("ls".to_string())) {
match input {
&Input::File(ref ifile) => {
let path = &(*ifile);
let mut v = Vec::new();
metadata::loader::list_file_metadata(&sess.target.target,
path,
&mut v).unwrap();
println!("{}", String::from_utf8(v).unwrap());
}
&Input::Str(_) => {
early_error("cannot list metadata for stdin");
}
}
return Compilation::Stop;
}
return Compilation::Continue;
}
fn print_crate_info(sess: &Session,
input: Option<&Input>,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>)
-> Compilation {
if sess.opts.prints.is_empty() {
return Compilation::Continue;
}
let attrs = input.map(|input| parse_crate_attrs(sess, input));
for req in &sess.opts.prints {
match *req {
PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
PrintRequest::FileNames |
PrintRequest::CrateName => {
let input = match input {
Some(input) => input,
None => early_error("no input file provided"),
};
let attrs = attrs.as_ref().unwrap();
let t_outputs = driver::build_output_filenames(input,
odir,
ofile,
attrs,
sess);
let id = link::find_crate_name(Some(sess),
attrs,
input);
if *req == PrintRequest::CrateName {
println!("{}", id);
continue
}
let crate_types = driver::collect_crate_types(sess, attrs);
let metadata = driver::collect_crate_metadata(sess, attrs);
*sess.crate_metadata.borrow_mut() = metadata;
for &style in &crate_types {
let fname = link::filename_for_input(sess,
style,
&id,
&t_outputs.with_extension(""));
println!("{}", fname.file_name().unwrap()
.to_string_lossy());
}
}
}
}
return Compilation::Stop;
}
}
/// Returns a version string such as "0.12.0-dev".
pub fn release_str() -> Option<&'static str> {
option_env!("CFG_RELEASE")
}
/// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
pub fn commit_hash_str() -> Option<&'static str> {
option_env!("CFG_VER_HASH")
}
/// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
pub fn commit_date_str() -> Option<&'static str> {
option_env!("CFG_VER_DATE")
}
/// Prints version information and returns None on success or an error
/// message on panic.
pub fn version(binary: &str, matches: &getopts::Matches) {
let verbose = matches.opt_present("verbose");
println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
if verbose {
fn unw(x: Option<&str>) -> &str { x.unwrap_or("unknown") }
println!("binary: {}", binary);
println!("commit-hash: {}", unw(commit_hash_str()));
println!("commit-date: {}", unw(commit_date_str()));
println!("host: {}", config::host_triple());
println!("release: {}", unw(release_str()));
}
}
fn usage(verbose: bool, include_unstable_options: bool) {
let groups = if verbose {
config::rustc_optgroups()
} else {
config::rustc_short_optgroups()
};
let groups : Vec<_> = groups.into_iter()
.filter(|x| include_unstable_options || x.is_stable())
.map(|x|x.opt_group)
.collect();
let message = format!("Usage: rustc [OPTIONS] INPUT");
let extra_help = if verbose {
""
} else {
"\n --help -v Print the full set of options rustc accepts"
};
println!("{}\n\
Additional help:
-C help Print codegen options
-W help Print 'lint' options and default settings
-Z help Print internal options for debugging rustc{}\n",
getopts::usage(&message, &groups),
extra_help);
}
fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
println!("
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny, and deny all overrides)
");
fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
lints.sort_by(|x: &&Lint, y: &&Lint| {
match x.default_level.cmp(&y.default_level) {
// The sort doesn't case-fold but it's doubtful we care.
Equal => x.name.cmp(y.name),
r => r,
}
});
lints
}
fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
-> Vec<(&'static str, Vec<lint::LintId>)> |
let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
.iter().cloned().partition(|&(_, p)| p);
let plugin = sort_lints(plugin);
let builtin = sort_lints(builtin);
let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
.iter().cloned().partition(|&(_, _, p)| p);
let plugin_groups = sort_lint_groups(plugin_groups);
let builtin_groups = sort_lint_groups(builtin_groups);
let max_name_len = plugin.iter().chain(&builtin)
.map(|&s| s.name.chars().count())
.max().unwrap_or(0);
let padded = |x: &str| {
let mut s = repeat(" ").take(max_name_len - x.chars().count())
.collect::<String>();
s.push_str(x);
s
};
println!("Lint checks provided by rustc:\n");
println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
let print_lints = |lints: Vec<&Lint>| {
for lint in lints {
let name = lint.name_lower().replace("_", "-");
println!(" {} {:7.7} {}",
padded(&name[..]), lint.default_level.as_str(), lint.desc);
}
println!("\n");
};
print_lints(builtin);
let max_name_len = plugin_groups.iter().chain(&builtin_groups)
.map(|&(s, _)| s.chars().count())
.max().unwrap_or(0);
let padded = |x: &str| {
let mut s = repeat(" ").take(max_name_len - x.chars().count())
.collect::<String>();
s.push_str(x);
s
};
println!("Lint groups provided by rustc:\n");
println!(" {} {}", padded("name"), "sub-lints");
println!(" {} {}", padded("----"), "---------");
let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
for (name, to) in lints {
let name = name.to_lowercase().replace("_", "-");
let desc = to.into_iter().map(|x| x.as_str().replace("_", "-"))
.collect::<Vec<String>>().connect(", ");
println!(" {} {}",
padded(&name[..]), desc);
}
println!("\n");
};
print_lint_groups(builtin_groups);
match (loaded_plugins, plugin.len(), plugin_groups.len()) {
(false, 0, _) | (false, _, 0) => {
println!("Compiler plugins can provide additional lints and lint groups. To see a \
listing of these, re-run `rustc -W help` with a crate filename.");
}
(false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
(true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
(true, l, g) => {
if l > 0 {
println!("Lint checks provided by plugins loaded by this crate:\n");
print_lints(plugin);
}
if g > 0 {
println!("Lint groups provided by plugins loaded by this crate:\n");
print_lint_groups(plugin_groups);
}
}
}
}
fn describe_debug_flags() {
println!("\nAvailable debug options:\n");
for &(name, _, opt_type_desc, desc) in config::DB_OPTIONS {
let (width, extra) = match opt_type_desc {
Some(..) => (21, "=val"),
None => (25, "")
};
println!(" -Z {:>width$}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
fn describe_codegen_flags() {
println!("\nAvailable codegen options:\n");
for &(name, _, opt_type_desc, desc) in config::CG_OPTIONS {
let (width, extra) = match opt_type_desc {
Some(..) => (21, "=val"),
None => (25, "")
};
println!(" -C {:>width$}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
/// Process command line options. Emits messages as appropriate. If compilation
/// should continue, returns a getopts::Matches object parsed from args, otherwise
/// returns None.
pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
// Throw away the first argument, the name of the binary
let _binary = args.remove(0);
if args.is_empty() {
// user did not write `-v` nor `-Z unstable-options`, so do not
// include that extra information.
usage(false, false);
return None;
}
fn allows_unstable_options(matches: &getopts::Matches) -> bool {
let r = matches.opt_strs("Z");
r.iter().any(|x| *x == "unstable-options")
}
fn parse_all_options(args: &Vec<String>) -> getopts::Matches {
let all_groups : Vec<getopts::OptGroup>
= config::rustc_optgroups().into_iter().map(|x|x.opt_group).collect();
match getopts::getopts(&args[..], &all_groups) {
Ok(m) => {
if !allows_unstable_options(&m) {
// If -Z unstable-options was not specified, verify that
// no unstable options were present.
for opt in config::rustc_optgroups().into_iter().filter(|x| !x.is_stable()) {
let opt_name = if !opt.opt_group.long_name.is_empty() {
&opt.opt_group.long_name
} else {
&opt.opt_group.short_name
};
if m.opt_present(opt_name) {
early_error(&format!("use of unstable option '{}' requires \
-Z unstable-options", opt_name));
}
}
}
m
}
Err(f) => early_error(&f.to_string())
}
}
// As a speed optimization, first try to parse the command-line using just
// the stable options.
let matches = match getopts::getopts(&args[..], &config::optgroups()) {
Ok(ref m) if allows_unstable_options(m) => {
// If -Z unstable-options was specified, redo parsing with the
// unstable options to ensure that unstable options are defined
// in the returned getopts::Matches.
parse_all_options(&args)
}
Ok(m) => m,
Err(_) => {
// redo option parsing, including unstable options this time,
// in anticipation that the mishandled option was one of the
// unstable ones.
parse_all_options(&args)
}
};
if matches.opt_present("h") || matches.opt_present("help") {
usage(matches.opt_present("verbose"), allows_unstable_options(&matches));
return None;
}
// Don't handle -W help here, because we might first load plugins.
let r = matches.opt_strs("Z");
if r.iter().any(|x| *x == "help") {
describe_debug_flags();
return None;
}
let cg_flags = matches.opt_strs("C");
if cg_flags.iter().any(|x| *x == "help") {
describe_codegen_flags();
return None;
}
if cg_flags.contains(&"passes=list".to_string()) {
unsafe { ::llvm::LLVMRustPrintPasses(); }
return None;
}
if matches.opt_present("version") {
version("rustc", &matches);
return None;
}
Some(matches)
}
fn parse_crate_attrs(sess: &Session, input: &Input) ->
Vec<ast::Attribute> {
let result = match *input {
Input::File(ref ifile) => {
parse::parse_crate_attrs_from_file(ifile,
Vec::new(),
&sess.parse_sess)
}
Input::Str(ref src) => {
parse::parse_crate_attrs_from_source_str(
driver::anon_src().to_string(),
src.to_string(),
Vec::new(),
&sess.parse_sess)
}
};
result.into_iter().collect()
}
/// Run a procedure which will detect panics in the compiler and print nicer
/// error messages rather than just failing the test.
///
/// The diagnostic emitter yielded to the procedure should be used for reporting
/// errors of the compiler.
pub fn monitor<F:FnOnce()+Send+'static>(f: F) {
const STACK_SIZE: usize = 8 * 1024 * 1024; // 8MB
struct Sink(Arc<Mutex<Vec<u8>>>);
impl Write for Sink {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
Write::write(&mut *self.0.lock().unwrap(), data)
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
let data = Arc::new(Mutex::new(Vec::new()));
let err = Sink(data.clone());
let mut cfg = thread::Builder::new().name("rustc".to_string());
// FIXME: Hacks on hacks. If the env is trying to override the stack size
// then *don't* set it explicitly.
if env::var_os("RUST_MIN_STACK").is_none() {
cfg = cfg.stack_size(STACK_SIZE);
}
match cfg.spawn(move || { io::set_panic(box err); f() }).unwrap().join() {
Ok(()) => { /* fallthrough */ }
Err(value) => {
// Thread panicked without emitting a fatal diagnostic
if !value.is::<diagnostic::FatalError>() {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
// a .span_bug or .bug call has already printed what
// it wants to print.
if !value.is::<diagnostic::ExplicitBug>() {
emitter.emit(
None,
"unexpected panic",
None,
diagnostic::Bug);
}
let xs = [
"the compiler unexpectedly panicked. this is a bug.".to_string(),
format!("we would appreciate a bug report: {}",
BUG_REPORT_URL),
];
for note in &xs {
emitter.emit(None, ¬e[..], None, diagnostic::Note)
}
if let None = env::var_os("RUST_BACKTRACE") {
emitter.emit(None, "run with `RUST_BACKTRACE=1` for a backtrace",
None, diagnostic::Note);
}
println!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
}
// Panic so the process returns a failure code, but don't pollute the
// output with some unnecessary panic messages, we've already
// printed everything that we needed to.
io::set_panic(box io::sink());
panic!();
}
}
}
pub fn diagnostics_registry() -> diagnostics::registry::Registry {
use syntax::diagnostics::registry::Registry;
let mut all_errors = Vec::new();
all_errors.push_all(&rustc::DIAGNOSTICS);
all_errors.push_all(&rustc_typeck::DIAGNOSTICS);
all_errors.push_all(&rustc_borrowck::DIAGNOSTICS);
all_errors.push_all(&rustc_resolve::DIAGNOSTICS);
Registry::new(&*all_errors)
}
pub fn main() {
let result = run(env::args().collect());
process::exit(result as i32);
}
| {
let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
&(y, _): &(&'static str, Vec<lint::LintId>)| {
x.cmp(y)
});
lints
} | identifier_body |
lib.rs | // Copyright 2014-2015 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.
//! The Rust compiler.
//!
//! # Note
//!
//! This API is completely unstable and subject to change.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_driver"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(box_syntax)]
#![feature(libc)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(set_stdio)]
#![feature(staged_api)]
#![feature(vec_push_all)]
extern crate arena;
extern crate flate;
extern crate getopts;
extern crate graphviz;
extern crate libc;
extern crate rustc;
extern crate rustc_back;
extern crate rustc_borrowck;
extern crate rustc_lint;
extern crate rustc_privacy;
extern crate rustc_resolve;
extern crate rustc_trans;
extern crate rustc_typeck;
extern crate serialize;
extern crate rustc_llvm as llvm;
#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
pub use syntax::diagnostic;
use driver::CompileController;
use pretty::{PpMode, UserIdentifiedItem};
use rustc_resolve as resolve;
use rustc_trans::back::link;
use rustc_trans::save;
use rustc::session::{config, Session, build_session};
use rustc::session::config::{Input, PrintRequest};
use rustc::lint::Lint;
use rustc::lint;
use rustc::metadata;
use rustc::util::common::time;
use std::cmp::Ordering::Equal;
use std::env;
use std::io::{self, Read, Write};
use std::iter::repeat;
use std::path::PathBuf;
use std::process;
use std::str;
use std::sync::{Arc, Mutex};
use std::thread;
use rustc::session::early_error;
use syntax::ast;
use syntax::parse;
use syntax::diagnostic::Emitter;
use syntax::diagnostics;
#[cfg(test)]
pub mod test;
pub mod driver;
pub mod pretty;
const BUG_REPORT_URL: &'static str =
"https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.md#bug-reports";
pub fn run(args: Vec<String>) -> isize {
monitor(move || run_compiler(&args, &mut RustcDefaultCalls));
0
}
// Parse args and run the compiler. This is the primary entry point for rustc.
// See comments on CompilerCalls below for details about the callbacks argument.
pub fn run_compiler<'a>(args: &[String],
callbacks: &mut CompilerCalls<'a>) {
macro_rules! do_or_return {($expr: expr) => {
match $expr {
Compilation::Stop => return,
Compilation::Continue => {}
}
}}
let matches = match handle_options(args.to_vec()) {
Some(matches) => matches,
None => return
};
let descriptions = diagnostics_registry();
do_or_return!(callbacks.early_callback(&matches, &descriptions));
let sopts = config::build_session_options(&matches);
let (odir, ofile) = make_output(&matches);
let (input, input_file_path) = match make_input(&matches.free) {
Some((input, input_file_path)) => callbacks.some_input(input, input_file_path),
None => match callbacks.no_input(&matches, &sopts, &odir, &ofile, &descriptions) {
Some((input, input_file_path)) => (input, input_file_path),
None => return
}
};
let mut sess = build_session(sopts, input_file_path, descriptions);
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
if sess.unstable_options() {
sess.opts.show_span = matches.opt_str("show-span");
}
let cfg = config::build_configuration(&sess);
do_or_return!(callbacks.late_callback(&matches, &sess, &input, &odir, &ofile));
// It is somewhat unfortunate that this is hardwired in - this is forced by
// the fact that pretty_print_input requires the session by value.
let pretty = callbacks.parse_pretty(&sess, &matches);
match pretty {
Some((ppm, opt_uii)) => {
pretty::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
return;
}
None => {/* continue */ }
}
let plugins = sess.opts.debugging_opts.extra_plugins.clone();
let control = callbacks.build_controller(&sess);
driver::compile_input(sess, cfg, &input, &odir, &ofile, Some(plugins), control);
}
// Extract output directory and file from matches.
fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) {
let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o));
let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o));
(odir, ofile)
}
// Extract input (string or file and optional path) from matches.
fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>)> {
if free_matches.len() == 1 {
let ifile = &free_matches[0][..];
if ifile == "-" {
let mut src = String::new();
io::stdin().read_to_string(&mut src).unwrap();
Some((Input::Str(src), None))
} else {
Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile))))
}
} else {
None
}
}
// Whether to stop or continue compilation.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Compilation {
Stop,
Continue,
}
impl Compilation {
pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation {
match self {
Compilation::Stop => Compilation::Stop,
Compilation::Continue => next()
}
}
}
// A trait for customising the compilation process. Offers a number of hooks for
// executing custom code or customising input.
pub trait CompilerCalls<'a> {
// Hook for a callback early in the process of handling arguments. This will
// be called straight after options have been parsed but before anything
// else (e.g., selecting input and output).
fn early_callback(&mut self,
&getopts::Matches,
&diagnostics::registry::Registry)
-> Compilation;
// Hook for a callback late in the process of handling arguments. This will
// be called just before actual compilation starts (and before build_controller
// is called), after all arguments etc. have been completely handled.
fn late_callback(&mut self,
&getopts::Matches,
&Session,
&Input,
&Option<PathBuf>,
&Option<PathBuf>)
-> Compilation;
// Called after we extract the input from the arguments. Gives the implementer
// an opportunity to change the inputs or to add some custom input handling.
// The default behaviour is to simply pass through the inputs.
fn some_input(&mut self, input: Input, input_path: Option<PathBuf>)
-> (Input, Option<PathBuf>) {
(input, input_path)
}
// Called after we extract the input from the arguments if there is no valid
// input. Gives the implementer an opportunity to supply alternate input (by
// returning a Some value) or to add custom behaviour for this error such as
// emitting error messages. Returning None will cause compilation to stop
// at this point.
fn no_input(&mut self,
&getopts::Matches,
&config::Options,
&Option<PathBuf>,
&Option<PathBuf>,
&diagnostics::registry::Registry)
-> Option<(Input, Option<PathBuf>)>;
// Parse pretty printing information from the arguments. The implementer can
// choose to ignore this (the default will return None) which will skip pretty
// printing. If you do want to pretty print, it is recommended to use the
// implementation of this method from RustcDefaultCalls.
// FIXME, this is a terrible bit of API. Parsing of pretty printing stuff
// should be done as part of the framework and the implementor should customise
// handling of it. However, that is not possible atm because pretty printing
// essentially goes off and takes another path through the compiler which
// means the session is either moved or not depending on what parse_pretty
// returns (we could fix this by cloning, but it's another hack). The proper
// solution is to handle pretty printing as if it were a compiler extension,
// extending CompileController to make this work (see for example the treatment
// of save-analysis in RustcDefaultCalls::build_controller).
fn parse_pretty(&mut self,
_sess: &Session,
_matches: &getopts::Matches)
-> Option<(PpMode, Option<UserIdentifiedItem>)> {
None
}
// Create a CompilController struct for controlling the behaviour of compilation.
fn build_controller(&mut self, &Session) -> CompileController<'a>;
}
// CompilerCalls instance for a regular rustc build.
#[derive(Copy, Clone)]
pub struct RustcDefaultCalls;
impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
fn early_callback(&mut self,
matches: &getopts::Matches,
descriptions: &diagnostics::registry::Registry)
-> Compilation {
match matches.opt_str("explain") {
Some(ref code) => {
match descriptions.find_description(&code[..]) {
Some(ref description) => {
// Slice off the leading newline and print.
print!("{}", &description[1..]);
}
None => {
early_error(&format!("no extended information for {}", code));
}
}
return Compilation::Stop;
},
None => ()
}
return Compilation::Continue;
}
fn no_input(&mut self,
matches: &getopts::Matches,
sopts: &config::Options,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>,
descriptions: &diagnostics::registry::Registry)
-> Option<(Input, Option<PathBuf>)> {
match matches.free.len() {
0 => {
if sopts.describe_lints {
let mut ls = lint::LintStore::new();
rustc_lint::register_builtins(&mut ls, None);
describe_lints(&ls, false);
return None;
}
let sess = build_session(sopts.clone(), None, descriptions.clone());
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
let should_stop = RustcDefaultCalls::print_crate_info(&sess, None, odir, ofile);
if should_stop == Compilation::Stop {
return None;
}
early_error("no input filename given");
}
1 => panic!("make_input should have provided valid inputs"),
_ => early_error("multiple input filenames provided")
}
None
}
fn parse_pretty(&mut self,
sess: &Session,
matches: &getopts::Matches)
-> Option<(PpMode, Option<UserIdentifiedItem>)> {
let pretty = if sess.opts.debugging_opts.unstable_options {
matches.opt_default("pretty", "normal").map(|a| {
// stable pretty-print variants only
pretty::parse_pretty(sess, &a, false)
})
} else {
None
};
if pretty.is_none() && sess.unstable_options() {
matches.opt_str("xpretty").map(|a| {
// extended with unstable pretty-print variants
pretty::parse_pretty(sess, &a, true)
})
} else {
pretty
}
}
fn late_callback(&mut self,
matches: &getopts::Matches,
sess: &Session,
input: &Input,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>)
-> Compilation {
RustcDefaultCalls::print_crate_info(sess, Some(input), odir, ofile).and_then(
|| RustcDefaultCalls::list_metadata(sess, matches, input))
}
fn build_controller(&mut self, sess: &Session) -> CompileController<'a> {
let mut control = CompileController::basic();
if sess.opts.parse_only ||
sess.opts.show_span.is_some() ||
sess.opts.debugging_opts.ast_json_noexpand {
control.after_parse.stop = Compilation::Stop;
}
if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json {
control.after_write_deps.stop = Compilation::Stop;
}
if sess.opts.no_trans {
control.after_analysis.stop = Compilation::Stop;
}
if !sess.opts.output_types.iter().any(|&i| i == config::OutputTypeExe) {
control.after_llvm.stop = Compilation::Stop;
}
if sess.opts.debugging_opts.save_analysis {
control.after_analysis.callback = box |state| {
time(state.session.time_passes(),
"save analysis", (),
|_| save::process_crate(state.tcx.unwrap(),
state.analysis.unwrap(),
state.out_dir));
};
control.make_glob_map = resolve::MakeGlobMap::Yes;
}
control
}
}
impl RustcDefaultCalls {
pub fn list_metadata(sess: &Session,
matches: &getopts::Matches,
input: &Input)
-> Compilation {
let r = matches.opt_strs("Z");
if r.contains(&("ls".to_string())) {
match input {
&Input::File(ref ifile) => {
let path = &(*ifile);
let mut v = Vec::new();
metadata::loader::list_file_metadata(&sess.target.target,
path,
&mut v).unwrap();
println!("{}", String::from_utf8(v).unwrap());
}
&Input::Str(_) => {
early_error("cannot list metadata for stdin");
}
}
return Compilation::Stop;
}
return Compilation::Continue;
}
fn print_crate_info(sess: &Session,
input: Option<&Input>,
odir: &Option<PathBuf>,
ofile: &Option<PathBuf>)
-> Compilation {
if sess.opts.prints.is_empty() {
return Compilation::Continue;
}
let attrs = input.map(|input| parse_crate_attrs(sess, input));
for req in &sess.opts.prints {
match *req {
PrintRequest::Sysroot => println!("{}", sess.sysroot().display()),
PrintRequest::FileNames |
PrintRequest::CrateName => |
}
}
return Compilation::Stop;
}
}
/// Returns a version string such as "0.12.0-dev".
pub fn release_str() -> Option<&'static str> {
option_env!("CFG_RELEASE")
}
/// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built.
pub fn commit_hash_str() -> Option<&'static str> {
option_env!("CFG_VER_HASH")
}
/// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string.
pub fn commit_date_str() -> Option<&'static str> {
option_env!("CFG_VER_DATE")
}
/// Prints version information and returns None on success or an error
/// message on panic.
pub fn version(binary: &str, matches: &getopts::Matches) {
let verbose = matches.opt_present("verbose");
println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
if verbose {
fn unw(x: Option<&str>) -> &str { x.unwrap_or("unknown") }
println!("binary: {}", binary);
println!("commit-hash: {}", unw(commit_hash_str()));
println!("commit-date: {}", unw(commit_date_str()));
println!("host: {}", config::host_triple());
println!("release: {}", unw(release_str()));
}
}
fn usage(verbose: bool, include_unstable_options: bool) {
let groups = if verbose {
config::rustc_optgroups()
} else {
config::rustc_short_optgroups()
};
let groups : Vec<_> = groups.into_iter()
.filter(|x| include_unstable_options || x.is_stable())
.map(|x|x.opt_group)
.collect();
let message = format!("Usage: rustc [OPTIONS] INPUT");
let extra_help = if verbose {
""
} else {
"\n --help -v Print the full set of options rustc accepts"
};
println!("{}\n\
Additional help:
-C help Print codegen options
-W help Print 'lint' options and default settings
-Z help Print internal options for debugging rustc{}\n",
getopts::usage(&message, &groups),
extra_help);
}
fn describe_lints(lint_store: &lint::LintStore, loaded_plugins: bool) {
println!("
Available lint options:
-W <foo> Warn about <foo>
-A <foo> Allow <foo>
-D <foo> Deny <foo>
-F <foo> Forbid <foo> (deny, and deny all overrides)
");
fn sort_lints(lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
lints.sort_by(|x: &&Lint, y: &&Lint| {
match x.default_level.cmp(&y.default_level) {
// The sort doesn't case-fold but it's doubtful we care.
Equal => x.name.cmp(y.name),
r => r,
}
});
lints
}
fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
-> Vec<(&'static str, Vec<lint::LintId>)> {
let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
&(y, _): &(&'static str, Vec<lint::LintId>)| {
x.cmp(y)
});
lints
}
let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints()
.iter().cloned().partition(|&(_, p)| p);
let plugin = sort_lints(plugin);
let builtin = sort_lints(builtin);
let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups()
.iter().cloned().partition(|&(_, _, p)| p);
let plugin_groups = sort_lint_groups(plugin_groups);
let builtin_groups = sort_lint_groups(builtin_groups);
let max_name_len = plugin.iter().chain(&builtin)
.map(|&s| s.name.chars().count())
.max().unwrap_or(0);
let padded = |x: &str| {
let mut s = repeat(" ").take(max_name_len - x.chars().count())
.collect::<String>();
s.push_str(x);
s
};
println!("Lint checks provided by rustc:\n");
println!(" {} {:7.7} {}", padded("name"), "default", "meaning");
println!(" {} {:7.7} {}", padded("----"), "-------", "-------");
let print_lints = |lints: Vec<&Lint>| {
for lint in lints {
let name = lint.name_lower().replace("_", "-");
println!(" {} {:7.7} {}",
padded(&name[..]), lint.default_level.as_str(), lint.desc);
}
println!("\n");
};
print_lints(builtin);
let max_name_len = plugin_groups.iter().chain(&builtin_groups)
.map(|&(s, _)| s.chars().count())
.max().unwrap_or(0);
let padded = |x: &str| {
let mut s = repeat(" ").take(max_name_len - x.chars().count())
.collect::<String>();
s.push_str(x);
s
};
println!("Lint groups provided by rustc:\n");
println!(" {} {}", padded("name"), "sub-lints");
println!(" {} {}", padded("----"), "---------");
let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| {
for (name, to) in lints {
let name = name.to_lowercase().replace("_", "-");
let desc = to.into_iter().map(|x| x.as_str().replace("_", "-"))
.collect::<Vec<String>>().connect(", ");
println!(" {} {}",
padded(&name[..]), desc);
}
println!("\n");
};
print_lint_groups(builtin_groups);
match (loaded_plugins, plugin.len(), plugin_groups.len()) {
(false, 0, _) | (false, _, 0) => {
println!("Compiler plugins can provide additional lints and lint groups. To see a \
listing of these, re-run `rustc -W help` with a crate filename.");
}
(false, _, _) => panic!("didn't load lint plugins but got them anyway!"),
(true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."),
(true, l, g) => {
if l > 0 {
println!("Lint checks provided by plugins loaded by this crate:\n");
print_lints(plugin);
}
if g > 0 {
println!("Lint groups provided by plugins loaded by this crate:\n");
print_lint_groups(plugin_groups);
}
}
}
}
fn describe_debug_flags() {
println!("\nAvailable debug options:\n");
for &(name, _, opt_type_desc, desc) in config::DB_OPTIONS {
let (width, extra) = match opt_type_desc {
Some(..) => (21, "=val"),
None => (25, "")
};
println!(" -Z {:>width$}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
fn describe_codegen_flags() {
println!("\nAvailable codegen options:\n");
for &(name, _, opt_type_desc, desc) in config::CG_OPTIONS {
let (width, extra) = match opt_type_desc {
Some(..) => (21, "=val"),
None => (25, "")
};
println!(" -C {:>width$}{} -- {}", name.replace("_", "-"),
extra, desc, width=width);
}
}
/// Process command line options. Emits messages as appropriate. If compilation
/// should continue, returns a getopts::Matches object parsed from args, otherwise
/// returns None.
pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
// Throw away the first argument, the name of the binary
let _binary = args.remove(0);
if args.is_empty() {
// user did not write `-v` nor `-Z unstable-options`, so do not
// include that extra information.
usage(false, false);
return None;
}
fn allows_unstable_options(matches: &getopts::Matches) -> bool {
let r = matches.opt_strs("Z");
r.iter().any(|x| *x == "unstable-options")
}
fn parse_all_options(args: &Vec<String>) -> getopts::Matches {
let all_groups : Vec<getopts::OptGroup>
= config::rustc_optgroups().into_iter().map(|x|x.opt_group).collect();
match getopts::getopts(&args[..], &all_groups) {
Ok(m) => {
if !allows_unstable_options(&m) {
// If -Z unstable-options was not specified, verify that
// no unstable options were present.
for opt in config::rustc_optgroups().into_iter().filter(|x| !x.is_stable()) {
let opt_name = if !opt.opt_group.long_name.is_empty() {
&opt.opt_group.long_name
} else {
&opt.opt_group.short_name
};
if m.opt_present(opt_name) {
early_error(&format!("use of unstable option '{}' requires \
-Z unstable-options", opt_name));
}
}
}
m
}
Err(f) => early_error(&f.to_string())
}
}
// As a speed optimization, first try to parse the command-line using just
// the stable options.
let matches = match getopts::getopts(&args[..], &config::optgroups()) {
Ok(ref m) if allows_unstable_options(m) => {
// If -Z unstable-options was specified, redo parsing with the
// unstable options to ensure that unstable options are defined
// in the returned getopts::Matches.
parse_all_options(&args)
}
Ok(m) => m,
Err(_) => {
// redo option parsing, including unstable options this time,
// in anticipation that the mishandled option was one of the
// unstable ones.
parse_all_options(&args)
}
};
if matches.opt_present("h") || matches.opt_present("help") {
usage(matches.opt_present("verbose"), allows_unstable_options(&matches));
return None;
}
// Don't handle -W help here, because we might first load plugins.
let r = matches.opt_strs("Z");
if r.iter().any(|x| *x == "help") {
describe_debug_flags();
return None;
}
let cg_flags = matches.opt_strs("C");
if cg_flags.iter().any(|x| *x == "help") {
describe_codegen_flags();
return None;
}
if cg_flags.contains(&"passes=list".to_string()) {
unsafe { ::llvm::LLVMRustPrintPasses(); }
return None;
}
if matches.opt_present("version") {
version("rustc", &matches);
return None;
}
Some(matches)
}
fn parse_crate_attrs(sess: &Session, input: &Input) ->
Vec<ast::Attribute> {
let result = match *input {
Input::File(ref ifile) => {
parse::parse_crate_attrs_from_file(ifile,
Vec::new(),
&sess.parse_sess)
}
Input::Str(ref src) => {
parse::parse_crate_attrs_from_source_str(
driver::anon_src().to_string(),
src.to_string(),
Vec::new(),
&sess.parse_sess)
}
};
result.into_iter().collect()
}
/// Run a procedure which will detect panics in the compiler and print nicer
/// error messages rather than just failing the test.
///
/// The diagnostic emitter yielded to the procedure should be used for reporting
/// errors of the compiler.
pub fn monitor<F:FnOnce()+Send+'static>(f: F) {
const STACK_SIZE: usize = 8 * 1024 * 1024; // 8MB
struct Sink(Arc<Mutex<Vec<u8>>>);
impl Write for Sink {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
Write::write(&mut *self.0.lock().unwrap(), data)
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
let data = Arc::new(Mutex::new(Vec::new()));
let err = Sink(data.clone());
let mut cfg = thread::Builder::new().name("rustc".to_string());
// FIXME: Hacks on hacks. If the env is trying to override the stack size
// then *don't* set it explicitly.
if env::var_os("RUST_MIN_STACK").is_none() {
cfg = cfg.stack_size(STACK_SIZE);
}
match cfg.spawn(move || { io::set_panic(box err); f() }).unwrap().join() {
Ok(()) => { /* fallthrough */ }
Err(value) => {
// Thread panicked without emitting a fatal diagnostic
if !value.is::<diagnostic::FatalError>() {
let mut emitter = diagnostic::EmitterWriter::stderr(diagnostic::Auto, None);
// a .span_bug or .bug call has already printed what
// it wants to print.
if !value.is::<diagnostic::ExplicitBug>() {
emitter.emit(
None,
"unexpected panic",
None,
diagnostic::Bug);
}
let xs = [
"the compiler unexpectedly panicked. this is a bug.".to_string(),
format!("we would appreciate a bug report: {}",
BUG_REPORT_URL),
];
for note in &xs {
emitter.emit(None, ¬e[..], None, diagnostic::Note)
}
if let None = env::var_os("RUST_BACKTRACE") {
emitter.emit(None, "run with `RUST_BACKTRACE=1` for a backtrace",
None, diagnostic::Note);
}
println!("{}", str::from_utf8(&data.lock().unwrap()).unwrap());
}
// Panic so the process returns a failure code, but don't pollute the
// output with some unnecessary panic messages, we've already
// printed everything that we needed to.
io::set_panic(box io::sink());
panic!();
}
}
}
pub fn diagnostics_registry() -> diagnostics::registry::Registry {
use syntax::diagnostics::registry::Registry;
let mut all_errors = Vec::new();
all_errors.push_all(&rustc::DIAGNOSTICS);
all_errors.push_all(&rustc_typeck::DIAGNOSTICS);
all_errors.push_all(&rustc_borrowck::DIAGNOSTICS);
all_errors.push_all(&rustc_resolve::DIAGNOSTICS);
Registry::new(&*all_errors)
}
pub fn main() {
let result = run(env::args().collect());
process::exit(result as i32);
}
| {
let input = match input {
Some(input) => input,
None => early_error("no input file provided"),
};
let attrs = attrs.as_ref().unwrap();
let t_outputs = driver::build_output_filenames(input,
odir,
ofile,
attrs,
sess);
let id = link::find_crate_name(Some(sess),
attrs,
input);
if *req == PrintRequest::CrateName {
println!("{}", id);
continue
}
let crate_types = driver::collect_crate_types(sess, attrs);
let metadata = driver::collect_crate_metadata(sess, attrs);
*sess.crate_metadata.borrow_mut() = metadata;
for &style in &crate_types {
let fname = link::filename_for_input(sess,
style,
&id,
&t_outputs.with_extension(""));
println!("{}", fname.file_name().unwrap()
.to_string_lossy());
}
} | conditional_block |
training-fas-sif-5.py | # training.py
# This is the training script which will be presented to the participant before they sleep
# or remain awake
#
# TODO
# Libraries - these seem fine and should not need altering.
from psychopy import visual, event, core, misc, data, gui, sound
# Participant needs to press y to continue.
def ready_cont():
stim_win.flip()
user_response=None
while user_response==None:
allKeys=event.waitKeys()
for thisKey in allKeys:
if thisKey=='y':
|
if thisKey=='q':
core.quit()
# Metronome function - This plays the metronome; the timing can also be altered here.
# The timing required needs to be passed to metronome function.
#music = pyglet.resource.media('klack.ogg', streaming=False)
music = sound.Sound(900,secs=0.01) # Just temporary
def metronome(met_time):
music.play()
core.wait(met_time)
music.play()
core.wait(met_time)
music.play()
core.wait(met_time)
music.play()
core.wait(met_time)
# The metronome alone so the participant can become familiar with
# the speed (no stimuli).
def metronome_alone():
stim_win.flip()
metronome(cvc_slow_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
# Variables
welcome_message = """Welcome to the training session! You will see four syllables in a row. Please read the entire row out loud 4 times in time to the metronome and try to say one syllable per beat. The first time will be slow, and the next 3 repetitions will be a little faster. Try to read as fluently as possible. Do not worry if you make mistakes, just keep in time with the beat.
Press y now to hear the speed of the metronome."""
sample_welcome = """The following will be a practice session to familiarize you with the sequences (press y to continue)"""
sample_goodbye = """The sample has ended, please press y if you are ready for the real session"""
thank_you = """The training session is complete,
Please inform a researcher you have finished.
Thank you."""
metronome_alone_message = """Playing the metronome..."""
# cvc rates
cvc_slow_rate = 1.0
# A cvc every 395ms with Warker e al (2008)
cvc_faster_rate = 0.395
# interval between each sequence
stim_interval = 1.0
between_tests_interval = 2.0
# Stimuli variables - These are the non counterbalanced stimuli.
sample_stim = ['gas fak man hang',
'has kag mang fan',
'gak nas ham fang']
real_stim = ['han kas mag fang',
'sing kim hig nif',
'fan mak gas hang',
'min hig kif sing',
'fan mag kas hang',
'hing sik mig nif',
'fak nag mang has',
'hif sin ging kim',
'kag hang fas nam',
'sin hing gim kif',
'kam nag fas hang',
'ning him sik gif',
'mang fas hag kan',
'sif kig hin ming',
'kas mag fang han',
'nim hik sif ging',
'hag mak fang nas',
'sin hik mif ging',
'mak hang fan gas',
'mig sing hik nif',
'gas fang nam hak',
'sing min gik hif',
'fan mak gang has',
'hin sif king gim',
'gan fang has mak',
'ging hik sim nif',
'gang kam fas han',
'gif king hin sim',
'mag nang has fak',
'gik sin mif hing',
'nam has kag fang',
'mif sin hing gik',
'kas hang gam fan',
'hing nim sif gik',
'mak han fas gang',
'mif hin sing kig',
'fak nas ham gang',
'hin sif ging kim',
'kan fang has gam',
'sig mif hin king',
'kam fas nang hag',
'sif ning him kig',
'gang fak han mas',
'sif kim gin hing',
'fam kag hang nas',
'hing nik sig mif',
'kas fan ham gang',
'king sin hif gim']
# Setting up the screen.
stim_win = visual.Window(monitor = "testMonitor", units ='norm', fullscr=True)
message = visual.TextStim(stim_win, text = welcome_message, font = "Arial")
message.setAutoDraw(True)
ready_cont()
stim_win.flip()
# The metronome so participant's know what it's like.
# Hmm allow participant to repeat? - Not really fair if
# some participants' run it more than others and pronounce
# cvc's better due to familiarity with the beat.
message.setText(metronome_alone_message)
metronome_alone()
core.wait(stim_interval)
stim_win.flip()
# Welcome the participant.
message.setText(sample_welcome)
ready_cont()
# The sample loop
stim_win.flip()
for i in range(len(sample_stim)):
message.setText(sample_stim[i])
stim_win.flip()
core.wait(stim_interval)
metronome(cvc_slow_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
core.wait(stim_interval)
# Ask participant if they are ready to continue
message.setText(sample_goodbye)
ready_cont()
# The real stimuli loop
stim_win.flip()
for i in range(len(real_stim)):
message.setText(real_stim[i])
stim_win.flip()
core.wait(stim_interval)
metronome(cvc_slow_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
core.wait(stim_interval)
# Saying goodbye
stim_win.flip()
message.setText(thank_you)
ready_cont()
core.wait(stim_interval)
#cleanup
stim_win.close()
core.quit()
| user_response=1 | conditional_block |
training-fas-sif-5.py | # training.py
# This is the training script which will be presented to the participant before they sleep
# or remain awake
#
# TODO
# Libraries - these seem fine and should not need altering.
from psychopy import visual, event, core, misc, data, gui, sound
# Participant needs to press y to continue.
def | ():
stim_win.flip()
user_response=None
while user_response==None:
allKeys=event.waitKeys()
for thisKey in allKeys:
if thisKey=='y':
user_response=1
if thisKey=='q':
core.quit()
# Metronome function - This plays the metronome; the timing can also be altered here.
# The timing required needs to be passed to metronome function.
#music = pyglet.resource.media('klack.ogg', streaming=False)
music = sound.Sound(900,secs=0.01) # Just temporary
def metronome(met_time):
music.play()
core.wait(met_time)
music.play()
core.wait(met_time)
music.play()
core.wait(met_time)
music.play()
core.wait(met_time)
# The metronome alone so the participant can become familiar with
# the speed (no stimuli).
def metronome_alone():
stim_win.flip()
metronome(cvc_slow_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
# Variables
welcome_message = """Welcome to the training session! You will see four syllables in a row. Please read the entire row out loud 4 times in time to the metronome and try to say one syllable per beat. The first time will be slow, and the next 3 repetitions will be a little faster. Try to read as fluently as possible. Do not worry if you make mistakes, just keep in time with the beat.
Press y now to hear the speed of the metronome."""
sample_welcome = """The following will be a practice session to familiarize you with the sequences (press y to continue)"""
sample_goodbye = """The sample has ended, please press y if you are ready for the real session"""
thank_you = """The training session is complete,
Please inform a researcher you have finished.
Thank you."""
metronome_alone_message = """Playing the metronome..."""
# cvc rates
cvc_slow_rate = 1.0
# A cvc every 395ms with Warker e al (2008)
cvc_faster_rate = 0.395
# interval between each sequence
stim_interval = 1.0
between_tests_interval = 2.0
# Stimuli variables - These are the non counterbalanced stimuli.
sample_stim = ['gas fak man hang',
'has kag mang fan',
'gak nas ham fang']
real_stim = ['han kas mag fang',
'sing kim hig nif',
'fan mak gas hang',
'min hig kif sing',
'fan mag kas hang',
'hing sik mig nif',
'fak nag mang has',
'hif sin ging kim',
'kag hang fas nam',
'sin hing gim kif',
'kam nag fas hang',
'ning him sik gif',
'mang fas hag kan',
'sif kig hin ming',
'kas mag fang han',
'nim hik sif ging',
'hag mak fang nas',
'sin hik mif ging',
'mak hang fan gas',
'mig sing hik nif',
'gas fang nam hak',
'sing min gik hif',
'fan mak gang has',
'hin sif king gim',
'gan fang has mak',
'ging hik sim nif',
'gang kam fas han',
'gif king hin sim',
'mag nang has fak',
'gik sin mif hing',
'nam has kag fang',
'mif sin hing gik',
'kas hang gam fan',
'hing nim sif gik',
'mak han fas gang',
'mif hin sing kig',
'fak nas ham gang',
'hin sif ging kim',
'kan fang has gam',
'sig mif hin king',
'kam fas nang hag',
'sif ning him kig',
'gang fak han mas',
'sif kim gin hing',
'fam kag hang nas',
'hing nik sig mif',
'kas fan ham gang',
'king sin hif gim']
# Setting up the screen.
stim_win = visual.Window(monitor = "testMonitor", units ='norm', fullscr=True)
message = visual.TextStim(stim_win, text = welcome_message, font = "Arial")
message.setAutoDraw(True)
ready_cont()
stim_win.flip()
# The metronome so participant's know what it's like.
# Hmm allow participant to repeat? - Not really fair if
# some participants' run it more than others and pronounce
# cvc's better due to familiarity with the beat.
message.setText(metronome_alone_message)
metronome_alone()
core.wait(stim_interval)
stim_win.flip()
# Welcome the participant.
message.setText(sample_welcome)
ready_cont()
# The sample loop
stim_win.flip()
for i in range(len(sample_stim)):
message.setText(sample_stim[i])
stim_win.flip()
core.wait(stim_interval)
metronome(cvc_slow_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
core.wait(stim_interval)
# Ask participant if they are ready to continue
message.setText(sample_goodbye)
ready_cont()
# The real stimuli loop
stim_win.flip()
for i in range(len(real_stim)):
message.setText(real_stim[i])
stim_win.flip()
core.wait(stim_interval)
metronome(cvc_slow_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
core.wait(stim_interval)
# Saying goodbye
stim_win.flip()
message.setText(thank_you)
ready_cont()
core.wait(stim_interval)
#cleanup
stim_win.close()
core.quit()
| ready_cont | identifier_name |
training-fas-sif-5.py | # training.py
# This is the training script which will be presented to the participant before they sleep
# or remain awake
#
# TODO
# Libraries - these seem fine and should not need altering.
from psychopy import visual, event, core, misc, data, gui, sound
# Participant needs to press y to continue.
def ready_cont():
stim_win.flip()
user_response=None
while user_response==None:
allKeys=event.waitKeys()
for thisKey in allKeys:
if thisKey=='y':
user_response=1
if thisKey=='q':
core.quit()
# Metronome function - This plays the metronome; the timing can also be altered here.
# The timing required needs to be passed to metronome function.
#music = pyglet.resource.media('klack.ogg', streaming=False)
music = sound.Sound(900,secs=0.01) # Just temporary
def metronome(met_time):
|
# The metronome alone so the participant can become familiar with
# the speed (no stimuli).
def metronome_alone():
stim_win.flip()
metronome(cvc_slow_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
# Variables
welcome_message = """Welcome to the training session! You will see four syllables in a row. Please read the entire row out loud 4 times in time to the metronome and try to say one syllable per beat. The first time will be slow, and the next 3 repetitions will be a little faster. Try to read as fluently as possible. Do not worry if you make mistakes, just keep in time with the beat.
Press y now to hear the speed of the metronome."""
sample_welcome = """The following will be a practice session to familiarize you with the sequences (press y to continue)"""
sample_goodbye = """The sample has ended, please press y if you are ready for the real session"""
thank_you = """The training session is complete,
Please inform a researcher you have finished.
Thank you."""
metronome_alone_message = """Playing the metronome..."""
# cvc rates
cvc_slow_rate = 1.0
# A cvc every 395ms with Warker e al (2008)
cvc_faster_rate = 0.395
# interval between each sequence
stim_interval = 1.0
between_tests_interval = 2.0
# Stimuli variables - These are the non counterbalanced stimuli.
sample_stim = ['gas fak man hang',
'has kag mang fan',
'gak nas ham fang']
real_stim = ['han kas mag fang',
'sing kim hig nif',
'fan mak gas hang',
'min hig kif sing',
'fan mag kas hang',
'hing sik mig nif',
'fak nag mang has',
'hif sin ging kim',
'kag hang fas nam',
'sin hing gim kif',
'kam nag fas hang',
'ning him sik gif',
'mang fas hag kan',
'sif kig hin ming',
'kas mag fang han',
'nim hik sif ging',
'hag mak fang nas',
'sin hik mif ging',
'mak hang fan gas',
'mig sing hik nif',
'gas fang nam hak',
'sing min gik hif',
'fan mak gang has',
'hin sif king gim',
'gan fang has mak',
'ging hik sim nif',
'gang kam fas han',
'gif king hin sim',
'mag nang has fak',
'gik sin mif hing',
'nam has kag fang',
'mif sin hing gik',
'kas hang gam fan',
'hing nim sif gik',
'mak han fas gang',
'mif hin sing kig',
'fak nas ham gang',
'hin sif ging kim',
'kan fang has gam',
'sig mif hin king',
'kam fas nang hag',
'sif ning him kig',
'gang fak han mas',
'sif kim gin hing',
'fam kag hang nas',
'hing nik sig mif',
'kas fan ham gang',
'king sin hif gim']
# Setting up the screen.
stim_win = visual.Window(monitor = "testMonitor", units ='norm', fullscr=True)
message = visual.TextStim(stim_win, text = welcome_message, font = "Arial")
message.setAutoDraw(True)
ready_cont()
stim_win.flip()
# The metronome so participant's know what it's like.
# Hmm allow participant to repeat? - Not really fair if
# some participants' run it more than others and pronounce
# cvc's better due to familiarity with the beat.
message.setText(metronome_alone_message)
metronome_alone()
core.wait(stim_interval)
stim_win.flip()
# Welcome the participant.
message.setText(sample_welcome)
ready_cont()
# The sample loop
stim_win.flip()
for i in range(len(sample_stim)):
message.setText(sample_stim[i])
stim_win.flip()
core.wait(stim_interval)
metronome(cvc_slow_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
core.wait(stim_interval)
# Ask participant if they are ready to continue
message.setText(sample_goodbye)
ready_cont()
# The real stimuli loop
stim_win.flip()
for i in range(len(real_stim)):
message.setText(real_stim[i])
stim_win.flip()
core.wait(stim_interval)
metronome(cvc_slow_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
core.wait(stim_interval)
# Saying goodbye
stim_win.flip()
message.setText(thank_you)
ready_cont()
core.wait(stim_interval)
#cleanup
stim_win.close()
core.quit()
| music.play()
core.wait(met_time)
music.play()
core.wait(met_time)
music.play()
core.wait(met_time)
music.play()
core.wait(met_time) | identifier_body |
training-fas-sif-5.py | # training.py
# This is the training script which will be presented to the participant before they sleep
# or remain awake
#
# TODO
# Libraries - these seem fine and should not need altering.
from psychopy import visual, event, core, misc, data, gui, sound
# Participant needs to press y to continue.
def ready_cont():
stim_win.flip()
user_response=None
while user_response==None:
allKeys=event.waitKeys()
for thisKey in allKeys:
if thisKey=='y':
user_response=1
if thisKey=='q':
core.quit()
# Metronome function - This plays the metronome; the timing can also be altered here.
# The timing required needs to be passed to metronome function.
#music = pyglet.resource.media('klack.ogg', streaming=False)
music = sound.Sound(900,secs=0.01) # Just temporary
def metronome(met_time):
music.play()
core.wait(met_time)
music.play()
core.wait(met_time)
music.play()
core.wait(met_time)
music.play()
core.wait(met_time)
# The metronome alone so the participant can become familiar with
# the speed (no stimuli).
def metronome_alone():
stim_win.flip()
metronome(cvc_slow_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
# Variables
welcome_message = """Welcome to the training session! You will see four syllables in a row. Please read the entire row out loud 4 times in time to the metronome and try to say one syllable per beat. The first time will be slow, and the next 3 repetitions will be a little faster. Try to read as fluently as possible. Do not worry if you make mistakes, just keep in time with the beat.
Press y now to hear the speed of the metronome."""
sample_welcome = """The following will be a practice session to familiarize you with the sequences (press y to continue)"""
sample_goodbye = """The sample has ended, please press y if you are ready for the real session"""
thank_you = """The training session is complete,
Please inform a researcher you have finished.
Thank you."""
metronome_alone_message = """Playing the metronome..."""
# cvc rates
cvc_slow_rate = 1.0
# A cvc every 395ms with Warker e al (2008)
cvc_faster_rate = 0.395
# interval between each sequence
stim_interval = 1.0
between_tests_interval = 2.0
# Stimuli variables - These are the non counterbalanced stimuli.
sample_stim = ['gas fak man hang',
'has kag mang fan',
'gak nas ham fang']
real_stim = ['han kas mag fang',
'sing kim hig nif',
'fan mak gas hang',
'min hig kif sing',
'fan mag kas hang',
'hing sik mig nif',
'fak nag mang has',
'hif sin ging kim',
'kag hang fas nam',
'sin hing gim kif',
'kam nag fas hang',
'ning him sik gif',
'mang fas hag kan',
'sif kig hin ming',
'kas mag fang han',
'nim hik sif ging',
'hag mak fang nas',
'sin hik mif ging',
'mak hang fan gas',
'mig sing hik nif',
'gas fang nam hak',
'sing min gik hif',
'fan mak gang has',
'hin sif king gim',
'gan fang has mak',
'ging hik sim nif',
'gang kam fas han',
'gif king hin sim',
'mag nang has fak',
'gik sin mif hing',
'nam has kag fang',
'mif sin hing gik',
'kas hang gam fan',
'hing nim sif gik',
'mak han fas gang',
'mif hin sing kig',
'fak nas ham gang',
'hin sif ging kim',
'kan fang has gam',
'sig mif hin king',
'kam fas nang hag',
'sif ning him kig',
'gang fak han mas',
'sif kim gin hing',
'fam kag hang nas',
'hing nik sig mif',
'kas fan ham gang',
'king sin hif gim']
# Setting up the screen.
stim_win = visual.Window(monitor = "testMonitor", units ='norm', fullscr=True)
message = visual.TextStim(stim_win, text = welcome_message, font = "Arial")
message.setAutoDraw(True)
ready_cont()
stim_win.flip()
# The metronome so participant's know what it's like.
# Hmm allow participant to repeat? - Not really fair if
# some participants' run it more than others and pronounce
# cvc's better due to familiarity with the beat.
message.setText(metronome_alone_message)
metronome_alone()
core.wait(stim_interval)
stim_win.flip()
|
# The sample loop
stim_win.flip()
for i in range(len(sample_stim)):
message.setText(sample_stim[i])
stim_win.flip()
core.wait(stim_interval)
metronome(cvc_slow_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
core.wait(stim_interval)
# Ask participant if they are ready to continue
message.setText(sample_goodbye)
ready_cont()
# The real stimuli loop
stim_win.flip()
for i in range(len(real_stim)):
message.setText(real_stim[i])
stim_win.flip()
core.wait(stim_interval)
metronome(cvc_slow_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
metronome(cvc_faster_rate)
core.wait(stim_interval)
# Saying goodbye
stim_win.flip()
message.setText(thank_you)
ready_cont()
core.wait(stim_interval)
#cleanup
stim_win.close()
core.quit() | # Welcome the participant.
message.setText(sample_welcome)
ready_cont()
| random_line_split |
util.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Utility traits and functions.
use num::PrimInt;
/// Returns `single` if the given number is 1, or `plural` otherwise.
pub(crate) fn plural<'a, T: PrimInt>(n: T, single: &'a str, plural: &'a str) -> &'a str {
if n == T::one() { single } else { plural }
}
fn byte_count(size: i64, unit_single: &str, unit_plural: &str, multiple: &[&str]) -> String |
/// Convert a byte count to a human-readable representation of the byte count
/// using appropriate IEC suffixes.
pub(crate) fn byte_count_iec(size: i64) -> String {
let suffixes = [
" KiB", " MiB", " GiB", " TiB", " PiB", " EiB", " ZiB", " YiB",
];
byte_count(size, " byte", " bytes", &suffixes)
}
/// Convert a byte count to a human-readable representation of the byte count
/// using short suffixes.
pub(crate) fn byte_count_short(size: i64) -> String {
byte_count(size, "", "", &["K", "M", "G", "T", "P", "E", "Z", "Y"])
}
| {
const UNIT_LIMIT: i64 = 9999;
match (size, multiple.split_last()) {
(std::i64::MIN..=UNIT_LIMIT, _) | (_, None) => {
format!("{}{}", size, plural(size, unit_single, unit_plural))
}
(size, Some((last_multiple, multiple))) => {
let mut divisor = 1024;
for unit in multiple.iter() {
if size < (UNIT_LIMIT + 1) * divisor {
return format!("{:.2}{}", (size as f64) / (divisor as f64), unit);
}
divisor *= 1024;
}
format!("{:.2}{}", (size as f64) / (divisor as f64), last_multiple)
}
}
} | identifier_body |
util.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Utility traits and functions.
use num::PrimInt;
/// Returns `single` if the given number is 1, or `plural` otherwise.
pub(crate) fn plural<'a, T: PrimInt>(n: T, single: &'a str, plural: &'a str) -> &'a str {
if n == T::one() { single } else { plural }
}
fn byte_count(size: i64, unit_single: &str, unit_plural: &str, multiple: &[&str]) -> String {
const UNIT_LIMIT: i64 = 9999;
match (size, multiple.split_last()) {
(std::i64::MIN..=UNIT_LIMIT, _) | (_, None) => {
format!("{}{}", size, plural(size, unit_single, unit_plural))
}
(size, Some((last_multiple, multiple))) => {
let mut divisor = 1024;
for unit in multiple.iter() {
if size < (UNIT_LIMIT + 1) * divisor {
return format!("{:.2}{}", (size as f64) / (divisor as f64), unit);
}
divisor *= 1024;
}
format!("{:.2}{}", (size as f64) / (divisor as f64), last_multiple) | /// Convert a byte count to a human-readable representation of the byte count
/// using appropriate IEC suffixes.
pub(crate) fn byte_count_iec(size: i64) -> String {
let suffixes = [
" KiB", " MiB", " GiB", " TiB", " PiB", " EiB", " ZiB", " YiB",
];
byte_count(size, " byte", " bytes", &suffixes)
}
/// Convert a byte count to a human-readable representation of the byte count
/// using short suffixes.
pub(crate) fn byte_count_short(size: i64) -> String {
byte_count(size, "", "", &["K", "M", "G", "T", "P", "E", "Z", "Y"])
} | }
}
}
| random_line_split |
util.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Utility traits and functions.
use num::PrimInt;
/// Returns `single` if the given number is 1, or `plural` otherwise.
pub(crate) fn plural<'a, T: PrimInt>(n: T, single: &'a str, plural: &'a str) -> &'a str {
if n == T::one() | else { plural }
}
fn byte_count(size: i64, unit_single: &str, unit_plural: &str, multiple: &[&str]) -> String {
const UNIT_LIMIT: i64 = 9999;
match (size, multiple.split_last()) {
(std::i64::MIN..=UNIT_LIMIT, _) | (_, None) => {
format!("{}{}", size, plural(size, unit_single, unit_plural))
}
(size, Some((last_multiple, multiple))) => {
let mut divisor = 1024;
for unit in multiple.iter() {
if size < (UNIT_LIMIT + 1) * divisor {
return format!("{:.2}{}", (size as f64) / (divisor as f64), unit);
}
divisor *= 1024;
}
format!("{:.2}{}", (size as f64) / (divisor as f64), last_multiple)
}
}
}
/// Convert a byte count to a human-readable representation of the byte count
/// using appropriate IEC suffixes.
pub(crate) fn byte_count_iec(size: i64) -> String {
let suffixes = [
" KiB", " MiB", " GiB", " TiB", " PiB", " EiB", " ZiB", " YiB",
];
byte_count(size, " byte", " bytes", &suffixes)
}
/// Convert a byte count to a human-readable representation of the byte count
/// using short suffixes.
pub(crate) fn byte_count_short(size: i64) -> String {
byte_count(size, "", "", &["K", "M", "G", "T", "P", "E", "Z", "Y"])
}
| { single } | conditional_block |
util.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
//! Utility traits and functions.
use num::PrimInt;
/// Returns `single` if the given number is 1, or `plural` otherwise.
pub(crate) fn plural<'a, T: PrimInt>(n: T, single: &'a str, plural: &'a str) -> &'a str {
if n == T::one() { single } else { plural }
}
fn byte_count(size: i64, unit_single: &str, unit_plural: &str, multiple: &[&str]) -> String {
const UNIT_LIMIT: i64 = 9999;
match (size, multiple.split_last()) {
(std::i64::MIN..=UNIT_LIMIT, _) | (_, None) => {
format!("{}{}", size, plural(size, unit_single, unit_plural))
}
(size, Some((last_multiple, multiple))) => {
let mut divisor = 1024;
for unit in multiple.iter() {
if size < (UNIT_LIMIT + 1) * divisor {
return format!("{:.2}{}", (size as f64) / (divisor as f64), unit);
}
divisor *= 1024;
}
format!("{:.2}{}", (size as f64) / (divisor as f64), last_multiple)
}
}
}
/// Convert a byte count to a human-readable representation of the byte count
/// using appropriate IEC suffixes.
pub(crate) fn | (size: i64) -> String {
let suffixes = [
" KiB", " MiB", " GiB", " TiB", " PiB", " EiB", " ZiB", " YiB",
];
byte_count(size, " byte", " bytes", &suffixes)
}
/// Convert a byte count to a human-readable representation of the byte count
/// using short suffixes.
pub(crate) fn byte_count_short(size: i64) -> String {
byte_count(size, "", "", &["K", "M", "G", "T", "P", "E", "Z", "Y"])
}
| byte_count_iec | identifier_name |
exclusion.ts | import * as util from "./util";
import debug from "debug";
const log = debug("json-property-filter:exclusion");
export function extract(filters: string[]) {
debug("Extract filters");
const extractDebug = log.extend("extract");
const exclusionFilters: string[] = [];
for (let i = filters.length; i--; ) |
return exclusionFilters;
}
export function filter(source: object, filters: string[]) {
log("Apply filters: %o", filters);
const destination = Array.isArray(source) ? [] : {};
apply(source, filters, destination, util.EMPTY_CONTEXT);
return destination;
}
function apply(source: object, filters: string[], destination: object, context: util.Context) {
const applyDebug = log.extend(context.absolutePath);
for (const propertyName in source) {
if (source.hasOwnProperty(propertyName)) {
applyDebug("Read property: %s", propertyName);
const propertyValue = source[propertyName];
if (!isFiltered(filters, context, propertyName)) {
let value = source[propertyName];
if (typeof propertyValue === "object") {
const newContext = util.createContext(context, source, propertyName);
value = Array.isArray(propertyValue) ? [] : {};
apply(propertyValue, filters, value, newContext);
}
applyDebug("Add property: %s", propertyName);
const index = +propertyName;
if (Array.isArray(destination) && !isNaN(index)) {
destination.splice(index, 0, value);
} else {
destination[propertyName] = value;
}
}
}
}
}
function isFiltered(filters: string[], context: util.Context, propertyName: string) {
const expectedRootPropertiesFilter = context.relativePath !== "" ? context.relativePath + ".*" : "*";
const expectedAllPropertiesFilter = context.relativePath !== "" ? context.relativePath + ".**" : "**";
const relativePath = context.relativePath ? `${context.relativePath}.${propertyName}` : propertyName;
const segments = context.segments ? context.segments.concat(propertyName) : [propertyName];
const absolutePath = segments.join(".");
return (
filters.includes(absolutePath) ||
filters.includes(relativePath) ||
filters.includes(context.absolutePath) ||
filters.includes(context.relativePath) ||
filters.includes(expectedAllPropertiesFilter) ||
filters.includes(expectedRootPropertiesFilter)
);
}
| {
const value = filters[i];
const firstCharacter = value[0];
if (value.length && firstCharacter === "-") {
extractDebug("Extracting filter: %s", value);
const filterWithoutSymbol = firstCharacter === "-" ? value.substring(1) : value;
exclusionFilters.push(filterWithoutSymbol);
}
} | conditional_block |
exclusion.ts | import * as util from "./util";
import debug from "debug";
const log = debug("json-property-filter:exclusion");
export function extract(filters: string[]) {
debug("Extract filters");
const extractDebug = log.extend("extract");
const exclusionFilters: string[] = [];
for (let i = filters.length; i--; ) {
const value = filters[i];
const firstCharacter = value[0];
if (value.length && firstCharacter === "-") {
extractDebug("Extracting filter: %s", value);
const filterWithoutSymbol = firstCharacter === "-" ? value.substring(1) : value;
exclusionFilters.push(filterWithoutSymbol);
}
}
return exclusionFilters;
}
export function filter(source: object, filters: string[]) {
log("Apply filters: %o", filters);
const destination = Array.isArray(source) ? [] : {};
apply(source, filters, destination, util.EMPTY_CONTEXT);
return destination;
}
function apply(source: object, filters: string[], destination: object, context: util.Context) {
const applyDebug = log.extend(context.absolutePath);
for (const propertyName in source) {
if (source.hasOwnProperty(propertyName)) {
applyDebug("Read property: %s", propertyName);
const propertyValue = source[propertyName];
if (!isFiltered(filters, context, propertyName)) {
let value = source[propertyName];
if (typeof propertyValue === "object") {
const newContext = util.createContext(context, source, propertyName);
value = Array.isArray(propertyValue) ? [] : {};
apply(propertyValue, filters, value, newContext);
}
applyDebug("Add property: %s", propertyName);
const index = +propertyName;
if (Array.isArray(destination) && !isNaN(index)) {
destination.splice(index, 0, value);
} else {
destination[propertyName] = value;
}
}
}
}
}
function | (filters: string[], context: util.Context, propertyName: string) {
const expectedRootPropertiesFilter = context.relativePath !== "" ? context.relativePath + ".*" : "*";
const expectedAllPropertiesFilter = context.relativePath !== "" ? context.relativePath + ".**" : "**";
const relativePath = context.relativePath ? `${context.relativePath}.${propertyName}` : propertyName;
const segments = context.segments ? context.segments.concat(propertyName) : [propertyName];
const absolutePath = segments.join(".");
return (
filters.includes(absolutePath) ||
filters.includes(relativePath) ||
filters.includes(context.absolutePath) ||
filters.includes(context.relativePath) ||
filters.includes(expectedAllPropertiesFilter) ||
filters.includes(expectedRootPropertiesFilter)
);
}
| isFiltered | identifier_name |
exclusion.ts | import * as util from "./util";
import debug from "debug";
const log = debug("json-property-filter:exclusion");
export function extract(filters: string[]) {
debug("Extract filters");
const extractDebug = log.extend("extract");
const exclusionFilters: string[] = [];
for (let i = filters.length; i--; ) {
const value = filters[i];
const firstCharacter = value[0];
if (value.length && firstCharacter === "-") {
extractDebug("Extracting filter: %s", value);
const filterWithoutSymbol = firstCharacter === "-" ? value.substring(1) : value;
exclusionFilters.push(filterWithoutSymbol);
}
}
return exclusionFilters;
}
export function filter(source: object, filters: string[]) {
log("Apply filters: %o", filters);
const destination = Array.isArray(source) ? [] : {};
apply(source, filters, destination, util.EMPTY_CONTEXT);
return destination;
}
function apply(source: object, filters: string[], destination: object, context: util.Context) {
const applyDebug = log.extend(context.absolutePath);
for (const propertyName in source) {
if (source.hasOwnProperty(propertyName)) {
applyDebug("Read property: %s", propertyName);
const propertyValue = source[propertyName];
if (!isFiltered(filters, context, propertyName)) {
let value = source[propertyName];
if (typeof propertyValue === "object") {
const newContext = util.createContext(context, source, propertyName);
value = Array.isArray(propertyValue) ? [] : {};
apply(propertyValue, filters, value, newContext);
}
applyDebug("Add property: %s", propertyName);
const index = +propertyName;
if (Array.isArray(destination) && !isNaN(index)) {
destination.splice(index, 0, value);
} else {
destination[propertyName] = value;
}
}
}
}
}
function isFiltered(filters: string[], context: util.Context, propertyName: string) {
const expectedRootPropertiesFilter = context.relativePath !== "" ? context.relativePath + ".*" : "*";
const expectedAllPropertiesFilter = context.relativePath !== "" ? context.relativePath + ".**" : "**";
|
return (
filters.includes(absolutePath) ||
filters.includes(relativePath) ||
filters.includes(context.absolutePath) ||
filters.includes(context.relativePath) ||
filters.includes(expectedAllPropertiesFilter) ||
filters.includes(expectedRootPropertiesFilter)
);
} | const relativePath = context.relativePath ? `${context.relativePath}.${propertyName}` : propertyName;
const segments = context.segments ? context.segments.concat(propertyName) : [propertyName];
const absolutePath = segments.join("."); | random_line_split |
exclusion.ts | import * as util from "./util";
import debug from "debug";
const log = debug("json-property-filter:exclusion");
export function extract(filters: string[]) |
export function filter(source: object, filters: string[]) {
log("Apply filters: %o", filters);
const destination = Array.isArray(source) ? [] : {};
apply(source, filters, destination, util.EMPTY_CONTEXT);
return destination;
}
function apply(source: object, filters: string[], destination: object, context: util.Context) {
const applyDebug = log.extend(context.absolutePath);
for (const propertyName in source) {
if (source.hasOwnProperty(propertyName)) {
applyDebug("Read property: %s", propertyName);
const propertyValue = source[propertyName];
if (!isFiltered(filters, context, propertyName)) {
let value = source[propertyName];
if (typeof propertyValue === "object") {
const newContext = util.createContext(context, source, propertyName);
value = Array.isArray(propertyValue) ? [] : {};
apply(propertyValue, filters, value, newContext);
}
applyDebug("Add property: %s", propertyName);
const index = +propertyName;
if (Array.isArray(destination) && !isNaN(index)) {
destination.splice(index, 0, value);
} else {
destination[propertyName] = value;
}
}
}
}
}
function isFiltered(filters: string[], context: util.Context, propertyName: string) {
const expectedRootPropertiesFilter = context.relativePath !== "" ? context.relativePath + ".*" : "*";
const expectedAllPropertiesFilter = context.relativePath !== "" ? context.relativePath + ".**" : "**";
const relativePath = context.relativePath ? `${context.relativePath}.${propertyName}` : propertyName;
const segments = context.segments ? context.segments.concat(propertyName) : [propertyName];
const absolutePath = segments.join(".");
return (
filters.includes(absolutePath) ||
filters.includes(relativePath) ||
filters.includes(context.absolutePath) ||
filters.includes(context.relativePath) ||
filters.includes(expectedAllPropertiesFilter) ||
filters.includes(expectedRootPropertiesFilter)
);
}
| {
debug("Extract filters");
const extractDebug = log.extend("extract");
const exclusionFilters: string[] = [];
for (let i = filters.length; i--; ) {
const value = filters[i];
const firstCharacter = value[0];
if (value.length && firstCharacter === "-") {
extractDebug("Extracting filter: %s", value);
const filterWithoutSymbol = firstCharacter === "-" ? value.substring(1) : value;
exclusionFilters.push(filterWithoutSymbol);
}
}
return exclusionFilters;
} | identifier_body |
event-handlers.spec.ts | /**
* Unit tests for The Cave of the Mind
*/
import Game from "../../core/models/game";
import {Monster} from "../../core/models/monster";
import {Artifact} from "../../core/models/artifact";
import {initLiveGame} from "../../core/utils/testing";
import {event_handlers} from "./event-handlers";
import {custom_commands} from "./commands";
// SETUP
const game = new Game();
beforeAll(() => { global['game'] = game; });
afterAll(() => { delete global['game']; });
// to initialize the test, we need to load the whole game data.
// this requires that a real, live API is running.
beforeEach(() => {
game.registerAdventureLogic(event_handlers, custom_commands);
game.slug = 'the-cave-of-the-mind';
return initLiveGame(game);
});
// uncomment the following for debugging
// afterEach(() => { game.history.history.map((h) => console.log(h.command, h.results)); });
// TESTS
test("game setup", () => {
expect(game.rooms.rooms.length).toBe(31);
expect(game.artifacts.all.length).toBe(51 + 5); // includes player artifacts
expect(game.effects.all.length).toBe(15);
expect(game.monsters.all.length).toBe(22); // 14 base monsters + 7 group monster members + player
expect(game.monsters.get(12).name).toBe("The Mind");
expect(game.monsters.get(12).combat_verbs.length).toBe(3);
});
test("miner's pick", () => {
game.player.moveToRoom(5);
game.artifacts.get(19).reveal();
game.triggerEvent("use", "", game.artifacts.get(7));
expect(game.artifacts.get(19).room_id).toBeNull();
expect(game.artifacts.get(18).room_id).toBe(5);
});
test("inscription", () => {
game.mock_random_numbers = [1, 2, 3];
expect(game.player.inventory.length).toBe(5);
game.triggerEvent("beforeRead", "", game.artifacts.get(17));
expect(game.player.inventory.length).toBe(2); | });
test("power spell effects", () => {
game.triggerEvent("power", 20);
game.queue.run();
expect(game.history.getLastOutput().text).toBe("You hear a loud sonic boom which echoes all around you!");
game.mock_random_numbers = [16];
game.triggerEvent("power", 51);
game.queue.run();
expect(game.history.getLastOutput().text).toBe("You are being teleported...");
expect(game.player.room_id).toBe(16);
});
test("potion", () => {
const p = game.artifacts.get(16);
game.triggerEvent("use", "potion", p);
expect(game.effects.get(10).seen).toBeTruthy();
expect(game.won).toBeTruthy();
}); | expect(game.artifacts.get(52).room_id).toBe(1);
expect(game.artifacts.get(53).room_id).toBe(2);
expect(game.artifacts.get(54).room_id).toBe(3); | random_line_split |
en_ca.js | /*!
* froala_editor v3.0.0-rc.2 (https://www.froala.com/wysiwyg-editor)
* License https://froala.com/wysiwyg-editor/terms/
* Copyright 2014-2019 Froala Labs
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) :
typeof define === 'function' && define.amd ? define(['froala-editor'], factory) :
(factory(global.FroalaEditor));
}(this, (function (FE) { 'use strict';
FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE;
/**
* English spoken in Canada
*/
FE.LANGUAGE['en_ca'] = {
translation: {
// Place holder
'Type something': 'Type something',
// Basic formatting
'Bold': 'Bold',
'Italic': 'Italic',
'Underline': 'Underline',
'Strikethrough': 'Strikethrough',
// Main buttons
'Insert': 'Insert',
'Delete': 'Delete',
'Cancel': 'Cancel',
'OK': 'OK',
'Back': 'Back',
'Remove': 'Remove',
'More': 'More',
'Update': 'Update',
'Style': 'Style',
// Font
'Font Family': 'Font Family',
'Font Size': 'Font Size',
// Colors
'Colors': 'Colours',
'Background': 'Background',
'Text': 'Text',
'HEX Color': 'HEX Colour',
// Paragraphs
'Paragraph Format': 'Paragraph Format',
'Normal': 'Normal',
'Code': 'Code',
'Heading 1': 'Heading 1',
'Heading 2': 'Heading 2',
'Heading 3': 'Heading 3',
'Heading 4': 'Heading 4',
// Style
'Paragraph Style': 'Paragraph Style',
'Inline Style': 'Inline Style',
// Alignment
'Align': 'Align',
'Align Left': 'Align Left',
'Align Center': 'Align Centre',
'Align Right': 'Align Right',
'Align Justify': 'Align Justify',
'None': 'None',
// Lists
'Ordered List': 'Ordered List',
'Unordered List': 'Unordered List',
// Indent
'Decrease Indent': 'Decrease Indent',
'Increase Indent': 'Increase Indent',
// Links
'Insert Link': 'Insert Link',
'Open in new tab': 'Open in new tab',
'Open Link': 'Open Link',
'Edit Link': 'Edit Link',
'Unlink': 'Unlink',
'Choose Link': 'Choose Link',
// Images
'Insert Image': 'Insert Image',
'Upload Image': 'Upload Image',
'By URL': 'By URL',
'Browse': 'Browse',
'Drop image': 'Drop image',
'or click': 'or click',
'Manage Images': 'Manage Images',
'Loading': 'Loading',
'Deleting': 'Deleting',
'Tags': 'Tags',
'Are you sure? Image will be deleted.': 'Are you sure? Image will be deleted.',
'Replace': 'Replace',
'Uploading': 'Uploading',
'Loading image': 'Loading image',
'Display': 'Display',
'Inline': 'Inline',
'Break Text': 'Break Text',
'Alternative Text': 'Alternative Text',
'Change Size': 'Change Size',
'Width': 'Width',
'Height': 'Height',
'Something went wrong. Please try again.': 'Something went wrong. Please try again.',
'Image Caption': 'Image Caption',
'Advanced Edit': 'Advanced Edit',
// Video
'Insert Video': 'Insert Video',
'Embedded Code': 'Embedded Code',
'Paste in a video URL': 'Paste in a video URL',
'Drop video': 'Drop video',
'Your browser does not support HTML5 video.': 'Your browser does not support HTML5 video.',
'Upload Video': 'Upload Video',
// Tables
'Insert Table': 'Insert Table',
'Table Header': 'Table Header',
'Remove Table': 'Remove Table',
'Table Style': 'Table Style',
'Horizontal Align': 'Horizontal Align',
'Row': 'Row',
'Insert row above': 'Insert row above', | 'Delete column': 'Delete column',
'Cell': 'Cell',
'Merge cells': 'Merge cells',
'Horizontal split': 'Horizontal split',
'Vertical split': 'Vertical split',
'Cell Background': 'Cell Background',
'Vertical Align': 'Vertical Align',
'Top': 'Top',
'Middle': 'Middle',
'Bottom': 'Bottom',
'Align Top': 'Align Top',
'Align Middle': 'Align Middle',
'Align Bottom': 'Align Bottom',
'Cell Style': 'Cell Style',
// Files
'Upload File': 'Upload File',
'Drop file': 'Drop file',
// Emoticons
'Emoticons': 'Emoticons',
// Line breaker
'Break': 'Break',
// Math
'Subscript': 'Subscript',
'Superscript': 'Superscript',
// Full screen
'Fullscreen': 'Fullscreen',
// Horizontal line
'Insert Horizontal Line': 'Insert Horizontal Line',
// Clear formatting
'Clear Formatting': 'Clear Formatting',
// Save
'Save': 'Save',
// Undo, redo
'Undo': 'Undo',
'Redo': 'Redo',
// Select all
'Select All': 'Select All',
// Code view
'Code View': 'Code View',
// Quote
'Quote': 'Quote',
'Increase': 'Increase',
'Decrease': 'Decrease',
// Quick Insert
'Quick Insert': 'Quick Insert',
// Spcial Characters
'Special Characters': 'Special Characters',
'Latin': 'Latin',
'Greek': 'Greek',
'Cyrillic': 'Cyrillic',
'Punctuation': 'Punctuation',
'Currency': 'Currency',
'Arrows': 'Arrows',
'Math': 'Math',
'Misc': 'Misc',
// Print.
'Print': 'Print',
// Spell Checker.
'Spell Checker': 'Spell Checker',
// Help
'Help': 'Help',
'Shortcuts': 'Shortcuts',
'Inline Editor': 'Inline Editor',
'Show the editor': 'Show the editor',
'Common actions': 'Common actions',
'Copy': 'Copy',
'Cut': 'Cut',
'Paste': 'Paste',
'Basic Formatting': 'Basic Formatting',
'Increase quote level': 'Increase quote level',
'Decrease quote level': 'Decrease quote level',
'Image / Video': 'Image / Video',
'Resize larger': 'Resize larger',
'Resize smaller': 'Resize smaller',
'Table': 'Table',
'Select table cell': 'Select table cell',
'Extend selection one cell': 'Extend selection one cell',
'Extend selection one row': 'Extend selection one row',
'Navigation': 'Navigation',
'Focus popup / toolbar': 'Focus popup / toolbar',
'Return focus to previous position': 'Return focus to previous position',
// Embed.ly
'Embed URL': 'Embed URL',
'Paste in a URL to embed': 'Paste in a URL to embed',
// Word Paste.
'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': 'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?',
'Keep': 'Keep',
'Clean': 'Clean',
'Word Paste Detected': 'Word Paste Detected',
// Character Counter
'Characters': 'Characters',
// More Buttons
'More Text': 'More Text',
'More Paragraph': 'More Paragraph',
'More Rich': 'More Rich',
'More Misc': 'More Misc'
},
direction: 'ltr'
};
})));
//# sourceMappingURL=en_ca.js.map | 'Insert row below': 'Insert row below',
'Delete row': 'Delete row',
'Column': 'Column',
'Insert column before': 'Insert column before',
'Insert column after': 'Insert column after', | random_line_split |
news.ts | 'use strict';
angular.module( 'portailApp' )
.component( 'news',
{
bindings: { edition: '<' },
controller: [ '$sce', 'Popups', '$http', '$q', 'URL_ENT', 'RANDOM_IMAGES', 'currentUser',
function( $sce, Popups, $http, $q, URL_ENT, RANDOM_IMAGES, currentUser ) {
var ctrl = this;
ctrl.newsfeed = [];
ctrl.retrieve_news = function( force_reload ) {
var one_month_ago = moment().subtract( 1, 'months' ).toDate().toISOString();
$http.get( URL_ENT + '/api/news', {
params: {
user_id: ctrl.user.id,
'pubDate>': one_month_ago
}
} )
.then( function( response ) {
ctrl.newsfeed = _( response.data ).map( function( item, index ) {
item.trusted_content = $sce.trustAsHtml( item.description );
item.no_image = _( item.image ).isNull();
item.pubDate = moment( new Date( item.pubDate ) ).toDate();
item.image = 'app/node_modules/laclasse-common-client/images/11_publipostage.svg';
return item;
} );
ctrl.carouselIndex = 0;
if ( _( ctrl.user.profiles ).isEmpty() ) {
return $q.resolve( { data: [] } );
} else |
} )
.then( function( response ) {
ctrl.newsfeed = ctrl.newsfeed.concat( _( response.data ).map( function( item, index ) {
item.trusted_content = $sce.trustAsHtml( item.content );
item.no_image = _( item.image ).isNull();
item.pubDate = moment( new Date( item.pubDate ) ).toDate();
if ( _( item.image ).isNull() ) {
item.image = _( RANDOM_IMAGES ).sample();
}
return item;
} ) );
} );
};
ctrl.config_news_fluxes = function() {
Popups.manage_fluxes( function() {
ctrl.retrieve_news( true );
}, function error() { } );
};
ctrl.$onInit = function() {
currentUser.get( false ).then( function( user ) {
ctrl.user = user;
ctrl.retrieve_news( false );
} );
};
}],
template: `
<ul class="noir" rn-carousel rn-carousel-buffered rn-carousel-auto-slide="6" rn-carousel-index="$ctrl.carouselIndex">
<li ng:repeat="slide in $ctrl.newsfeed | orderBy:'pubDate':true" active="slide.active"
ng:class="{'publipostage': slide.title == 'Publipostage', 'no-image': slide.no_image}">
<div class="carousel-image"
ng:style="{'background-image': 'url(' + slide.image + ')'}"></div>
<div class="carousel-caption">
<span class="pub-date" ng:cloak>{{ slide.pubDate | date:'medium' }}</span>
<a href="{{ slide.link }}" target="_blank" ng:if="slide.link != 'notYetImplemented'">
<h6 ng:cloak>{{ slide.title }}</h6>
</a>
<h6 ng:if="slide.link == 'notYetImplemented'">{{ slide.title }}</h6>
<p ng:bind-html="slide.trusted_content"></p>
</div>
</li>
<div class="hidden-xs hidden-sm angular-carousel-indicators"
rn-carousel-indicators
slides="$ctrl.newsfeed"
rn-carousel-index="$ctrl.carouselIndex">
</div>
<span class="hidden-xs hidden-sm floating-button big toggle bouton-config-news blanc"
ng:if="$ctrl.user.is_admin() && $ctrl.edition"
ng:click="$ctrl.config_news_fluxes()"></span>
</ul>
`
} );
| {
return $http.get( URL_ENT + '/api/structures/' + ctrl.user.active_profile().structure_id + '/rss', { params: { 'pubDate>': one_month_ago } } );
} | conditional_block |
news.ts | 'use strict';
angular.module( 'portailApp' )
.component( 'news',
{
bindings: { edition: '<' },
controller: [ '$sce', 'Popups', '$http', '$q', 'URL_ENT', 'RANDOM_IMAGES', 'currentUser',
function( $sce, Popups, $http, $q, URL_ENT, RANDOM_IMAGES, currentUser ) {
var ctrl = this;
ctrl.newsfeed = [];
ctrl.retrieve_news = function( force_reload ) {
var one_month_ago = moment().subtract( 1, 'months' ).toDate().toISOString();
$http.get( URL_ENT + '/api/news', {
params: {
user_id: ctrl.user.id,
'pubDate>': one_month_ago
}
} )
.then( function( response ) {
ctrl.newsfeed = _( response.data ).map( function( item, index ) {
item.trusted_content = $sce.trustAsHtml( item.description );
item.no_image = _( item.image ).isNull();
item.pubDate = moment( new Date( item.pubDate ) ).toDate();
item.image = 'app/node_modules/laclasse-common-client/images/11_publipostage.svg';
return item;
} );
ctrl.carouselIndex = 0;
if ( _( ctrl.user.profiles ).isEmpty() ) {
return $q.resolve( { data: [] } );
} else {
return $http.get( URL_ENT + '/api/structures/' + ctrl.user.active_profile().structure_id + '/rss', { params: { 'pubDate>': one_month_ago } } );
}
} )
.then( function( response ) {
ctrl.newsfeed = ctrl.newsfeed.concat( _( response.data ).map( function( item, index ) {
item.trusted_content = $sce.trustAsHtml( item.content );
item.no_image = _( item.image ).isNull(); | }
return item;
} ) );
} );
};
ctrl.config_news_fluxes = function() {
Popups.manage_fluxes( function() {
ctrl.retrieve_news( true );
}, function error() { } );
};
ctrl.$onInit = function() {
currentUser.get( false ).then( function( user ) {
ctrl.user = user;
ctrl.retrieve_news( false );
} );
};
}],
template: `
<ul class="noir" rn-carousel rn-carousel-buffered rn-carousel-auto-slide="6" rn-carousel-index="$ctrl.carouselIndex">
<li ng:repeat="slide in $ctrl.newsfeed | orderBy:'pubDate':true" active="slide.active"
ng:class="{'publipostage': slide.title == 'Publipostage', 'no-image': slide.no_image}">
<div class="carousel-image"
ng:style="{'background-image': 'url(' + slide.image + ')'}"></div>
<div class="carousel-caption">
<span class="pub-date" ng:cloak>{{ slide.pubDate | date:'medium' }}</span>
<a href="{{ slide.link }}" target="_blank" ng:if="slide.link != 'notYetImplemented'">
<h6 ng:cloak>{{ slide.title }}</h6>
</a>
<h6 ng:if="slide.link == 'notYetImplemented'">{{ slide.title }}</h6>
<p ng:bind-html="slide.trusted_content"></p>
</div>
</li>
<div class="hidden-xs hidden-sm angular-carousel-indicators"
rn-carousel-indicators
slides="$ctrl.newsfeed"
rn-carousel-index="$ctrl.carouselIndex">
</div>
<span class="hidden-xs hidden-sm floating-button big toggle bouton-config-news blanc"
ng:if="$ctrl.user.is_admin() && $ctrl.edition"
ng:click="$ctrl.config_news_fluxes()"></span>
</ul>
`
} ); | item.pubDate = moment( new Date( item.pubDate ) ).toDate();
if ( _( item.image ).isNull() ) {
item.image = _( RANDOM_IMAGES ).sample(); | random_line_split |
trail_maker.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Mehmet Atakan Gürkan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program (probably in a file named COPYING).
# If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function, division
import numpy as np
from numpy.random import random, seed
import argparse, sys
parser = argparse.ArgumentParser(description='Creates a random walk trail')
parser.add_argument('-d',
type=int, default=3,
help='topological dimension of the trail (default: 3)')
parser.add_argument('-N',
type=int, default=1000,
help='number of steps in the trail (default: 1000)')
parser.add_argument('-i',
type=float, default=1.0,
help='size of increments (will get normalized by 1/sqrt(N))')
parser.add_argument('-r',
type=int, default=0,
help='repository size (default: 0)')
parser.add_argument('-c',
type=float, default=0.0,
help='bias strength')
parser.add_argument('-b',
type=float, default=3.0e40,
help='radius of boundary')
parser.add_argument('-s',
type=int, default=42,
help='random number seed (default: 42)')
parser.add_argument('--rangen',
type=int, default=-1,
help='generate this many random numbers before starting to build the trail (default: repo size; ignored if less than repo size)')
parser.add_argument('-P0',
type=float, default=0.0, dest='P0',
help='initial value (for 1D)')
parser.add_argument('-P0x',
type=float, default=0.0, dest='P0x',
help='initial value of x component (for 3D)')
parser.add_argument('-P0y',
type=float, default=0.0, dest='P0y',
help='initial value of y component (for 3D)')
parser.add_argument('-P0z',
type=float, default=0.0, dest='P0z',
help='initial value of z component (for 3D)')
parser.add_argument('-o','--output-file',
dest='outfile',
type=argparse.FileType('w'),
default=sys.stdout,
help='output filename (if not given, use stdout)')
parser.add_argument('--numpy', dest='outputformat', action='store_const',
const='numpy', default='undecided',
help='output in NumPy format (default: ASCII for stdout, NumPy for file')
parser.add_argument('--ascii', dest='outputformat', action='store_const',
const='ascii', default='undecided',
help='output in ASCII format (default: ASCII for stdout, NumPy for file')
args = parser.parse_args()
seed(args.s)
if args.rangen > args.r :
dummy = random(args.rangen - args.r)
N = args.N
d = args.d
b = args.b
dP = args.i/np.sqrt(N)
def trail_1d(N, r=0, c=0.0, b=3.0e40) :
P0 = args.P0
P = P0
trl = np.empty(N+1)
trl[0] = P0
if r>0 and c!=0.0 : # repository initialization
u | else :
use_rep = False
dummy = random(r)
q = 0.0
for i in range(N) :
X = random() - 0.5
if X>q : DP = -dP
else : DP = dP
if np.fabs(P+DP) > b :
P -= DP
else :
P += DP
trl[i+1] = P
if use_rep :
rep[i%r] = X
q = -1.0*np.sum(rep)*rep_norm * c
return trl
def trail_3d(N, r=0, c=0.0, b=3.0e40) :
def vec_norm2(a) :
return a[0]*a[0] + a[1]*a[1] + a[2]*a[2]
b2 = b*b
P0x, P0y, P0z = args.P0x, args.P0y, args.P0z
Px, Py, Pz = P0x, P0y, P0z
trl = np.empty((N+1,3))
trl[0] = P0x, P0y, P0z
if r>0 and c!=0.0 : # repository initialization
use_rep = True
rep_norm = 1.0/np.sqrt(r)
repx, repy, repz = random(r)-0.5, random(r)-0.5, random(r)-0.5
qx = np.sum(repx)*rep_norm * c
qy = np.sum(repy)*rep_norm * c
qz = np.sum(repz)*rep_norm * c
else :
use_rep = False
dummy = random(r*3)
qx, qy, qz = 0.0, 0.0, 0.0
for i in range(N) :
Xx = random() - 0.5
Xy = random() - 0.5
Xz = random() - 0.5
if Xx>qx : DPx = -dP
else : DPx = dP
if Xy>qy : DPy = -dP
else : DPy = dP
if Xz>qz : DPz = -dP
else : DPz = dP
Ptry = Px+DPx, Py+DPy, Pz+DPz
if vec_norm2(Ptry) > b2 : # we'll cross bndry if we take this step
Px -= DPx # so we take the opposite step
Py -= DPy
Pz -= DPz
else : # we are safe
Px += DPx # so we take normal step
Py += DPy
Pz += DPz
trl[i+1] = (Px, Py, Pz)
if use_rep :
repx[i%r], repy[i%r], repz[i%r]= Xx, Xy, Xz
qx = -1.0*np.sum(repx)*rep_norm * c
qy = -1.0*np.sum(repy)*rep_norm * c
qz = -1.0*np.sum(repz)*rep_norm * c
return trl
if args.outputformat == 'undecided' :
if args.outfile == sys.stdout :
outputformat = 'ascii'
else :
outputformat = 'numpy'
else :
outputformat = args.outputformat
if d==1 :
trl = trail_1d(N, r=args.r, c=args.c, b=args.b)
if outputformat == 'ascii' :
for p in trl :
print('%e' % (p), file=args.outfile)
else :
np.save(args.outfile, trl)
elif d==3 :
trl = trail_3d(N, r=args.r, c=args.c, b=args.b)
if outputformat == 'ascii' :
for p in trl :
print('%e %e %e' % (p[0], p[1], p[2]), file=args.outfile)
else :
np.save(args.outfile, trl)
else :
print('illegal dimension given: %d' %(d))
| se_rep = True
rep_norm = 1.0/np.sqrt(r)
rep = random(r)-0.5
q = np.sum(rep)*rep_norm * c
| conditional_block |
trail_maker.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Mehmet Atakan Gürkan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program (probably in a file named COPYING).
# If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function, division
import numpy as np
from numpy.random import random, seed
import argparse, sys
parser = argparse.ArgumentParser(description='Creates a random walk trail')
parser.add_argument('-d',
type=int, default=3,
help='topological dimension of the trail (default: 3)')
parser.add_argument('-N',
type=int, default=1000,
help='number of steps in the trail (default: 1000)')
parser.add_argument('-i',
type=float, default=1.0,
help='size of increments (will get normalized by 1/sqrt(N))')
parser.add_argument('-r', | help='bias strength')
parser.add_argument('-b',
type=float, default=3.0e40,
help='radius of boundary')
parser.add_argument('-s',
type=int, default=42,
help='random number seed (default: 42)')
parser.add_argument('--rangen',
type=int, default=-1,
help='generate this many random numbers before starting to build the trail (default: repo size; ignored if less than repo size)')
parser.add_argument('-P0',
type=float, default=0.0, dest='P0',
help='initial value (for 1D)')
parser.add_argument('-P0x',
type=float, default=0.0, dest='P0x',
help='initial value of x component (for 3D)')
parser.add_argument('-P0y',
type=float, default=0.0, dest='P0y',
help='initial value of y component (for 3D)')
parser.add_argument('-P0z',
type=float, default=0.0, dest='P0z',
help='initial value of z component (for 3D)')
parser.add_argument('-o','--output-file',
dest='outfile',
type=argparse.FileType('w'),
default=sys.stdout,
help='output filename (if not given, use stdout)')
parser.add_argument('--numpy', dest='outputformat', action='store_const',
const='numpy', default='undecided',
help='output in NumPy format (default: ASCII for stdout, NumPy for file')
parser.add_argument('--ascii', dest='outputformat', action='store_const',
const='ascii', default='undecided',
help='output in ASCII format (default: ASCII for stdout, NumPy for file')
args = parser.parse_args()
seed(args.s)
if args.rangen > args.r :
dummy = random(args.rangen - args.r)
N = args.N
d = args.d
b = args.b
dP = args.i/np.sqrt(N)
def trail_1d(N, r=0, c=0.0, b=3.0e40) :
P0 = args.P0
P = P0
trl = np.empty(N+1)
trl[0] = P0
if r>0 and c!=0.0 : # repository initialization
use_rep = True
rep_norm = 1.0/np.sqrt(r)
rep = random(r)-0.5
q = np.sum(rep)*rep_norm * c
else :
use_rep = False
dummy = random(r)
q = 0.0
for i in range(N) :
X = random() - 0.5
if X>q : DP = -dP
else : DP = dP
if np.fabs(P+DP) > b :
P -= DP
else :
P += DP
trl[i+1] = P
if use_rep :
rep[i%r] = X
q = -1.0*np.sum(rep)*rep_norm * c
return trl
def trail_3d(N, r=0, c=0.0, b=3.0e40) :
def vec_norm2(a) :
return a[0]*a[0] + a[1]*a[1] + a[2]*a[2]
b2 = b*b
P0x, P0y, P0z = args.P0x, args.P0y, args.P0z
Px, Py, Pz = P0x, P0y, P0z
trl = np.empty((N+1,3))
trl[0] = P0x, P0y, P0z
if r>0 and c!=0.0 : # repository initialization
use_rep = True
rep_norm = 1.0/np.sqrt(r)
repx, repy, repz = random(r)-0.5, random(r)-0.5, random(r)-0.5
qx = np.sum(repx)*rep_norm * c
qy = np.sum(repy)*rep_norm * c
qz = np.sum(repz)*rep_norm * c
else :
use_rep = False
dummy = random(r*3)
qx, qy, qz = 0.0, 0.0, 0.0
for i in range(N) :
Xx = random() - 0.5
Xy = random() - 0.5
Xz = random() - 0.5
if Xx>qx : DPx = -dP
else : DPx = dP
if Xy>qy : DPy = -dP
else : DPy = dP
if Xz>qz : DPz = -dP
else : DPz = dP
Ptry = Px+DPx, Py+DPy, Pz+DPz
if vec_norm2(Ptry) > b2 : # we'll cross bndry if we take this step
Px -= DPx # so we take the opposite step
Py -= DPy
Pz -= DPz
else : # we are safe
Px += DPx # so we take normal step
Py += DPy
Pz += DPz
trl[i+1] = (Px, Py, Pz)
if use_rep :
repx[i%r], repy[i%r], repz[i%r]= Xx, Xy, Xz
qx = -1.0*np.sum(repx)*rep_norm * c
qy = -1.0*np.sum(repy)*rep_norm * c
qz = -1.0*np.sum(repz)*rep_norm * c
return trl
if args.outputformat == 'undecided' :
if args.outfile == sys.stdout :
outputformat = 'ascii'
else :
outputformat = 'numpy'
else :
outputformat = args.outputformat
if d==1 :
trl = trail_1d(N, r=args.r, c=args.c, b=args.b)
if outputformat == 'ascii' :
for p in trl :
print('%e' % (p), file=args.outfile)
else :
np.save(args.outfile, trl)
elif d==3 :
trl = trail_3d(N, r=args.r, c=args.c, b=args.b)
if outputformat == 'ascii' :
for p in trl :
print('%e %e %e' % (p[0], p[1], p[2]), file=args.outfile)
else :
np.save(args.outfile, trl)
else :
print('illegal dimension given: %d' %(d)) | type=int, default=0,
help='repository size (default: 0)')
parser.add_argument('-c',
type=float, default=0.0, | random_line_split |
trail_maker.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Mehmet Atakan Gürkan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program (probably in a file named COPYING).
# If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function, division
import numpy as np
from numpy.random import random, seed
import argparse, sys
parser = argparse.ArgumentParser(description='Creates a random walk trail')
parser.add_argument('-d',
type=int, default=3,
help='topological dimension of the trail (default: 3)')
parser.add_argument('-N',
type=int, default=1000,
help='number of steps in the trail (default: 1000)')
parser.add_argument('-i',
type=float, default=1.0,
help='size of increments (will get normalized by 1/sqrt(N))')
parser.add_argument('-r',
type=int, default=0,
help='repository size (default: 0)')
parser.add_argument('-c',
type=float, default=0.0,
help='bias strength')
parser.add_argument('-b',
type=float, default=3.0e40,
help='radius of boundary')
parser.add_argument('-s',
type=int, default=42,
help='random number seed (default: 42)')
parser.add_argument('--rangen',
type=int, default=-1,
help='generate this many random numbers before starting to build the trail (default: repo size; ignored if less than repo size)')
parser.add_argument('-P0',
type=float, default=0.0, dest='P0',
help='initial value (for 1D)')
parser.add_argument('-P0x',
type=float, default=0.0, dest='P0x',
help='initial value of x component (for 3D)')
parser.add_argument('-P0y',
type=float, default=0.0, dest='P0y',
help='initial value of y component (for 3D)')
parser.add_argument('-P0z',
type=float, default=0.0, dest='P0z',
help='initial value of z component (for 3D)')
parser.add_argument('-o','--output-file',
dest='outfile',
type=argparse.FileType('w'),
default=sys.stdout,
help='output filename (if not given, use stdout)')
parser.add_argument('--numpy', dest='outputformat', action='store_const',
const='numpy', default='undecided',
help='output in NumPy format (default: ASCII for stdout, NumPy for file')
parser.add_argument('--ascii', dest='outputformat', action='store_const',
const='ascii', default='undecided',
help='output in ASCII format (default: ASCII for stdout, NumPy for file')
args = parser.parse_args()
seed(args.s)
if args.rangen > args.r :
dummy = random(args.rangen - args.r)
N = args.N
d = args.d
b = args.b
dP = args.i/np.sqrt(N)
def trail_1d(N, r=0, c=0.0, b=3.0e40) :
P0 = args.P0
P = P0
trl = np.empty(N+1)
trl[0] = P0
if r>0 and c!=0.0 : # repository initialization
use_rep = True
rep_norm = 1.0/np.sqrt(r)
rep = random(r)-0.5
q = np.sum(rep)*rep_norm * c
else :
use_rep = False
dummy = random(r)
q = 0.0
for i in range(N) :
X = random() - 0.5
if X>q : DP = -dP
else : DP = dP
if np.fabs(P+DP) > b :
P -= DP
else :
P += DP
trl[i+1] = P
if use_rep :
rep[i%r] = X
q = -1.0*np.sum(rep)*rep_norm * c
return trl
def trail_3d(N, r=0, c=0.0, b=3.0e40) :
d |
if args.outputformat == 'undecided' :
if args.outfile == sys.stdout :
outputformat = 'ascii'
else :
outputformat = 'numpy'
else :
outputformat = args.outputformat
if d==1 :
trl = trail_1d(N, r=args.r, c=args.c, b=args.b)
if outputformat == 'ascii' :
for p in trl :
print('%e' % (p), file=args.outfile)
else :
np.save(args.outfile, trl)
elif d==3 :
trl = trail_3d(N, r=args.r, c=args.c, b=args.b)
if outputformat == 'ascii' :
for p in trl :
print('%e %e %e' % (p[0], p[1], p[2]), file=args.outfile)
else :
np.save(args.outfile, trl)
else :
print('illegal dimension given: %d' %(d))
| ef vec_norm2(a) :
return a[0]*a[0] + a[1]*a[1] + a[2]*a[2]
b2 = b*b
P0x, P0y, P0z = args.P0x, args.P0y, args.P0z
Px, Py, Pz = P0x, P0y, P0z
trl = np.empty((N+1,3))
trl[0] = P0x, P0y, P0z
if r>0 and c!=0.0 : # repository initialization
use_rep = True
rep_norm = 1.0/np.sqrt(r)
repx, repy, repz = random(r)-0.5, random(r)-0.5, random(r)-0.5
qx = np.sum(repx)*rep_norm * c
qy = np.sum(repy)*rep_norm * c
qz = np.sum(repz)*rep_norm * c
else :
use_rep = False
dummy = random(r*3)
qx, qy, qz = 0.0, 0.0, 0.0
for i in range(N) :
Xx = random() - 0.5
Xy = random() - 0.5
Xz = random() - 0.5
if Xx>qx : DPx = -dP
else : DPx = dP
if Xy>qy : DPy = -dP
else : DPy = dP
if Xz>qz : DPz = -dP
else : DPz = dP
Ptry = Px+DPx, Py+DPy, Pz+DPz
if vec_norm2(Ptry) > b2 : # we'll cross bndry if we take this step
Px -= DPx # so we take the opposite step
Py -= DPy
Pz -= DPz
else : # we are safe
Px += DPx # so we take normal step
Py += DPy
Pz += DPz
trl[i+1] = (Px, Py, Pz)
if use_rep :
repx[i%r], repy[i%r], repz[i%r]= Xx, Xy, Xz
qx = -1.0*np.sum(repx)*rep_norm * c
qy = -1.0*np.sum(repy)*rep_norm * c
qz = -1.0*np.sum(repz)*rep_norm * c
return trl
| identifier_body |
trail_maker.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Mehmet Atakan Gürkan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program (probably in a file named COPYING).
# If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function, division
import numpy as np
from numpy.random import random, seed
import argparse, sys
parser = argparse.ArgumentParser(description='Creates a random walk trail')
parser.add_argument('-d',
type=int, default=3,
help='topological dimension of the trail (default: 3)')
parser.add_argument('-N',
type=int, default=1000,
help='number of steps in the trail (default: 1000)')
parser.add_argument('-i',
type=float, default=1.0,
help='size of increments (will get normalized by 1/sqrt(N))')
parser.add_argument('-r',
type=int, default=0,
help='repository size (default: 0)')
parser.add_argument('-c',
type=float, default=0.0,
help='bias strength')
parser.add_argument('-b',
type=float, default=3.0e40,
help='radius of boundary')
parser.add_argument('-s',
type=int, default=42,
help='random number seed (default: 42)')
parser.add_argument('--rangen',
type=int, default=-1,
help='generate this many random numbers before starting to build the trail (default: repo size; ignored if less than repo size)')
parser.add_argument('-P0',
type=float, default=0.0, dest='P0',
help='initial value (for 1D)')
parser.add_argument('-P0x',
type=float, default=0.0, dest='P0x',
help='initial value of x component (for 3D)')
parser.add_argument('-P0y',
type=float, default=0.0, dest='P0y',
help='initial value of y component (for 3D)')
parser.add_argument('-P0z',
type=float, default=0.0, dest='P0z',
help='initial value of z component (for 3D)')
parser.add_argument('-o','--output-file',
dest='outfile',
type=argparse.FileType('w'),
default=sys.stdout,
help='output filename (if not given, use stdout)')
parser.add_argument('--numpy', dest='outputformat', action='store_const',
const='numpy', default='undecided',
help='output in NumPy format (default: ASCII for stdout, NumPy for file')
parser.add_argument('--ascii', dest='outputformat', action='store_const',
const='ascii', default='undecided',
help='output in ASCII format (default: ASCII for stdout, NumPy for file')
args = parser.parse_args()
seed(args.s)
if args.rangen > args.r :
dummy = random(args.rangen - args.r)
N = args.N
d = args.d
b = args.b
dP = args.i/np.sqrt(N)
def trail_1d(N, r=0, c=0.0, b=3.0e40) :
P0 = args.P0
P = P0
trl = np.empty(N+1)
trl[0] = P0
if r>0 and c!=0.0 : # repository initialization
use_rep = True
rep_norm = 1.0/np.sqrt(r)
rep = random(r)-0.5
q = np.sum(rep)*rep_norm * c
else :
use_rep = False
dummy = random(r)
q = 0.0
for i in range(N) :
X = random() - 0.5
if X>q : DP = -dP
else : DP = dP
if np.fabs(P+DP) > b :
P -= DP
else :
P += DP
trl[i+1] = P
if use_rep :
rep[i%r] = X
q = -1.0*np.sum(rep)*rep_norm * c
return trl
def t | N, r=0, c=0.0, b=3.0e40) :
def vec_norm2(a) :
return a[0]*a[0] + a[1]*a[1] + a[2]*a[2]
b2 = b*b
P0x, P0y, P0z = args.P0x, args.P0y, args.P0z
Px, Py, Pz = P0x, P0y, P0z
trl = np.empty((N+1,3))
trl[0] = P0x, P0y, P0z
if r>0 and c!=0.0 : # repository initialization
use_rep = True
rep_norm = 1.0/np.sqrt(r)
repx, repy, repz = random(r)-0.5, random(r)-0.5, random(r)-0.5
qx = np.sum(repx)*rep_norm * c
qy = np.sum(repy)*rep_norm * c
qz = np.sum(repz)*rep_norm * c
else :
use_rep = False
dummy = random(r*3)
qx, qy, qz = 0.0, 0.0, 0.0
for i in range(N) :
Xx = random() - 0.5
Xy = random() - 0.5
Xz = random() - 0.5
if Xx>qx : DPx = -dP
else : DPx = dP
if Xy>qy : DPy = -dP
else : DPy = dP
if Xz>qz : DPz = -dP
else : DPz = dP
Ptry = Px+DPx, Py+DPy, Pz+DPz
if vec_norm2(Ptry) > b2 : # we'll cross bndry if we take this step
Px -= DPx # so we take the opposite step
Py -= DPy
Pz -= DPz
else : # we are safe
Px += DPx # so we take normal step
Py += DPy
Pz += DPz
trl[i+1] = (Px, Py, Pz)
if use_rep :
repx[i%r], repy[i%r], repz[i%r]= Xx, Xy, Xz
qx = -1.0*np.sum(repx)*rep_norm * c
qy = -1.0*np.sum(repy)*rep_norm * c
qz = -1.0*np.sum(repz)*rep_norm * c
return trl
if args.outputformat == 'undecided' :
if args.outfile == sys.stdout :
outputformat = 'ascii'
else :
outputformat = 'numpy'
else :
outputformat = args.outputformat
if d==1 :
trl = trail_1d(N, r=args.r, c=args.c, b=args.b)
if outputformat == 'ascii' :
for p in trl :
print('%e' % (p), file=args.outfile)
else :
np.save(args.outfile, trl)
elif d==3 :
trl = trail_3d(N, r=args.r, c=args.c, b=args.b)
if outputformat == 'ascii' :
for p in trl :
print('%e %e %e' % (p[0], p[1], p[2]), file=args.outfile)
else :
np.save(args.outfile, trl)
else :
print('illegal dimension given: %d' %(d))
| rail_3d( | identifier_name |
models.py | from django.db import models
from django.contrib.auth.models import User
from helper_functions import my_strftime
# Create your models here.
#This only contains metadata about this thread (i.e. just the subject for now)
#It is used in a Many-to-Many relationship with User, with a through object that contains the has_been_read flag
class Thread(models.Model):
subject = models.CharField(max_length=64)
def getThread(self):
"""Returns list of most recent messages with corresponding info"""
return [message.getDetail() for message in self.message_set.order_by('time_sent')]
def getThreadInfo(self, user=None):
"""
Returns dictionary object containing basic info about thread,
such as most recent message/author, title, etc.
"""
if user == None:
has_been_read = False
else:
|
last_message = self.message_set.order_by('-time_sent')[0]
return { 'subject' : self.subject, 'last_message' : last_message.getDetail(), 'id' : self.id,
'has_been_read' : has_been_read }
class Message(models.Model):
thread = models.ForeignKey(Thread)
user = models.ForeignKey('userInfo.UserProfile') #the author of this message
time_sent = models.DateTimeField(auto_now_add=True)
text = models.TextField()
def getDetail(self):
"""Returns dictionary object containing the info of this object"""
return { 'author' : self.user.getInfo(),
'timestamp' : my_strftime(self.time_sent),
'text' : self.text }
class ThreadMembership(models.Model):
user = models.ForeignKey('userInfo.UserProfile')
thread = models.ForeignKey(Thread)
#Meta data for user's relation to thread
has_been_read = models.BooleanField(default=False)
| has_been_read = ThreadMembership.objects.get(user=user, thread=self).has_been_read | conditional_block |
models.py | from django.db import models
from django.contrib.auth.models import User
from helper_functions import my_strftime
# Create your models here.
#This only contains metadata about this thread (i.e. just the subject for now)
#It is used in a Many-to-Many relationship with User, with a through object that contains the has_been_read flag
class Thread(models.Model):
subject = models.CharField(max_length=64)
def getThread(self):
"""Returns list of most recent messages with corresponding info"""
return [message.getDetail() for message in self.message_set.order_by('time_sent')]
def getThreadInfo(self, user=None):
"""
Returns dictionary object containing basic info about thread,
such as most recent message/author, title, etc.
"""
if user == None:
has_been_read = False
else:
has_been_read = ThreadMembership.objects.get(user=user, thread=self).has_been_read
last_message = self.message_set.order_by('-time_sent')[0]
return { 'subject' : self.subject, 'last_message' : last_message.getDetail(), 'id' : self.id,
'has_been_read' : has_been_read }
class Message(models.Model): | text = models.TextField()
def getDetail(self):
"""Returns dictionary object containing the info of this object"""
return { 'author' : self.user.getInfo(),
'timestamp' : my_strftime(self.time_sent),
'text' : self.text }
class ThreadMembership(models.Model):
user = models.ForeignKey('userInfo.UserProfile')
thread = models.ForeignKey(Thread)
#Meta data for user's relation to thread
has_been_read = models.BooleanField(default=False) | thread = models.ForeignKey(Thread)
user = models.ForeignKey('userInfo.UserProfile') #the author of this message
time_sent = models.DateTimeField(auto_now_add=True) | random_line_split |
models.py | from django.db import models
from django.contrib.auth.models import User
from helper_functions import my_strftime
# Create your models here.
#This only contains metadata about this thread (i.e. just the subject for now)
#It is used in a Many-to-Many relationship with User, with a through object that contains the has_been_read flag
class Thread(models.Model):
subject = models.CharField(max_length=64)
def getThread(self):
"""Returns list of most recent messages with corresponding info"""
return [message.getDetail() for message in self.message_set.order_by('time_sent')]
def getThreadInfo(self, user=None):
"""
Returns dictionary object containing basic info about thread,
such as most recent message/author, title, etc.
"""
if user == None:
has_been_read = False
else:
has_been_read = ThreadMembership.objects.get(user=user, thread=self).has_been_read
last_message = self.message_set.order_by('-time_sent')[0]
return { 'subject' : self.subject, 'last_message' : last_message.getDetail(), 'id' : self.id,
'has_been_read' : has_been_read }
class Message(models.Model):
thread = models.ForeignKey(Thread)
user = models.ForeignKey('userInfo.UserProfile') #the author of this message
time_sent = models.DateTimeField(auto_now_add=True)
text = models.TextField()
def | (self):
"""Returns dictionary object containing the info of this object"""
return { 'author' : self.user.getInfo(),
'timestamp' : my_strftime(self.time_sent),
'text' : self.text }
class ThreadMembership(models.Model):
user = models.ForeignKey('userInfo.UserProfile')
thread = models.ForeignKey(Thread)
#Meta data for user's relation to thread
has_been_read = models.BooleanField(default=False)
| getDetail | identifier_name |
models.py | from django.db import models
from django.contrib.auth.models import User
from helper_functions import my_strftime
# Create your models here.
#This only contains metadata about this thread (i.e. just the subject for now)
#It is used in a Many-to-Many relationship with User, with a through object that contains the has_been_read flag
class Thread(models.Model):
subject = models.CharField(max_length=64)
def getThread(self):
"""Returns list of most recent messages with corresponding info"""
return [message.getDetail() for message in self.message_set.order_by('time_sent')]
def getThreadInfo(self, user=None):
"""
Returns dictionary object containing basic info about thread,
such as most recent message/author, title, etc.
"""
if user == None:
has_been_read = False
else:
has_been_read = ThreadMembership.objects.get(user=user, thread=self).has_been_read
last_message = self.message_set.order_by('-time_sent')[0]
return { 'subject' : self.subject, 'last_message' : last_message.getDetail(), 'id' : self.id,
'has_been_read' : has_been_read }
class Message(models.Model):
thread = models.ForeignKey(Thread)
user = models.ForeignKey('userInfo.UserProfile') #the author of this message
time_sent = models.DateTimeField(auto_now_add=True)
text = models.TextField()
def getDetail(self):
|
class ThreadMembership(models.Model):
user = models.ForeignKey('userInfo.UserProfile')
thread = models.ForeignKey(Thread)
#Meta data for user's relation to thread
has_been_read = models.BooleanField(default=False)
| """Returns dictionary object containing the info of this object"""
return { 'author' : self.user.getInfo(),
'timestamp' : my_strftime(self.time_sent),
'text' : self.text } | identifier_body |
model.py | """
model.py
by Ted Morin
contains a function to predict 10-year Atrial Fibrilation risks using beta coefficients from
10.1016:S0140-6736(09)60443-8
2010 Development of a Risk Score for Atrial Fibrillation in the Community
Framingham Heart Study
translated and optimized from FHS online risk calculator's javascript
function expects parameters of
"Male Sex" "Age" "BMI" "Systolic BP" "Antihypertensive Medication Use" "PR Interval" "Sig. Murmur" "Prev Heart Fail"
years kg/m^2 mm Hg mSec
bool int/float int/float int/float bool int/float bool bool
"""
"""
# originally part of the function, calculates xbar_value
xbar_values = np.array([
0.4464, # gender
60.9022, # age
26.2861, # bmi
136.1674, # sbp
0.2413, # hrx
16.3901, # pr_intv
0.0281, # vhd
0.0087, # hxchf
3806.9000, # age2
1654.6600, # gender_age2
1.8961, # age_vhd
0.6100 # age_hxchf
])
xbar_value = np.dot(xbar_values,betas) # this constant should be hard coded like s0!
# (and now it is)
"""
def model(ismale, age, bmi, sbp, antihyp, pr_intv, sigmurm, phf):
# convert seconds to milliseconds as used in regression
| pr_intv = pr_intv * 1000.0
# inexplicable conversion
pr_intv = pr_intv / 10.0
# this was done in the js, and the output seems much more realistic than otherwise, but it seems inexplicable!
# perhaps the coefficient shown in FHS's website is erroneous? Or uses the wrong units? It is hard to say.
import numpy as np
# betas
betas = np.array([
1.994060, #gender
0.150520, #age
0.019300, #bmi Body Mass Index
0.00615, #sbp Systolic Blood Pressure
0.424100, #hrx Treatment for hypertension
0.070650, #pr_intv PR interval
3.795860, #vhd Significant Murmur
9.428330, #hxchf Prevalent Heart Failure
-0.000380, #age2 age squared
-0.000280, #gender_age2 male gender times age squared
-0.042380, #age_vhd age times murmur
-0.123070 #age_hxchf age times prevalent heart failure
])
s0 = 0.96337 # "const is from the spreadsheet"
xbar_value = 10.785528582
values = [ismale, age, bmi, sbp, antihyp, pr_intv, sigmurm, phf]
# calculate derived values
values.append(age*age) # age squared
values.append(ismale*age*age) # gender times age squared
values.append(sigmurm*age) # age times significant murmur
values.append(phf*age)
values = np.array(values)
# dot product
value = np.dot(values, betas)
# calculate using cox regression model
risk = 1.0 - np.power(s0, np.exp(value - xbar_value));
# cap at .3
#if (risk > .3) : risk = .3 # is this justified by the paper?
return risk | identifier_body | |
model.py | """
model.py
by Ted Morin
contains a function to predict 10-year Atrial Fibrilation risks using beta coefficients from
10.1016:S0140-6736(09)60443-8
2010 Development of a Risk Score for Atrial Fibrillation in the Community
Framingham Heart Study
translated and optimized from FHS online risk calculator's javascript
function expects parameters of
"Male Sex" "Age" "BMI" "Systolic BP" "Antihypertensive Medication Use" "PR Interval" "Sig. Murmur" "Prev Heart Fail"
years kg/m^2 mm Hg mSec
bool int/float int/float int/float bool int/float bool bool
"""
"""
# originally part of the function, calculates xbar_value
xbar_values = np.array([
0.4464, # gender
60.9022, # age
26.2861, # bmi
136.1674, # sbp
0.2413, # hrx
16.3901, # pr_intv
0.0281, # vhd
0.0087, # hxchf
3806.9000, # age2
1654.6600, # gender_age2
1.8961, # age_vhd
0.6100 # age_hxchf
])
xbar_value = np.dot(xbar_values,betas) # this constant should be hard coded like s0!
# (and now it is)
"""
| def model(ismale, age, bmi, sbp, antihyp, pr_intv, sigmurm, phf):
# convert seconds to milliseconds as used in regression
pr_intv = pr_intv * 1000.0
# inexplicable conversion
pr_intv = pr_intv / 10.0
# this was done in the js, and the output seems much more realistic than otherwise, but it seems inexplicable!
# perhaps the coefficient shown in FHS's website is erroneous? Or uses the wrong units? It is hard to say.
import numpy as np
# betas
betas = np.array([
1.994060, #gender
0.150520, #age
0.019300, #bmi Body Mass Index
0.00615, #sbp Systolic Blood Pressure
0.424100, #hrx Treatment for hypertension
0.070650, #pr_intv PR interval
3.795860, #vhd Significant Murmur
9.428330, #hxchf Prevalent Heart Failure
-0.000380, #age2 age squared
-0.000280, #gender_age2 male gender times age squared
-0.042380, #age_vhd age times murmur
-0.123070 #age_hxchf age times prevalent heart failure
])
s0 = 0.96337 # "const is from the spreadsheet"
xbar_value = 10.785528582
values = [ismale, age, bmi, sbp, antihyp, pr_intv, sigmurm, phf]
# calculate derived values
values.append(age*age) # age squared
values.append(ismale*age*age) # gender times age squared
values.append(sigmurm*age) # age times significant murmur
values.append(phf*age)
values = np.array(values)
# dot product
value = np.dot(values, betas)
# calculate using cox regression model
risk = 1.0 - np.power(s0, np.exp(value - xbar_value));
# cap at .3
#if (risk > .3) : risk = .3 # is this justified by the paper?
return risk | random_line_split | |
model.py | """
model.py
by Ted Morin
contains a function to predict 10-year Atrial Fibrilation risks using beta coefficients from
10.1016:S0140-6736(09)60443-8
2010 Development of a Risk Score for Atrial Fibrillation in the Community
Framingham Heart Study
translated and optimized from FHS online risk calculator's javascript
function expects parameters of
"Male Sex" "Age" "BMI" "Systolic BP" "Antihypertensive Medication Use" "PR Interval" "Sig. Murmur" "Prev Heart Fail"
years kg/m^2 mm Hg mSec
bool int/float int/float int/float bool int/float bool bool
"""
"""
# originally part of the function, calculates xbar_value
xbar_values = np.array([
0.4464, # gender
60.9022, # age
26.2861, # bmi
136.1674, # sbp
0.2413, # hrx
16.3901, # pr_intv
0.0281, # vhd
0.0087, # hxchf
3806.9000, # age2
1654.6600, # gender_age2
1.8961, # age_vhd
0.6100 # age_hxchf
])
xbar_value = np.dot(xbar_values,betas) # this constant should be hard coded like s0!
# (and now it is)
"""
def | (ismale, age, bmi, sbp, antihyp, pr_intv, sigmurm, phf):
# convert seconds to milliseconds as used in regression
pr_intv = pr_intv * 1000.0
# inexplicable conversion
pr_intv = pr_intv / 10.0
# this was done in the js, and the output seems much more realistic than otherwise, but it seems inexplicable!
# perhaps the coefficient shown in FHS's website is erroneous? Or uses the wrong units? It is hard to say.
import numpy as np
# betas
betas = np.array([
1.994060, #gender
0.150520, #age
0.019300, #bmi Body Mass Index
0.00615, #sbp Systolic Blood Pressure
0.424100, #hrx Treatment for hypertension
0.070650, #pr_intv PR interval
3.795860, #vhd Significant Murmur
9.428330, #hxchf Prevalent Heart Failure
-0.000380, #age2 age squared
-0.000280, #gender_age2 male gender times age squared
-0.042380, #age_vhd age times murmur
-0.123070 #age_hxchf age times prevalent heart failure
])
s0 = 0.96337 # "const is from the spreadsheet"
xbar_value = 10.785528582
values = [ismale, age, bmi, sbp, antihyp, pr_intv, sigmurm, phf]
# calculate derived values
values.append(age*age) # age squared
values.append(ismale*age*age) # gender times age squared
values.append(sigmurm*age) # age times significant murmur
values.append(phf*age)
values = np.array(values)
# dot product
value = np.dot(values, betas)
# calculate using cox regression model
risk = 1.0 - np.power(s0, np.exp(value - xbar_value));
# cap at .3
#if (risk > .3) : risk = .3 # is this justified by the paper?
return risk
| model | identifier_name |
comm.py | import urllib2
import json
import time
import threading
import Queue
from utils import make_random_id, LOGINFO, LOGDEBUG, LOGERROR
class CommBase(object):
def __init__(self):
self.agents = []
def add_agent(self, agent):
self.agents.append(agent)
class HTTPComm(CommBase):
def __init__(self, config, url = 'http://localhost:8080/messages'):
super(HTTPComm, self).__init__()
self.config = config
self.lastpoll = -1
self.url = url
self.own_msgids = set()
def post_message(self, content):
msgid = make_random_id()
content['msgid'] = msgid
self.own_msgids.add(msgid)
LOGDEBUG( "----- POSTING MESSAGE ----")
data = json.dumps(content)
LOGDEBUG(data)
u = urllib2.urlopen(self.url, data)
return u.read() == 'Success'
def poll_and_dispatch(self):
url = self.url
if self.lastpoll == -1:
url = url + "?from_timestamp_rel=%s" % self.config['offer_expiry_interval']
else:
url = url + '?from_serial=%s' % (self.lastpoll+1)
print (url)
u = urllib2.urlopen(url)
resp = json.loads(u.read())
for x in resp:
if int(x.get('serial',0)) > self.lastpoll: self.lastpoll = int(x.get('serial',0))
content = x.get('content',None)
if content and not content.get('msgid', '') in self.own_msgids:
|
class ThreadedComm(CommBase):
class AgentProxy(object):
def __init__(self, tc):
self.tc = tc
def dispatch_message(self, content):
self.tc.receive_queue.put(content)
def __init__(self, upstream_comm):
super(ThreadedComm, self).__init__()
self.upstream_comm = upstream_comm
self.send_queue = Queue.Queue()
self.receive_queue = Queue.Queue()
self.comm_thread = CommThread(self, upstream_comm)
upstream_comm.add_agent(self.AgentProxy(self))
def post_message(self, content):
self.send_queue.put(content)
def poll_and_dispatch(self):
while not self.receive_queue.empty():
content = self.receive_queue.get()
for a in self.agents:
a.dispatch_message(content)
def start(self):
self.comm_thread.start()
def stop(self):
self.comm_thread.stop()
self.comm_thread.join()
class CommThread(threading.Thread):
def __init__(self, threaded_comm, upstream_comm):
threading.Thread.__init__(self)
self._stop = threading.Event()
self.threaded_comm = threaded_comm
self.upstream_comm = upstream_comm
def run(self):
send_queue = self.threaded_comm.send_queue
receive_queue = self.threaded_comm.receive_queue
while not self._stop.is_set():
while not send_queue.empty():
self.upstream_comm.post_message(send_queue.get())
self.upstream_comm.poll_and_dispatch()
time.sleep(1)
def stop(self):
self._stop.set()
| for a in self.agents:
a.dispatch_message(content) | conditional_block |
comm.py | import urllib2
import json
import time
import threading
import Queue
from utils import make_random_id, LOGINFO, LOGDEBUG, LOGERROR
class | (object):
def __init__(self):
self.agents = []
def add_agent(self, agent):
self.agents.append(agent)
class HTTPComm(CommBase):
def __init__(self, config, url = 'http://localhost:8080/messages'):
super(HTTPComm, self).__init__()
self.config = config
self.lastpoll = -1
self.url = url
self.own_msgids = set()
def post_message(self, content):
msgid = make_random_id()
content['msgid'] = msgid
self.own_msgids.add(msgid)
LOGDEBUG( "----- POSTING MESSAGE ----")
data = json.dumps(content)
LOGDEBUG(data)
u = urllib2.urlopen(self.url, data)
return u.read() == 'Success'
def poll_and_dispatch(self):
url = self.url
if self.lastpoll == -1:
url = url + "?from_timestamp_rel=%s" % self.config['offer_expiry_interval']
else:
url = url + '?from_serial=%s' % (self.lastpoll+1)
print (url)
u = urllib2.urlopen(url)
resp = json.loads(u.read())
for x in resp:
if int(x.get('serial',0)) > self.lastpoll: self.lastpoll = int(x.get('serial',0))
content = x.get('content',None)
if content and not content.get('msgid', '') in self.own_msgids:
for a in self.agents:
a.dispatch_message(content)
class ThreadedComm(CommBase):
class AgentProxy(object):
def __init__(self, tc):
self.tc = tc
def dispatch_message(self, content):
self.tc.receive_queue.put(content)
def __init__(self, upstream_comm):
super(ThreadedComm, self).__init__()
self.upstream_comm = upstream_comm
self.send_queue = Queue.Queue()
self.receive_queue = Queue.Queue()
self.comm_thread = CommThread(self, upstream_comm)
upstream_comm.add_agent(self.AgentProxy(self))
def post_message(self, content):
self.send_queue.put(content)
def poll_and_dispatch(self):
while not self.receive_queue.empty():
content = self.receive_queue.get()
for a in self.agents:
a.dispatch_message(content)
def start(self):
self.comm_thread.start()
def stop(self):
self.comm_thread.stop()
self.comm_thread.join()
class CommThread(threading.Thread):
def __init__(self, threaded_comm, upstream_comm):
threading.Thread.__init__(self)
self._stop = threading.Event()
self.threaded_comm = threaded_comm
self.upstream_comm = upstream_comm
def run(self):
send_queue = self.threaded_comm.send_queue
receive_queue = self.threaded_comm.receive_queue
while not self._stop.is_set():
while not send_queue.empty():
self.upstream_comm.post_message(send_queue.get())
self.upstream_comm.poll_and_dispatch()
time.sleep(1)
def stop(self):
self._stop.set()
| CommBase | identifier_name |
comm.py | import urllib2
import json
import time
import threading
import Queue
from utils import make_random_id, LOGINFO, LOGDEBUG, LOGERROR
class CommBase(object):
def __init__(self):
self.agents = []
def add_agent(self, agent):
self.agents.append(agent)
class HTTPComm(CommBase):
def __init__(self, config, url = 'http://localhost:8080/messages'):
super(HTTPComm, self).__init__()
self.config = config
self.lastpoll = -1
self.url = url
self.own_msgids = set()
def post_message(self, content):
msgid = make_random_id()
content['msgid'] = msgid
self.own_msgids.add(msgid)
LOGDEBUG( "----- POSTING MESSAGE ----")
data = json.dumps(content)
LOGDEBUG(data)
u = urllib2.urlopen(self.url, data)
return u.read() == 'Success'
def poll_and_dispatch(self):
url = self.url
if self.lastpoll == -1:
url = url + "?from_timestamp_rel=%s" % self.config['offer_expiry_interval']
else:
url = url + '?from_serial=%s' % (self.lastpoll+1)
print (url)
u = urllib2.urlopen(url)
resp = json.loads(u.read())
for x in resp:
if int(x.get('serial',0)) > self.lastpoll: self.lastpoll = int(x.get('serial',0))
content = x.get('content',None)
if content and not content.get('msgid', '') in self.own_msgids:
for a in self.agents:
a.dispatch_message(content)
class ThreadedComm(CommBase):
class AgentProxy(object):
def __init__(self, tc):
self.tc = tc
def dispatch_message(self, content):
self.tc.receive_queue.put(content)
def __init__(self, upstream_comm):
super(ThreadedComm, self).__init__()
self.upstream_comm = upstream_comm
self.send_queue = Queue.Queue()
self.receive_queue = Queue.Queue()
self.comm_thread = CommThread(self, upstream_comm)
upstream_comm.add_agent(self.AgentProxy(self))
def post_message(self, content):
self.send_queue.put(content)
def poll_and_dispatch(self):
while not self.receive_queue.empty():
content = self.receive_queue.get()
for a in self.agents:
a.dispatch_message(content)
def start(self):
self.comm_thread.start()
def stop(self):
self.comm_thread.stop()
self.comm_thread.join() |
class CommThread(threading.Thread):
def __init__(self, threaded_comm, upstream_comm):
threading.Thread.__init__(self)
self._stop = threading.Event()
self.threaded_comm = threaded_comm
self.upstream_comm = upstream_comm
def run(self):
send_queue = self.threaded_comm.send_queue
receive_queue = self.threaded_comm.receive_queue
while not self._stop.is_set():
while not send_queue.empty():
self.upstream_comm.post_message(send_queue.get())
self.upstream_comm.poll_and_dispatch()
time.sleep(1)
def stop(self):
self._stop.set() | random_line_split | |
comm.py | import urllib2
import json
import time
import threading
import Queue
from utils import make_random_id, LOGINFO, LOGDEBUG, LOGERROR
class CommBase(object):
def __init__(self):
self.agents = []
def add_agent(self, agent):
self.agents.append(agent)
class HTTPComm(CommBase):
def __init__(self, config, url = 'http://localhost:8080/messages'):
super(HTTPComm, self).__init__()
self.config = config
self.lastpoll = -1
self.url = url
self.own_msgids = set()
def post_message(self, content):
msgid = make_random_id()
content['msgid'] = msgid
self.own_msgids.add(msgid)
LOGDEBUG( "----- POSTING MESSAGE ----")
data = json.dumps(content)
LOGDEBUG(data)
u = urllib2.urlopen(self.url, data)
return u.read() == 'Success'
def poll_and_dispatch(self):
url = self.url
if self.lastpoll == -1:
url = url + "?from_timestamp_rel=%s" % self.config['offer_expiry_interval']
else:
url = url + '?from_serial=%s' % (self.lastpoll+1)
print (url)
u = urllib2.urlopen(url)
resp = json.loads(u.read())
for x in resp:
if int(x.get('serial',0)) > self.lastpoll: self.lastpoll = int(x.get('serial',0))
content = x.get('content',None)
if content and not content.get('msgid', '') in self.own_msgids:
for a in self.agents:
a.dispatch_message(content)
class ThreadedComm(CommBase):
class AgentProxy(object):
def __init__(self, tc):
self.tc = tc
def dispatch_message(self, content):
self.tc.receive_queue.put(content)
def __init__(self, upstream_comm):
|
def post_message(self, content):
self.send_queue.put(content)
def poll_and_dispatch(self):
while not self.receive_queue.empty():
content = self.receive_queue.get()
for a in self.agents:
a.dispatch_message(content)
def start(self):
self.comm_thread.start()
def stop(self):
self.comm_thread.stop()
self.comm_thread.join()
class CommThread(threading.Thread):
def __init__(self, threaded_comm, upstream_comm):
threading.Thread.__init__(self)
self._stop = threading.Event()
self.threaded_comm = threaded_comm
self.upstream_comm = upstream_comm
def run(self):
send_queue = self.threaded_comm.send_queue
receive_queue = self.threaded_comm.receive_queue
while not self._stop.is_set():
while not send_queue.empty():
self.upstream_comm.post_message(send_queue.get())
self.upstream_comm.poll_and_dispatch()
time.sleep(1)
def stop(self):
self._stop.set()
| super(ThreadedComm, self).__init__()
self.upstream_comm = upstream_comm
self.send_queue = Queue.Queue()
self.receive_queue = Queue.Queue()
self.comm_thread = CommThread(self, upstream_comm)
upstream_comm.add_agent(self.AgentProxy(self)) | identifier_body |
cite_tool.js | var Substance = require('substance');
var Tool = Substance.Surface.Tool;
var _ = require("substance/helpers");
var CiteTool = Tool.extend({
name: "cite",
update: function(surface, sel) {
this.surface = surface; // IMPORTANT!
// Set disabled when not a property selection
if (!surface.isEnabled() || sel.isNull() || !sel.isPropertySelection()) {
return this.setDisabled();
}
var newState = {
surface: surface,
sel: sel,
disabled: false
};
this.setToolState(newState);
},
// Needs app context in order to request a state switch
createCitation: function(citationTargetType) {
var citation;
var doc = this.context.doc;
var citationType = doc.getSchema().getNodeClass(citationTargetType).static.citationType;
var surface = this.surface;
var editor = surface.getEditor();
console.log('citationType', citationType);
surface.transaction(function(tx, args) {
var selection = args.selection;
var path = selection.start.path;
var startOffset = selection.start.offset;
if (!selection.isCollapsed) {
var out = editor.delete(tx, args);
args.selection = out.selection;
}
args.text = '$';
editor.insertText(tx, args);
citation = tx.create({
id: Substance.uuid(citationType),
"type": citationType,
"targets": [],
"path": path,
"startOffset": startOffset,
"endOffset": startOffset + 1,
});
citation.label = "???";
args.selection = citation.getSelection();
return args;
});
return citation;
},
toggleTarget: function(citationId, targetId) {
var doc = this.context.doc;
var citation = doc.get(citationId);
var newTargets = citation.targets.slice();
if (_.includes(newTargets, targetId)) {
newTargets = _.without(newTargets, targetId);
} else |
this.surface.transaction(function(tx, args) {
tx.set([citation.id, "targets"], newTargets);
return args;
});
}
});
module.exports = CiteTool;
| {
newTargets.push(targetId);
} | conditional_block |
cite_tool.js | var Substance = require('substance');
var Tool = Substance.Surface.Tool;
var _ = require("substance/helpers");
var CiteTool = Tool.extend({
name: "cite",
update: function(surface, sel) {
this.surface = surface; // IMPORTANT!
// Set disabled when not a property selection
if (!surface.isEnabled() || sel.isNull() || !sel.isPropertySelection()) {
return this.setDisabled(); | }
var newState = {
surface: surface,
sel: sel,
disabled: false
};
this.setToolState(newState);
},
// Needs app context in order to request a state switch
createCitation: function(citationTargetType) {
var citation;
var doc = this.context.doc;
var citationType = doc.getSchema().getNodeClass(citationTargetType).static.citationType;
var surface = this.surface;
var editor = surface.getEditor();
console.log('citationType', citationType);
surface.transaction(function(tx, args) {
var selection = args.selection;
var path = selection.start.path;
var startOffset = selection.start.offset;
if (!selection.isCollapsed) {
var out = editor.delete(tx, args);
args.selection = out.selection;
}
args.text = '$';
editor.insertText(tx, args);
citation = tx.create({
id: Substance.uuid(citationType),
"type": citationType,
"targets": [],
"path": path,
"startOffset": startOffset,
"endOffset": startOffset + 1,
});
citation.label = "???";
args.selection = citation.getSelection();
return args;
});
return citation;
},
toggleTarget: function(citationId, targetId) {
var doc = this.context.doc;
var citation = doc.get(citationId);
var newTargets = citation.targets.slice();
if (_.includes(newTargets, targetId)) {
newTargets = _.without(newTargets, targetId);
} else {
newTargets.push(targetId);
}
this.surface.transaction(function(tx, args) {
tx.set([citation.id, "targets"], newTargets);
return args;
});
}
});
module.exports = CiteTool; | random_line_split | |
form.directive.js | /*
* Copyright (C) 2015 Telosys-tools-saas project org. ( http://telosys-tools-saas.github.io/ )
*
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3.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.gnu.org/licenses/lgpl.html
*
* 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.
*/
/* globals $ */
'use strict';
angular.module('telosys-tools-saasApp')
.directive('showValidation', function() {
return {
restrict: 'A',
require: 'form',
link: function (scope, element) {
element.find('.form-group').each(function() {
var $formGroup = $(this);
var $inputs = $formGroup.find('input[ng-model],textarea[ng-model],select[ng-model]');
if ($inputs.length > 0) {
$inputs.each(function() {
var $input = $(this);
scope.$watch(function() {
return $input.hasClass('ng-invalid') && $input.hasClass('ng-dirty');
}, function(isInvalid) {
$formGroup.toggleClass('has-error', isInvalid);
});
});
} | }
};
}); | }); | random_line_split |
form.directive.js | /*
* Copyright (C) 2015 Telosys-tools-saas project org. ( http://telosys-tools-saas.github.io/ )
*
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3.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.gnu.org/licenses/lgpl.html
*
* 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.
*/
/* globals $ */
'use strict';
angular.module('telosys-tools-saasApp')
.directive('showValidation', function() {
return {
restrict: 'A',
require: 'form',
link: function (scope, element) {
element.find('.form-group').each(function() {
var $formGroup = $(this);
var $inputs = $formGroup.find('input[ng-model],textarea[ng-model],select[ng-model]');
if ($inputs.length > 0) |
});
}
};
}); | {
$inputs.each(function() {
var $input = $(this);
scope.$watch(function() {
return $input.hasClass('ng-invalid') && $input.hasClass('ng-dirty');
}, function(isInvalid) {
$formGroup.toggleClass('has-error', isInvalid);
});
});
} | conditional_block |
Dot.js | var React = require('react-native');
var {
StyleSheet,
View,
Animated,
} = React;
var Dot = React.createClass({
propTypes: {
isPlacedCorrectly: React.PropTypes.bool.isRequired,
},
getInitialState: function() {
return {
scale: new Animated.Value(this.props.isPlacedCorrectly ? 1 : 0.1),
visible: this.props.isPlacedCorrectly,
};
},
componentWillReceiveProps: function(nextProps) {
if (!this.props.isPlacedCorrectly && nextProps.isPlacedCorrectly) {
this.animateShow();
} else if (this.props.isPlacedCorrectly && !nextProps.isPlacedCorrectly) {
this.animateHide();
}
},
animateShow: function() {
this.setState({visible: true}, () => {
Animated.timing(this.state.scale, {
toValue: 1,
duration: 100,
}).start();
});
},
animateHide: function() {
Animated.timing(this.state.scale, {
toValue: 0.1,
duration: 100,
}).start(() => this.setState({visible: false}));
}, | return (
<Animated.View style={[styles.dot, {transform: [{scale: this.state.scale}]}]}/>
);
},
});
var styles = StyleSheet.create({
dot: {
backgroundColor: '#FF3366',
width: 6,
height: 6,
borderRadius: 3,
margin: 3,
},
});
module.exports = Dot; |
render: function() {
if (!this.state.visible) {
return null;
} | random_line_split |
debug.py | # -*- coding: utf-8 -*-
## Copyright 2015 Rasmus Scholer Sorensen, rasmusscholer@gmail.com
##
## This file is part of Nascent.
##
## Nascent is free software: you can redistribute it and/or modify
## it under the terms of the GNU Affero General Public License as
## published by the Free Software Foundation, either version 3 of the
## License, or (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU Affero General Public License for more details.
##
## You should have received a copy of the GNU Affero General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
#pylint: disable=C0103,C0111,W0613
from __future__ import absolute_import, print_function, division
from pprint import pprint
do_print = False
def print_debug(*args, **kwargs):
""" Change module-level do_print variable to toggle behaviour. """
if 'origin' in kwargs:
del kwargs['origin']
if do_print:
print(*args, **kwargs)
def pprint_debug(*args, **kwargs):
if do_print:
pprint(*args, **kwargs)
def | (*args, **kwargs):
""" Will print the file and line before printing. Can be used to find spurrious print statements. """
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe().f_back)
print(frameinfo.filename, frameinfo.lineno)
pprint(*args, **kwargs)
def info_pprint(*args, **kwargs):
""" Will print the file and line before printing the variable. """
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe().f_back)
print(frameinfo.filename, frameinfo.lineno)
pprint(*args, **kwargs)
pprintd = pprint_debug
printd = print_debug
| info_print | identifier_name |
debug.py | # -*- coding: utf-8 -*-
## Copyright 2015 Rasmus Scholer Sorensen, rasmusscholer@gmail.com
##
## This file is part of Nascent.
##
## Nascent is free software: you can redistribute it and/or modify
## it under the terms of the GNU Affero General Public License as
## published by the Free Software Foundation, either version 3 of the
## License, or (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU Affero General Public License for more details.
##
## You should have received a copy of the GNU Affero General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
#pylint: disable=C0103,C0111,W0613
from __future__ import absolute_import, print_function, division
from pprint import pprint
do_print = False
def print_debug(*args, **kwargs):
|
def pprint_debug(*args, **kwargs):
if do_print:
pprint(*args, **kwargs)
def info_print(*args, **kwargs):
""" Will print the file and line before printing. Can be used to find spurrious print statements. """
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe().f_back)
print(frameinfo.filename, frameinfo.lineno)
pprint(*args, **kwargs)
def info_pprint(*args, **kwargs):
""" Will print the file and line before printing the variable. """
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe().f_back)
print(frameinfo.filename, frameinfo.lineno)
pprint(*args, **kwargs)
pprintd = pprint_debug
printd = print_debug
| """ Change module-level do_print variable to toggle behaviour. """
if 'origin' in kwargs:
del kwargs['origin']
if do_print:
print(*args, **kwargs) | identifier_body |
debug.py | # -*- coding: utf-8 -*-
## Copyright 2015 Rasmus Scholer Sorensen, rasmusscholer@gmail.com
##
## This file is part of Nascent.
##
## Nascent is free software: you can redistribute it and/or modify
## it under the terms of the GNU Affero General Public License as
## published by the Free Software Foundation, either version 3 of the
## License, or (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU Affero General Public License for more details.
##
## You should have received a copy of the GNU Affero General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
#pylint: disable=C0103,C0111,W0613
from __future__ import absolute_import, print_function, division
from pprint import pprint
do_print = False
def print_debug(*args, **kwargs):
""" Change module-level do_print variable to toggle behaviour. """
if 'origin' in kwargs:
del kwargs['origin']
if do_print:
|
def pprint_debug(*args, **kwargs):
if do_print:
pprint(*args, **kwargs)
def info_print(*args, **kwargs):
""" Will print the file and line before printing. Can be used to find spurrious print statements. """
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe().f_back)
print(frameinfo.filename, frameinfo.lineno)
pprint(*args, **kwargs)
def info_pprint(*args, **kwargs):
""" Will print the file and line before printing the variable. """
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe().f_back)
print(frameinfo.filename, frameinfo.lineno)
pprint(*args, **kwargs)
pprintd = pprint_debug
printd = print_debug
| print(*args, **kwargs) | conditional_block |
debug.py | # -*- coding: utf-8 -*-
## Copyright 2015 Rasmus Scholer Sorensen, rasmusscholer@gmail.com
##
## This file is part of Nascent.
##
## Nascent is free software: you can redistribute it and/or modify | ## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU Affero General Public License for more details.
##
## You should have received a copy of the GNU Affero General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
#pylint: disable=C0103,C0111,W0613
from __future__ import absolute_import, print_function, division
from pprint import pprint
do_print = False
def print_debug(*args, **kwargs):
""" Change module-level do_print variable to toggle behaviour. """
if 'origin' in kwargs:
del kwargs['origin']
if do_print:
print(*args, **kwargs)
def pprint_debug(*args, **kwargs):
if do_print:
pprint(*args, **kwargs)
def info_print(*args, **kwargs):
""" Will print the file and line before printing. Can be used to find spurrious print statements. """
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe().f_back)
print(frameinfo.filename, frameinfo.lineno)
pprint(*args, **kwargs)
def info_pprint(*args, **kwargs):
""" Will print the file and line before printing the variable. """
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe().f_back)
print(frameinfo.filename, frameinfo.lineno)
pprint(*args, **kwargs)
pprintd = pprint_debug
printd = print_debug | ## it under the terms of the GNU Affero General Public License as
## published by the Free Software Foundation, either version 3 of the
## License, or (at your option) any later version.
## | random_line_split |
proxy_only_resource.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is |
class ProxyOnlyResource(Model):
"""Azure proxy only resource. This resource is not tracked by Azure Resource
Manager.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource Name.
:vartype name: str
:param kind: Kind of resource.
:type kind: str
:ivar type: Resource type.
:vartype type: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'kind': {'key': 'kind', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(self, kind=None):
super(ProxyOnlyResource, self).__init__()
self.id = None
self.name = None
self.kind = kind
self.type = None | # regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model | random_line_split |
proxy_only_resource.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class | (Model):
"""Azure proxy only resource. This resource is not tracked by Azure Resource
Manager.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource Name.
:vartype name: str
:param kind: Kind of resource.
:type kind: str
:ivar type: Resource type.
:vartype type: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'kind': {'key': 'kind', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(self, kind=None):
super(ProxyOnlyResource, self).__init__()
self.id = None
self.name = None
self.kind = kind
self.type = None
| ProxyOnlyResource | identifier_name |
proxy_only_resource.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class ProxyOnlyResource(Model):
| """Azure proxy only resource. This resource is not tracked by Azure Resource
Manager.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource Name.
:vartype name: str
:param kind: Kind of resource.
:type kind: str
:ivar type: Resource type.
:vartype type: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'kind': {'key': 'kind', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(self, kind=None):
super(ProxyOnlyResource, self).__init__()
self.id = None
self.name = None
self.kind = kind
self.type = None | identifier_body | |
auth.guard.ts | import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { AppState } from '@genesis/$core/store/app.state';
@Injectable()
export class | implements CanActivate {
constructor(protected _router: Router,
private _appStore: AppState) {}
/**
* Checks that the user is connected and if so, permits the activation of the wanted state. If the user is not
* authenticated, he is redirected toward home page with login inputs presented.
*
* @param route current route
* @param state wanted state
* @returns {boolean} true if the user is authenticated
*/
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const canGo = this._appStore.tokens.accessToken !== undefined;
console.log('# AuthGuard :: can activate ', state.url, ' ? : ', canGo, state);
if (!canGo) {
this._router.navigate([ '/sign-in' ]);
}
return canGo;
}
}
| AuthGuard | identifier_name |
auth.guard.ts | import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { AppState } from '@genesis/$core/store/app.state';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(protected _router: Router,
private _appStore: AppState) {}
/**
* Checks that the user is connected and if so, permits the activation of the wanted state. If the user is not
* authenticated, he is redirected toward home page with login inputs presented.
*
* @param route current route
* @param state wanted state
* @returns {boolean} true if the user is authenticated
*/
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const canGo = this._appStore.tokens.accessToken !== undefined;
console.log('# AuthGuard :: can activate ', state.url, ' ? : ', canGo, state);
if (!canGo) {
this._router.navigate([ '/sign-in' ]);
} | return canGo;
}
} | random_line_split | |
auth.guard.ts | import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { AppState } from '@genesis/$core/store/app.state';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(protected _router: Router,
private _appStore: AppState) {}
/**
* Checks that the user is connected and if so, permits the activation of the wanted state. If the user is not
* authenticated, he is redirected toward home page with login inputs presented.
*
* @param route current route
* @param state wanted state
* @returns {boolean} true if the user is authenticated
*/
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const canGo = this._appStore.tokens.accessToken !== undefined;
console.log('# AuthGuard :: can activate ', state.url, ' ? : ', canGo, state);
if (!canGo) |
return canGo;
}
}
| {
this._router.navigate([ '/sign-in' ]);
} | conditional_block |
download.py | import os
from com.googlecode.fascinator.api.indexer import SearchRequest
from com.googlecode.fascinator.api.storage import StorageException
from com.googlecode.fascinator.common.solr import SolrDoc, SolrResult
from org.apache.tapestry5.internal.services import URLEncoderImpl
from org.apache.tapestry5.internal import TapestryInternalUtils
from java.io import ByteArrayInputStream, ByteArrayOutputStream
from java.lang import Boolean
from java.net import URLDecoder
from org.apache.commons.io import IOUtils
class DownloadData:
def __init__(self):
pass
def __activate__(self, context):
self.services = context["Services"]
self.contextPath = context["contextPath"]
self.pageName = context["pageName"]
self.portalId = context["portalId"]
self.request = context["request"]
self.response = context["response"]
self.formData = context["formData"]
self.page = context["page"]
self.log = context["log"]
self.__metadata = SolrDoc(None)
object = None
payload = None
# URL basics
basePath = self.portalId + "/" + self.pageName
# Turn our URL into objects
fullUri = URLDecoder.decode(self.request.getAttribute("RequestURI"))
fullUri = self.tapestryUrlDecode(fullUri)
uri = fullUri[len(basePath)+1:]
object, payload = self.__resolve(uri)
if object is None:
if uri.endswith("/"):
self.log.error("Object 404: '{}'", uri)
self.response.setStatus(404);
writer = self.response.getPrintWriter("text/plain; charset=UTF-8")
writer.println("Object not found")
writer.close()
return
else:
# Sometimes adding a slash to the end will resolve the problem
|
# Ensure solr metadata is useable
oid = object.getId()
if self.isIndexed():
self.__metadata = self.__solrData.getResults().get(0)
else:
self.__metadata.getJsonObject().put("id", oid)
#print "URI='%s' OID='%s' PID='%s'" % (uri, object.getId(), payload.getId())
## The byte range cache will check for byte range requests first
self.cache = self.services.getByteRangeCache()
processed = self.cache.processRequest(self.request, self.response, payload)
if processed:
# We don't need to return data, the cache took care of it.
return
# Now the 'real' work of payload retrieval
if payload is not None:
filename = os.path.split(payload.getId())[1]
filename = "\"" + filename + "\""
mimeType = payload.getContentType()
if mimeType == "application/octet-stream":
self.response.setHeader("Content-Disposition", "attachment; filename=%s" % filename)
type = payload.getContentType()
# Enocode textual responses before sending
if type is not None and type.startswith("text/"):
out = ByteArrayOutputStream()
IOUtils.copy(payload.open(), out)
payload.close()
writer = self.response.getPrintWriter(type + "; charset=UTF-8")
writer.println(out.toString("UTF-8"))
writer.close()
# Other data can just be streamed out
else:
if type is None:
# Send as raw data
out = self.response.getOutputStream("application/octet-stream")
self.response.setHeader("Content-Disposition", "attachment; filename=%s" % filename)
else:
out = self.response.getOutputStream(type)
self.response.setHeader("Content-Disposition", "attachment; filename=%s" % filename)
IOUtils.copy(payload.open(), out)
payload.close()
object.close()
out.close()
else:
self.response.setStatus(404)
writer = self.response.getPrintWriter("text/plain; charset=UTF-8")
writer.println("Resource not found: uri='%s'" % uri)
writer.close()
def tapestryUrlDecode(self, uri):
tapestryUrlEncoder = URLEncoderImpl()
splitPath = TapestryInternalUtils.splitPath(uri);
decodedArray = []
for splitComponent in splitPath:
decodedArray.append(tapestryUrlEncoder.decode(splitComponent))
return '/'.join(decodedArray)
def getAllowedRoles(self):
metadata = self.getMetadata()
if metadata is not None:
return metadata.getList("security_filter")
else:
return []
def getViewUsers(self):
metadata = self.getMetadata()
if metadata is not None:
return metadata.getList("security_exception")
else:
return []
def getMetadata(self):
return self.__metadata
def isDetail(self):
preview = Boolean.parseBoolean(self.formData.get("preview", "false"))
return not (self.request.isXHR() or preview)
def isIndexed(self):
found = self.__solrData.getNumFound()
return (found is not None) and (found == 1)
def __resolve(self, uri):
# Grab OID from the URL
slash = uri.find("/")
if slash == -1:
return None, None
oid = uri[:slash]
# Query solr for this object
self.__loadSolrData(oid)
if not self.isIndexed():
print "WARNING: Object '%s' not found in index" % oid
sid = None
else:
# Query storage for this object
sid = self.__solrData.getResults().get(0).getFirst("storage_id")
try:
if sid is None:
# Use the URL OID
object = self.services.getStorage().getObject(oid)
else:
# We have a special storage ID from the index
object = self.services.getStorage().getObject(sid)
except StorageException, e:
#print "Failed to access object: %s" % (str(e))
return None, None
# Grab the payload from the rest of the URL
pid = uri[slash+1:]
if pid == "":
# We want the source
pid = object.getSourceId()
# Now get the payload from storage
try:
payload = object.getPayload(pid)
except StorageException, e:
#print "Failed to access payload: %s" % (str(e))
return None, None
# We're done
return object, payload
def __loadSolrData(self, oid):
portal = self.page.getPortal()
query = 'id:"%s"' % oid
if self.isDetail() and portal.getSearchQuery():
query += " AND " + portal.getSearchQuery()
req = SearchRequest(query)
req.addParam("fq", 'item_type:"object"')
if self.isDetail():
req.addParam("fq", portal.getQuery())
current_user = self.page.authentication.get_username()
security_roles = self.page.authentication.get_roles_list()
security_exceptions = 'security_exception:"' + current_user + '"'
owner_query = 'owner:"' + current_user + '"'
security_query = "(" + security_exceptions + ") OR (" + owner_query + ") OR ("+ security_exceptions +")"
req.addParam("fq", security_query)
out = ByteArrayOutputStream()
self.log.error("searching to get solrData")
self.services.getIndexer().search(req, out)
self.__solrData = SolrResult(ByteArrayInputStream(out.toByteArray()))
| self.log.error("Redirecting, object 404: '{}'", uri)
self.response.sendRedirect(context["urlBase"] + fullUri + "/")
return | conditional_block |
download.py | import os
from com.googlecode.fascinator.api.indexer import SearchRequest
from com.googlecode.fascinator.api.storage import StorageException
from com.googlecode.fascinator.common.solr import SolrDoc, SolrResult
from org.apache.tapestry5.internal.services import URLEncoderImpl
from org.apache.tapestry5.internal import TapestryInternalUtils
from java.io import ByteArrayInputStream, ByteArrayOutputStream
from java.lang import Boolean
from java.net import URLDecoder
from org.apache.commons.io import IOUtils
class DownloadData:
def __init__(self):
pass
def __activate__(self, context):
self.services = context["Services"]
self.contextPath = context["contextPath"]
self.pageName = context["pageName"]
self.portalId = context["portalId"]
self.request = context["request"]
self.response = context["response"]
self.formData = context["formData"]
self.page = context["page"]
self.log = context["log"]
self.__metadata = SolrDoc(None)
object = None | basePath = self.portalId + "/" + self.pageName
# Turn our URL into objects
fullUri = URLDecoder.decode(self.request.getAttribute("RequestURI"))
fullUri = self.tapestryUrlDecode(fullUri)
uri = fullUri[len(basePath)+1:]
object, payload = self.__resolve(uri)
if object is None:
if uri.endswith("/"):
self.log.error("Object 404: '{}'", uri)
self.response.setStatus(404);
writer = self.response.getPrintWriter("text/plain; charset=UTF-8")
writer.println("Object not found")
writer.close()
return
else:
# Sometimes adding a slash to the end will resolve the problem
self.log.error("Redirecting, object 404: '{}'", uri)
self.response.sendRedirect(context["urlBase"] + fullUri + "/")
return
# Ensure solr metadata is useable
oid = object.getId()
if self.isIndexed():
self.__metadata = self.__solrData.getResults().get(0)
else:
self.__metadata.getJsonObject().put("id", oid)
#print "URI='%s' OID='%s' PID='%s'" % (uri, object.getId(), payload.getId())
## The byte range cache will check for byte range requests first
self.cache = self.services.getByteRangeCache()
processed = self.cache.processRequest(self.request, self.response, payload)
if processed:
# We don't need to return data, the cache took care of it.
return
# Now the 'real' work of payload retrieval
if payload is not None:
filename = os.path.split(payload.getId())[1]
filename = "\"" + filename + "\""
mimeType = payload.getContentType()
if mimeType == "application/octet-stream":
self.response.setHeader("Content-Disposition", "attachment; filename=%s" % filename)
type = payload.getContentType()
# Enocode textual responses before sending
if type is not None and type.startswith("text/"):
out = ByteArrayOutputStream()
IOUtils.copy(payload.open(), out)
payload.close()
writer = self.response.getPrintWriter(type + "; charset=UTF-8")
writer.println(out.toString("UTF-8"))
writer.close()
# Other data can just be streamed out
else:
if type is None:
# Send as raw data
out = self.response.getOutputStream("application/octet-stream")
self.response.setHeader("Content-Disposition", "attachment; filename=%s" % filename)
else:
out = self.response.getOutputStream(type)
self.response.setHeader("Content-Disposition", "attachment; filename=%s" % filename)
IOUtils.copy(payload.open(), out)
payload.close()
object.close()
out.close()
else:
self.response.setStatus(404)
writer = self.response.getPrintWriter("text/plain; charset=UTF-8")
writer.println("Resource not found: uri='%s'" % uri)
writer.close()
def tapestryUrlDecode(self, uri):
tapestryUrlEncoder = URLEncoderImpl()
splitPath = TapestryInternalUtils.splitPath(uri);
decodedArray = []
for splitComponent in splitPath:
decodedArray.append(tapestryUrlEncoder.decode(splitComponent))
return '/'.join(decodedArray)
def getAllowedRoles(self):
metadata = self.getMetadata()
if metadata is not None:
return metadata.getList("security_filter")
else:
return []
def getViewUsers(self):
metadata = self.getMetadata()
if metadata is not None:
return metadata.getList("security_exception")
else:
return []
def getMetadata(self):
return self.__metadata
def isDetail(self):
preview = Boolean.parseBoolean(self.formData.get("preview", "false"))
return not (self.request.isXHR() or preview)
def isIndexed(self):
found = self.__solrData.getNumFound()
return (found is not None) and (found == 1)
def __resolve(self, uri):
# Grab OID from the URL
slash = uri.find("/")
if slash == -1:
return None, None
oid = uri[:slash]
# Query solr for this object
self.__loadSolrData(oid)
if not self.isIndexed():
print "WARNING: Object '%s' not found in index" % oid
sid = None
else:
# Query storage for this object
sid = self.__solrData.getResults().get(0).getFirst("storage_id")
try:
if sid is None:
# Use the URL OID
object = self.services.getStorage().getObject(oid)
else:
# We have a special storage ID from the index
object = self.services.getStorage().getObject(sid)
except StorageException, e:
#print "Failed to access object: %s" % (str(e))
return None, None
# Grab the payload from the rest of the URL
pid = uri[slash+1:]
if pid == "":
# We want the source
pid = object.getSourceId()
# Now get the payload from storage
try:
payload = object.getPayload(pid)
except StorageException, e:
#print "Failed to access payload: %s" % (str(e))
return None, None
# We're done
return object, payload
def __loadSolrData(self, oid):
portal = self.page.getPortal()
query = 'id:"%s"' % oid
if self.isDetail() and portal.getSearchQuery():
query += " AND " + portal.getSearchQuery()
req = SearchRequest(query)
req.addParam("fq", 'item_type:"object"')
if self.isDetail():
req.addParam("fq", portal.getQuery())
current_user = self.page.authentication.get_username()
security_roles = self.page.authentication.get_roles_list()
security_exceptions = 'security_exception:"' + current_user + '"'
owner_query = 'owner:"' + current_user + '"'
security_query = "(" + security_exceptions + ") OR (" + owner_query + ") OR ("+ security_exceptions +")"
req.addParam("fq", security_query)
out = ByteArrayOutputStream()
self.log.error("searching to get solrData")
self.services.getIndexer().search(req, out)
self.__solrData = SolrResult(ByteArrayInputStream(out.toByteArray())) | payload = None
# URL basics | random_line_split |
download.py | import os
from com.googlecode.fascinator.api.indexer import SearchRequest
from com.googlecode.fascinator.api.storage import StorageException
from com.googlecode.fascinator.common.solr import SolrDoc, SolrResult
from org.apache.tapestry5.internal.services import URLEncoderImpl
from org.apache.tapestry5.internal import TapestryInternalUtils
from java.io import ByteArrayInputStream, ByteArrayOutputStream
from java.lang import Boolean
from java.net import URLDecoder
from org.apache.commons.io import IOUtils
class DownloadData:
def __init__(self):
pass
def __activate__(self, context):
self.services = context["Services"]
self.contextPath = context["contextPath"]
self.pageName = context["pageName"]
self.portalId = context["portalId"]
self.request = context["request"]
self.response = context["response"]
self.formData = context["formData"]
self.page = context["page"]
self.log = context["log"]
self.__metadata = SolrDoc(None)
object = None
payload = None
# URL basics
basePath = self.portalId + "/" + self.pageName
# Turn our URL into objects
fullUri = URLDecoder.decode(self.request.getAttribute("RequestURI"))
fullUri = self.tapestryUrlDecode(fullUri)
uri = fullUri[len(basePath)+1:]
object, payload = self.__resolve(uri)
if object is None:
if uri.endswith("/"):
self.log.error("Object 404: '{}'", uri)
self.response.setStatus(404);
writer = self.response.getPrintWriter("text/plain; charset=UTF-8")
writer.println("Object not found")
writer.close()
return
else:
# Sometimes adding a slash to the end will resolve the problem
self.log.error("Redirecting, object 404: '{}'", uri)
self.response.sendRedirect(context["urlBase"] + fullUri + "/")
return
# Ensure solr metadata is useable
oid = object.getId()
if self.isIndexed():
self.__metadata = self.__solrData.getResults().get(0)
else:
self.__metadata.getJsonObject().put("id", oid)
#print "URI='%s' OID='%s' PID='%s'" % (uri, object.getId(), payload.getId())
## The byte range cache will check for byte range requests first
self.cache = self.services.getByteRangeCache()
processed = self.cache.processRequest(self.request, self.response, payload)
if processed:
# We don't need to return data, the cache took care of it.
return
# Now the 'real' work of payload retrieval
if payload is not None:
filename = os.path.split(payload.getId())[1]
filename = "\"" + filename + "\""
mimeType = payload.getContentType()
if mimeType == "application/octet-stream":
self.response.setHeader("Content-Disposition", "attachment; filename=%s" % filename)
type = payload.getContentType()
# Enocode textual responses before sending
if type is not None and type.startswith("text/"):
out = ByteArrayOutputStream()
IOUtils.copy(payload.open(), out)
payload.close()
writer = self.response.getPrintWriter(type + "; charset=UTF-8")
writer.println(out.toString("UTF-8"))
writer.close()
# Other data can just be streamed out
else:
if type is None:
# Send as raw data
out = self.response.getOutputStream("application/octet-stream")
self.response.setHeader("Content-Disposition", "attachment; filename=%s" % filename)
else:
out = self.response.getOutputStream(type)
self.response.setHeader("Content-Disposition", "attachment; filename=%s" % filename)
IOUtils.copy(payload.open(), out)
payload.close()
object.close()
out.close()
else:
self.response.setStatus(404)
writer = self.response.getPrintWriter("text/plain; charset=UTF-8")
writer.println("Resource not found: uri='%s'" % uri)
writer.close()
def tapestryUrlDecode(self, uri):
tapestryUrlEncoder = URLEncoderImpl()
splitPath = TapestryInternalUtils.splitPath(uri);
decodedArray = []
for splitComponent in splitPath:
decodedArray.append(tapestryUrlEncoder.decode(splitComponent))
return '/'.join(decodedArray)
def getAllowedRoles(self):
metadata = self.getMetadata()
if metadata is not None:
return metadata.getList("security_filter")
else:
return []
def getViewUsers(self):
metadata = self.getMetadata()
if metadata is not None:
return metadata.getList("security_exception")
else:
return []
def getMetadata(self):
return self.__metadata
def isDetail(self):
preview = Boolean.parseBoolean(self.formData.get("preview", "false"))
return not (self.request.isXHR() or preview)
def isIndexed(self):
found = self.__solrData.getNumFound()
return (found is not None) and (found == 1)
def __resolve(self, uri):
# Grab OID from the URL
slash = uri.find("/")
if slash == -1:
return None, None
oid = uri[:slash]
# Query solr for this object
self.__loadSolrData(oid)
if not self.isIndexed():
print "WARNING: Object '%s' not found in index" % oid
sid = None
else:
# Query storage for this object
sid = self.__solrData.getResults().get(0).getFirst("storage_id")
try:
if sid is None:
# Use the URL OID
object = self.services.getStorage().getObject(oid)
else:
# We have a special storage ID from the index
object = self.services.getStorage().getObject(sid)
except StorageException, e:
#print "Failed to access object: %s" % (str(e))
return None, None
# Grab the payload from the rest of the URL
pid = uri[slash+1:]
if pid == "":
# We want the source
pid = object.getSourceId()
# Now get the payload from storage
try:
payload = object.getPayload(pid)
except StorageException, e:
#print "Failed to access payload: %s" % (str(e))
return None, None
# We're done
return object, payload
def __loadSolrData(self, oid):
| portal = self.page.getPortal()
query = 'id:"%s"' % oid
if self.isDetail() and portal.getSearchQuery():
query += " AND " + portal.getSearchQuery()
req = SearchRequest(query)
req.addParam("fq", 'item_type:"object"')
if self.isDetail():
req.addParam("fq", portal.getQuery())
current_user = self.page.authentication.get_username()
security_roles = self.page.authentication.get_roles_list()
security_exceptions = 'security_exception:"' + current_user + '"'
owner_query = 'owner:"' + current_user + '"'
security_query = "(" + security_exceptions + ") OR (" + owner_query + ") OR ("+ security_exceptions +")"
req.addParam("fq", security_query)
out = ByteArrayOutputStream()
self.log.error("searching to get solrData")
self.services.getIndexer().search(req, out)
self.__solrData = SolrResult(ByteArrayInputStream(out.toByteArray())) | identifier_body | |
download.py | import os
from com.googlecode.fascinator.api.indexer import SearchRequest
from com.googlecode.fascinator.api.storage import StorageException
from com.googlecode.fascinator.common.solr import SolrDoc, SolrResult
from org.apache.tapestry5.internal.services import URLEncoderImpl
from org.apache.tapestry5.internal import TapestryInternalUtils
from java.io import ByteArrayInputStream, ByteArrayOutputStream
from java.lang import Boolean
from java.net import URLDecoder
from org.apache.commons.io import IOUtils
class DownloadData:
def __init__(self):
pass
def __activate__(self, context):
self.services = context["Services"]
self.contextPath = context["contextPath"]
self.pageName = context["pageName"]
self.portalId = context["portalId"]
self.request = context["request"]
self.response = context["response"]
self.formData = context["formData"]
self.page = context["page"]
self.log = context["log"]
self.__metadata = SolrDoc(None)
object = None
payload = None
# URL basics
basePath = self.portalId + "/" + self.pageName
# Turn our URL into objects
fullUri = URLDecoder.decode(self.request.getAttribute("RequestURI"))
fullUri = self.tapestryUrlDecode(fullUri)
uri = fullUri[len(basePath)+1:]
object, payload = self.__resolve(uri)
if object is None:
if uri.endswith("/"):
self.log.error("Object 404: '{}'", uri)
self.response.setStatus(404);
writer = self.response.getPrintWriter("text/plain; charset=UTF-8")
writer.println("Object not found")
writer.close()
return
else:
# Sometimes adding a slash to the end will resolve the problem
self.log.error("Redirecting, object 404: '{}'", uri)
self.response.sendRedirect(context["urlBase"] + fullUri + "/")
return
# Ensure solr metadata is useable
oid = object.getId()
if self.isIndexed():
self.__metadata = self.__solrData.getResults().get(0)
else:
self.__metadata.getJsonObject().put("id", oid)
#print "URI='%s' OID='%s' PID='%s'" % (uri, object.getId(), payload.getId())
## The byte range cache will check for byte range requests first
self.cache = self.services.getByteRangeCache()
processed = self.cache.processRequest(self.request, self.response, payload)
if processed:
# We don't need to return data, the cache took care of it.
return
# Now the 'real' work of payload retrieval
if payload is not None:
filename = os.path.split(payload.getId())[1]
filename = "\"" + filename + "\""
mimeType = payload.getContentType()
if mimeType == "application/octet-stream":
self.response.setHeader("Content-Disposition", "attachment; filename=%s" % filename)
type = payload.getContentType()
# Enocode textual responses before sending
if type is not None and type.startswith("text/"):
out = ByteArrayOutputStream()
IOUtils.copy(payload.open(), out)
payload.close()
writer = self.response.getPrintWriter(type + "; charset=UTF-8")
writer.println(out.toString("UTF-8"))
writer.close()
# Other data can just be streamed out
else:
if type is None:
# Send as raw data
out = self.response.getOutputStream("application/octet-stream")
self.response.setHeader("Content-Disposition", "attachment; filename=%s" % filename)
else:
out = self.response.getOutputStream(type)
self.response.setHeader("Content-Disposition", "attachment; filename=%s" % filename)
IOUtils.copy(payload.open(), out)
payload.close()
object.close()
out.close()
else:
self.response.setStatus(404)
writer = self.response.getPrintWriter("text/plain; charset=UTF-8")
writer.println("Resource not found: uri='%s'" % uri)
writer.close()
def tapestryUrlDecode(self, uri):
tapestryUrlEncoder = URLEncoderImpl()
splitPath = TapestryInternalUtils.splitPath(uri);
decodedArray = []
for splitComponent in splitPath:
decodedArray.append(tapestryUrlEncoder.decode(splitComponent))
return '/'.join(decodedArray)
def getAllowedRoles(self):
metadata = self.getMetadata()
if metadata is not None:
return metadata.getList("security_filter")
else:
return []
def | (self):
metadata = self.getMetadata()
if metadata is not None:
return metadata.getList("security_exception")
else:
return []
def getMetadata(self):
return self.__metadata
def isDetail(self):
preview = Boolean.parseBoolean(self.formData.get("preview", "false"))
return not (self.request.isXHR() or preview)
def isIndexed(self):
found = self.__solrData.getNumFound()
return (found is not None) and (found == 1)
def __resolve(self, uri):
# Grab OID from the URL
slash = uri.find("/")
if slash == -1:
return None, None
oid = uri[:slash]
# Query solr for this object
self.__loadSolrData(oid)
if not self.isIndexed():
print "WARNING: Object '%s' not found in index" % oid
sid = None
else:
# Query storage for this object
sid = self.__solrData.getResults().get(0).getFirst("storage_id")
try:
if sid is None:
# Use the URL OID
object = self.services.getStorage().getObject(oid)
else:
# We have a special storage ID from the index
object = self.services.getStorage().getObject(sid)
except StorageException, e:
#print "Failed to access object: %s" % (str(e))
return None, None
# Grab the payload from the rest of the URL
pid = uri[slash+1:]
if pid == "":
# We want the source
pid = object.getSourceId()
# Now get the payload from storage
try:
payload = object.getPayload(pid)
except StorageException, e:
#print "Failed to access payload: %s" % (str(e))
return None, None
# We're done
return object, payload
def __loadSolrData(self, oid):
portal = self.page.getPortal()
query = 'id:"%s"' % oid
if self.isDetail() and portal.getSearchQuery():
query += " AND " + portal.getSearchQuery()
req = SearchRequest(query)
req.addParam("fq", 'item_type:"object"')
if self.isDetail():
req.addParam("fq", portal.getQuery())
current_user = self.page.authentication.get_username()
security_roles = self.page.authentication.get_roles_list()
security_exceptions = 'security_exception:"' + current_user + '"'
owner_query = 'owner:"' + current_user + '"'
security_query = "(" + security_exceptions + ") OR (" + owner_query + ") OR ("+ security_exceptions +")"
req.addParam("fq", security_query)
out = ByteArrayOutputStream()
self.log.error("searching to get solrData")
self.services.getIndexer().search(req, out)
self.__solrData = SolrResult(ByteArrayInputStream(out.toByteArray()))
| getViewUsers | identifier_name |
ocr.py | """
Runs OCR on a given file.
"""
from os import system, listdir
from PIL import Image
from pytesseract import image_to_string
import editdistance
from constants import DATA_DIR
def classify(image, people_class, max_classify_distance=1, min_nonclassify_distance=3):
""" | dist = editdistance.eval(person, read)
if dist <= max_classify_distance:
if result is not None:
return None
result = people_class[person]
elif max_classify_distance < dist <= min_nonclassify_distance:
return None
return result
def setup_ocr(raw_data, progress):
"""
Grabs names from a pdf to an image
"""
system("unzip {} -d {}/extract".format(raw_data, DATA_DIR))
base = DATA_DIR + "/extract/"
mainfolder = base + listdir(base)[0]
files = sorted(listdir(mainfolder))
p_bar = progress(len(files))
for index, path in enumerate(files):
p_bar.update(index)
fullpath = mainfolder + "/" + path
system("mkdir {}/ocr".format(DATA_DIR))
basic_format = r"pdftoppm -png -f 3 -l 3 -x 170 -y %s -W 900 -H 100 {} > {}/ocr/%s{}.png" \
.format(fullpath, DATA_DIR, index)
system(basic_format % (1030, "left"))
system(basic_format % (1115, "right")) | Runs an OCR classifier on a given image file, drawing from a dictionary
"""
read = image_to_string(Image.open(image)).lower()
result = None
for person in people_class: | random_line_split |
ocr.py | """
Runs OCR on a given file.
"""
from os import system, listdir
from PIL import Image
from pytesseract import image_to_string
import editdistance
from constants import DATA_DIR
def classify(image, people_class, max_classify_distance=1, min_nonclassify_distance=3):
"""
Runs an OCR classifier on a given image file, drawing from a dictionary
"""
read = image_to_string(Image.open(image)).lower()
result = None
for person in people_class:
dist = editdistance.eval(person, read)
if dist <= max_classify_distance:
if result is not None:
return None
result = people_class[person]
elif max_classify_distance < dist <= min_nonclassify_distance:
return None
return result
def | (raw_data, progress):
"""
Grabs names from a pdf to an image
"""
system("unzip {} -d {}/extract".format(raw_data, DATA_DIR))
base = DATA_DIR + "/extract/"
mainfolder = base + listdir(base)[0]
files = sorted(listdir(mainfolder))
p_bar = progress(len(files))
for index, path in enumerate(files):
p_bar.update(index)
fullpath = mainfolder + "/" + path
system("mkdir {}/ocr".format(DATA_DIR))
basic_format = r"pdftoppm -png -f 3 -l 3 -x 170 -y %s -W 900 -H 100 {} > {}/ocr/%s{}.png" \
.format(fullpath, DATA_DIR, index)
system(basic_format % (1030, "left"))
system(basic_format % (1115, "right"))
| setup_ocr | identifier_name |
ocr.py | """
Runs OCR on a given file.
"""
from os import system, listdir
from PIL import Image
from pytesseract import image_to_string
import editdistance
from constants import DATA_DIR
def classify(image, people_class, max_classify_distance=1, min_nonclassify_distance=3):
"""
Runs an OCR classifier on a given image file, drawing from a dictionary
"""
read = image_to_string(Image.open(image)).lower()
result = None
for person in people_class:
dist = editdistance.eval(person, read)
if dist <= max_classify_distance:
if result is not None:
return None
result = people_class[person]
elif max_classify_distance < dist <= min_nonclassify_distance:
return None
return result
def setup_ocr(raw_data, progress):
| """
Grabs names from a pdf to an image
"""
system("unzip {} -d {}/extract".format(raw_data, DATA_DIR))
base = DATA_DIR + "/extract/"
mainfolder = base + listdir(base)[0]
files = sorted(listdir(mainfolder))
p_bar = progress(len(files))
for index, path in enumerate(files):
p_bar.update(index)
fullpath = mainfolder + "/" + path
system("mkdir {}/ocr".format(DATA_DIR))
basic_format = r"pdftoppm -png -f 3 -l 3 -x 170 -y %s -W 900 -H 100 {} > {}/ocr/%s{}.png" \
.format(fullpath, DATA_DIR, index)
system(basic_format % (1030, "left"))
system(basic_format % (1115, "right")) | identifier_body | |
ocr.py | """
Runs OCR on a given file.
"""
from os import system, listdir
from PIL import Image
from pytesseract import image_to_string
import editdistance
from constants import DATA_DIR
def classify(image, people_class, max_classify_distance=1, min_nonclassify_distance=3):
"""
Runs an OCR classifier on a given image file, drawing from a dictionary
"""
read = image_to_string(Image.open(image)).lower()
result = None
for person in people_class:
dist = editdistance.eval(person, read)
if dist <= max_classify_distance:
|
elif max_classify_distance < dist <= min_nonclassify_distance:
return None
return result
def setup_ocr(raw_data, progress):
"""
Grabs names from a pdf to an image
"""
system("unzip {} -d {}/extract".format(raw_data, DATA_DIR))
base = DATA_DIR + "/extract/"
mainfolder = base + listdir(base)[0]
files = sorted(listdir(mainfolder))
p_bar = progress(len(files))
for index, path in enumerate(files):
p_bar.update(index)
fullpath = mainfolder + "/" + path
system("mkdir {}/ocr".format(DATA_DIR))
basic_format = r"pdftoppm -png -f 3 -l 3 -x 170 -y %s -W 900 -H 100 {} > {}/ocr/%s{}.png" \
.format(fullpath, DATA_DIR, index)
system(basic_format % (1030, "left"))
system(basic_format % (1115, "right"))
| if result is not None:
return None
result = people_class[person] | conditional_block |
users.ts | 'use strict';
import * as bcrypt from 'bcryptjs';
import * as express from 'express';
import * as jwt from 'jsonwebtoken';
import * as _ from 'lodash';
import * as auth from 'passport';
import { Inject } from 'typescript-ioc';
import { ValidationError } from '../../config/errors';
import { UserData } from '../../config/users';
import { Configuration } from '../../configuration';
import { Database } from '../../database';
import { NotFoundError } from '../../pipeline/error/errors';
import { MiddlewareLoader } from '../../utils/middleware-loader';
import { UserService } from '../users';
export class RedisUserService implements UserService {
public static USERS_PREFIX = 'adminUsers';
@Inject private config: Configuration;
@Inject private database: Database;
@Inject private middlewareLoader: MiddlewareLoader;
public async list(): Promise<Array<UserData>> {
const users = await this.database.redisClient.hgetall(RedisUserService.USERS_PREFIX);
return _.map(_.values(users), (value: string) => _.omit(JSON.parse(value), 'password')) as Array<UserData>;
}
public async get(login: string): Promise<UserData> {
const user = await this.database.redisClient.hget(RedisUserService.USERS_PREFIX, login);
if (!user) {
return null;
}
return JSON.parse(user);
}
public async create(user: UserData): Promise<void> {
const exists = await this.database.redisClient.hexists(`${RedisUserService.USERS_PREFIX}`, user.login);
if (exists) {
throw new ValidationError(`User ${user.login} already exists`);
}
if (!user.password) {
throw new ValidationError(`Password is required for user.`);
}
user.password = await bcrypt.hash(user.password, 10);
await this.database.redisClient.hmset(`${RedisUserService.USERS_PREFIX}`, user.login, JSON.stringify(user));
}
public async changePassword(login: string, password: string): Promise<void> {
const exists = await this.database.redisClient.hexists(`${RedisUserService.USERS_PREFIX}`, login);
if (!exists) {
throw new NotFoundError('User not found.');
}
const user: UserData = await this.get(login);
user.password = await bcrypt.hash(user.password, 10);
await this.database.redisClient.hmset(`${RedisUserService.USERS_PREFIX}`, user.login, JSON.stringify(user));
}
public async update(user: UserData): Promise<void> {
const exists = await this.database.redisClient.hexists(`${RedisUserService.USERS_PREFIX}`, user.login);
if (!exists) {
throw new NotFoundError('User not found.');
}
const oldUser = await this.get(user.login);
user.password = oldUser.password;
await this.database.redisClient.hmset(`${RedisUserService.USERS_PREFIX}`, user.login, JSON.stringify(user));
}
public async remove(login: string): Promise<void> |
public async generateToken(login: string, password: string): Promise<string> {
const user = await this.get(login);
if (!user) {
throw new ValidationError('User not found');
}
let same;
try {
same = await bcrypt.compare(password, user.password);
} catch (err) {
throw new ValidationError('Error validating user password');
}
if (!same) {
throw new ValidationError('Invalid username / password');
}
try {
const dataToken = {
email: user.email,
login: user.login,
name: user.name,
roles: user.roles
};
const token = jwt.sign(dataToken, this.config.gateway.admin.userService.jwtSecret, {
expiresIn: 7200 // TODO read an human interval configuration
});
return token;
} catch (err) {
throw new ValidationError('Error validating user password');
}
}
public getAuthMiddleware(): express.RequestHandler {
const opts: any = {
secretOrKey: this.config.gateway.admin.userService.jwtSecret
};
const strategy = this.middlewareLoader.loadMiddleware('authentication/strategy', { name: 'jwt', options: opts });
auth.use('_tree_gateway_admin_', strategy);
return auth.authenticate('_tree_gateway_admin_', { session: false, failWithError: true });
}
}
| {
const count = await this.database.redisClient.hdel(`${RedisUserService.USERS_PREFIX}`, login);
if (count === 0) {
throw new NotFoundError('User not found.');
}
} | identifier_body |
users.ts | 'use strict';
import * as bcrypt from 'bcryptjs';
import * as express from 'express';
import * as jwt from 'jsonwebtoken';
import * as _ from 'lodash';
import * as auth from 'passport';
import { Inject } from 'typescript-ioc';
import { ValidationError } from '../../config/errors';
import { UserData } from '../../config/users';
import { Configuration } from '../../configuration';
import { Database } from '../../database';
import { NotFoundError } from '../../pipeline/error/errors';
import { MiddlewareLoader } from '../../utils/middleware-loader';
import { UserService } from '../users';
export class RedisUserService implements UserService {
public static USERS_PREFIX = 'adminUsers';
@Inject private config: Configuration;
@Inject private database: Database;
@Inject private middlewareLoader: MiddlewareLoader;
public async list(): Promise<Array<UserData>> {
const users = await this.database.redisClient.hgetall(RedisUserService.USERS_PREFIX);
return _.map(_.values(users), (value: string) => _.omit(JSON.parse(value), 'password')) as Array<UserData>;
}
public async get(login: string): Promise<UserData> {
const user = await this.database.redisClient.hget(RedisUserService.USERS_PREFIX, login);
if (!user) {
return null;
}
return JSON.parse(user);
}
public async create(user: UserData): Promise<void> {
const exists = await this.database.redisClient.hexists(`${RedisUserService.USERS_PREFIX}`, user.login);
if (exists) {
throw new ValidationError(`User ${user.login} already exists`);
}
if (!user.password) {
throw new ValidationError(`Password is required for user.`);
}
user.password = await bcrypt.hash(user.password, 10);
await this.database.redisClient.hmset(`${RedisUserService.USERS_PREFIX}`, user.login, JSON.stringify(user));
}
public async changePassword(login: string, password: string): Promise<void> {
const exists = await this.database.redisClient.hexists(`${RedisUserService.USERS_PREFIX}`, login);
if (!exists) {
throw new NotFoundError('User not found.');
}
const user: UserData = await this.get(login);
user.password = await bcrypt.hash(user.password, 10); | const exists = await this.database.redisClient.hexists(`${RedisUserService.USERS_PREFIX}`, user.login);
if (!exists) {
throw new NotFoundError('User not found.');
}
const oldUser = await this.get(user.login);
user.password = oldUser.password;
await this.database.redisClient.hmset(`${RedisUserService.USERS_PREFIX}`, user.login, JSON.stringify(user));
}
public async remove(login: string): Promise<void> {
const count = await this.database.redisClient.hdel(`${RedisUserService.USERS_PREFIX}`, login);
if (count === 0) {
throw new NotFoundError('User not found.');
}
}
public async generateToken(login: string, password: string): Promise<string> {
const user = await this.get(login);
if (!user) {
throw new ValidationError('User not found');
}
let same;
try {
same = await bcrypt.compare(password, user.password);
} catch (err) {
throw new ValidationError('Error validating user password');
}
if (!same) {
throw new ValidationError('Invalid username / password');
}
try {
const dataToken = {
email: user.email,
login: user.login,
name: user.name,
roles: user.roles
};
const token = jwt.sign(dataToken, this.config.gateway.admin.userService.jwtSecret, {
expiresIn: 7200 // TODO read an human interval configuration
});
return token;
} catch (err) {
throw new ValidationError('Error validating user password');
}
}
public getAuthMiddleware(): express.RequestHandler {
const opts: any = {
secretOrKey: this.config.gateway.admin.userService.jwtSecret
};
const strategy = this.middlewareLoader.loadMiddleware('authentication/strategy', { name: 'jwt', options: opts });
auth.use('_tree_gateway_admin_', strategy);
return auth.authenticate('_tree_gateway_admin_', { session: false, failWithError: true });
}
} | await this.database.redisClient.hmset(`${RedisUserService.USERS_PREFIX}`, user.login, JSON.stringify(user));
}
public async update(user: UserData): Promise<void> { | random_line_split |
users.ts | 'use strict';
import * as bcrypt from 'bcryptjs';
import * as express from 'express';
import * as jwt from 'jsonwebtoken';
import * as _ from 'lodash';
import * as auth from 'passport';
import { Inject } from 'typescript-ioc';
import { ValidationError } from '../../config/errors';
import { UserData } from '../../config/users';
import { Configuration } from '../../configuration';
import { Database } from '../../database';
import { NotFoundError } from '../../pipeline/error/errors';
import { MiddlewareLoader } from '../../utils/middleware-loader';
import { UserService } from '../users';
export class RedisUserService implements UserService {
public static USERS_PREFIX = 'adminUsers';
@Inject private config: Configuration;
@Inject private database: Database;
@Inject private middlewareLoader: MiddlewareLoader;
public async list(): Promise<Array<UserData>> {
const users = await this.database.redisClient.hgetall(RedisUserService.USERS_PREFIX);
return _.map(_.values(users), (value: string) => _.omit(JSON.parse(value), 'password')) as Array<UserData>;
}
public async get(login: string): Promise<UserData> {
const user = await this.database.redisClient.hget(RedisUserService.USERS_PREFIX, login);
if (!user) {
return null;
}
return JSON.parse(user);
}
public async create(user: UserData): Promise<void> {
const exists = await this.database.redisClient.hexists(`${RedisUserService.USERS_PREFIX}`, user.login);
if (exists) {
throw new ValidationError(`User ${user.login} already exists`);
}
if (!user.password) {
throw new ValidationError(`Password is required for user.`);
}
user.password = await bcrypt.hash(user.password, 10);
await this.database.redisClient.hmset(`${RedisUserService.USERS_PREFIX}`, user.login, JSON.stringify(user));
}
public async changePassword(login: string, password: string): Promise<void> {
const exists = await this.database.redisClient.hexists(`${RedisUserService.USERS_PREFIX}`, login);
if (!exists) {
throw new NotFoundError('User not found.');
}
const user: UserData = await this.get(login);
user.password = await bcrypt.hash(user.password, 10);
await this.database.redisClient.hmset(`${RedisUserService.USERS_PREFIX}`, user.login, JSON.stringify(user));
}
public async update(user: UserData): Promise<void> {
const exists = await this.database.redisClient.hexists(`${RedisUserService.USERS_PREFIX}`, user.login);
if (!exists) {
throw new NotFoundError('User not found.');
}
const oldUser = await this.get(user.login);
user.password = oldUser.password;
await this.database.redisClient.hmset(`${RedisUserService.USERS_PREFIX}`, user.login, JSON.stringify(user));
}
public async remove(login: string): Promise<void> {
const count = await this.database.redisClient.hdel(`${RedisUserService.USERS_PREFIX}`, login);
if (count === 0) {
throw new NotFoundError('User not found.');
}
}
public async generateToken(login: string, password: string): Promise<string> {
const user = await this.get(login);
if (!user) |
let same;
try {
same = await bcrypt.compare(password, user.password);
} catch (err) {
throw new ValidationError('Error validating user password');
}
if (!same) {
throw new ValidationError('Invalid username / password');
}
try {
const dataToken = {
email: user.email,
login: user.login,
name: user.name,
roles: user.roles
};
const token = jwt.sign(dataToken, this.config.gateway.admin.userService.jwtSecret, {
expiresIn: 7200 // TODO read an human interval configuration
});
return token;
} catch (err) {
throw new ValidationError('Error validating user password');
}
}
public getAuthMiddleware(): express.RequestHandler {
const opts: any = {
secretOrKey: this.config.gateway.admin.userService.jwtSecret
};
const strategy = this.middlewareLoader.loadMiddleware('authentication/strategy', { name: 'jwt', options: opts });
auth.use('_tree_gateway_admin_', strategy);
return auth.authenticate('_tree_gateway_admin_', { session: false, failWithError: true });
}
}
| {
throw new ValidationError('User not found');
} | conditional_block |
users.ts | 'use strict';
import * as bcrypt from 'bcryptjs';
import * as express from 'express';
import * as jwt from 'jsonwebtoken';
import * as _ from 'lodash';
import * as auth from 'passport';
import { Inject } from 'typescript-ioc';
import { ValidationError } from '../../config/errors';
import { UserData } from '../../config/users';
import { Configuration } from '../../configuration';
import { Database } from '../../database';
import { NotFoundError } from '../../pipeline/error/errors';
import { MiddlewareLoader } from '../../utils/middleware-loader';
import { UserService } from '../users';
export class | implements UserService {
public static USERS_PREFIX = 'adminUsers';
@Inject private config: Configuration;
@Inject private database: Database;
@Inject private middlewareLoader: MiddlewareLoader;
public async list(): Promise<Array<UserData>> {
const users = await this.database.redisClient.hgetall(RedisUserService.USERS_PREFIX);
return _.map(_.values(users), (value: string) => _.omit(JSON.parse(value), 'password')) as Array<UserData>;
}
public async get(login: string): Promise<UserData> {
const user = await this.database.redisClient.hget(RedisUserService.USERS_PREFIX, login);
if (!user) {
return null;
}
return JSON.parse(user);
}
public async create(user: UserData): Promise<void> {
const exists = await this.database.redisClient.hexists(`${RedisUserService.USERS_PREFIX}`, user.login);
if (exists) {
throw new ValidationError(`User ${user.login} already exists`);
}
if (!user.password) {
throw new ValidationError(`Password is required for user.`);
}
user.password = await bcrypt.hash(user.password, 10);
await this.database.redisClient.hmset(`${RedisUserService.USERS_PREFIX}`, user.login, JSON.stringify(user));
}
public async changePassword(login: string, password: string): Promise<void> {
const exists = await this.database.redisClient.hexists(`${RedisUserService.USERS_PREFIX}`, login);
if (!exists) {
throw new NotFoundError('User not found.');
}
const user: UserData = await this.get(login);
user.password = await bcrypt.hash(user.password, 10);
await this.database.redisClient.hmset(`${RedisUserService.USERS_PREFIX}`, user.login, JSON.stringify(user));
}
public async update(user: UserData): Promise<void> {
const exists = await this.database.redisClient.hexists(`${RedisUserService.USERS_PREFIX}`, user.login);
if (!exists) {
throw new NotFoundError('User not found.');
}
const oldUser = await this.get(user.login);
user.password = oldUser.password;
await this.database.redisClient.hmset(`${RedisUserService.USERS_PREFIX}`, user.login, JSON.stringify(user));
}
public async remove(login: string): Promise<void> {
const count = await this.database.redisClient.hdel(`${RedisUserService.USERS_PREFIX}`, login);
if (count === 0) {
throw new NotFoundError('User not found.');
}
}
public async generateToken(login: string, password: string): Promise<string> {
const user = await this.get(login);
if (!user) {
throw new ValidationError('User not found');
}
let same;
try {
same = await bcrypt.compare(password, user.password);
} catch (err) {
throw new ValidationError('Error validating user password');
}
if (!same) {
throw new ValidationError('Invalid username / password');
}
try {
const dataToken = {
email: user.email,
login: user.login,
name: user.name,
roles: user.roles
};
const token = jwt.sign(dataToken, this.config.gateway.admin.userService.jwtSecret, {
expiresIn: 7200 // TODO read an human interval configuration
});
return token;
} catch (err) {
throw new ValidationError('Error validating user password');
}
}
public getAuthMiddleware(): express.RequestHandler {
const opts: any = {
secretOrKey: this.config.gateway.admin.userService.jwtSecret
};
const strategy = this.middlewareLoader.loadMiddleware('authentication/strategy', { name: 'jwt', options: opts });
auth.use('_tree_gateway_admin_', strategy);
return auth.authenticate('_tree_gateway_admin_', { session: false, failWithError: true });
}
}
| RedisUserService | identifier_name |
toast.d.ts | import * as React from "react";
import { IActionProps, IIntentProps, IProps } from "../../common/props";
export interface IToastProps extends IProps, IIntentProps {
/**
* Action to display in a minimal button. The toast is dismissed automatically when the
* user clicks the action button. Note that the `intent` prop is ignored (the action button
* cannot have its own intent color that might conflict with the toast's intent). Omit this
* prop to omit the action button.
*/
action?: IActionProps;
/** Name of icon to appear before message. Specify only the part of the name after `pt-icon-`. */
iconName?: string;
/** Message to display in the body of the toast. */
message: string | JSX.Element;
/**
* Callback invoked when the toast is dismissed, either by the user or by the timeout.
* The value of the argument indicates whether the toast was closed because the timeout expired.
*/
onDismiss?: (didTimeoutExpire: boolean) => void;
/**
* Milliseconds to wait before automatically dismissing toast.
* Providing a value <= 0 will disable the timeout (this is discouraged).
* @default 5000
*/
timeout?: number; | displayName: string;
private timeoutId;
render(): JSX.Element;
componentDidMount(): void;
componentDidUpdate(prevProps: IToastProps): void;
componentWillUnmount(): void;
private maybeRenderActionButton();
private maybeRenderIcon();
private handleActionClick;
private handleCloseClick;
private triggerDismiss(didTimeoutExpire);
private startTimeout;
private clearTimeout;
}
export declare const ToastFactory: React.ComponentFactory<IToastProps & {
children?: React.ReactNode;
}, Toast>; | }
export declare class Toast extends React.Component<IToastProps, {}> {
static defaultProps: IToastProps; | random_line_split |
toast.d.ts | import * as React from "react";
import { IActionProps, IIntentProps, IProps } from "../../common/props";
export interface IToastProps extends IProps, IIntentProps {
/**
* Action to display in a minimal button. The toast is dismissed automatically when the
* user clicks the action button. Note that the `intent` prop is ignored (the action button
* cannot have its own intent color that might conflict with the toast's intent). Omit this
* prop to omit the action button.
*/
action?: IActionProps;
/** Name of icon to appear before message. Specify only the part of the name after `pt-icon-`. */
iconName?: string;
/** Message to display in the body of the toast. */
message: string | JSX.Element;
/**
* Callback invoked when the toast is dismissed, either by the user or by the timeout.
* The value of the argument indicates whether the toast was closed because the timeout expired.
*/
onDismiss?: (didTimeoutExpire: boolean) => void;
/**
* Milliseconds to wait before automatically dismissing toast.
* Providing a value <= 0 will disable the timeout (this is discouraged).
* @default 5000
*/
timeout?: number;
}
export declare class | extends React.Component<IToastProps, {}> {
static defaultProps: IToastProps;
displayName: string;
private timeoutId;
render(): JSX.Element;
componentDidMount(): void;
componentDidUpdate(prevProps: IToastProps): void;
componentWillUnmount(): void;
private maybeRenderActionButton();
private maybeRenderIcon();
private handleActionClick;
private handleCloseClick;
private triggerDismiss(didTimeoutExpire);
private startTimeout;
private clearTimeout;
}
export declare const ToastFactory: React.ComponentFactory<IToastProps & {
children?: React.ReactNode;
}, Toast>;
| Toast | identifier_name |
index.tsx | import { ArtworkExtraLinks_artwork } from "__generated__/ArtworkExtraLinks_artwork.graphql"
import { AuctionTimerState } from "app/Components/Bidding/Components/Timer"
import { navigate } from "app/navigation/navigate"
import { partnerName } from "app/Scenes/Artwork/Components/ArtworkExtraLinks/partnerName"
import { useSelectedTab } from "app/store/GlobalStore"
import { sendEmail } from "app/utils/sendEmail"
import { Schema, track } from "app/utils/track"
import { Sans, Spacer } from "palette"
import React from "react"
import { Text, View } from "react-native"
import { createFragmentContainer, graphql } from "react-relay"
import { useTracking } from "react-tracking"
export interface ArtworkExtraLinksProps {
artwork: ArtworkExtraLinks_artwork
auctionState: AuctionTimerState
}
@track()
export class ArtworkExtraLinks extends React.Component<ArtworkExtraLinksProps> {
handleReadOurFAQTap = () => {
navigate(`/buy-now-feature-faq`)
}
@track({
action_name: Schema.ActionNames.AskASpecialist,
action_type: Schema.ActionTypes.Tap,
context_module: Schema.ContextModules.ArtworkExtraLinks,
})
// @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏
handleAskASpecialistTap(emailAddress) {
const { artwork } = this.props
const mailtoSubject = `Inquiry on ${artwork.title}`.concat(
artwork.artist && artwork.artist.name ? ` by ${artwork.artist.name}` : ""
)
sendEmail(emailAddress, { subject: mailtoSubject })
}
@track({
action_name: Schema.ActionNames.AuctionsFAQ,
action_type: Schema.ActionTypes.Tap,
context_module: Schema.ContextModules.ArtworkExtraLinks,
})
handleReadOurAuctionFAQsTap() {
navigate(`/auction-faq`)
return
}
@track({
action_name: Schema.ActionNames.ConditionsOfSale,
action_type: Schema.ActionTypes.Tap,
context_module: Schema.ContextModules.ArtworkExtraLinks,
})
handleCon | navigate(`/conditions-of-sale`)
}
renderFAQAndSpecialist = () => {
const {
artwork: { isAcquireable, isOfferable, isInAuction, sale, isForSale },
auctionState,
} = this.props
if (isInAuction && sale && isForSale && auctionState !== AuctionTimerState.CLOSED) {
return (
<>
<Sans size="2" color="black60">
By placing a bid you agree to {partnerName(sale)}{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleConditionsOfSaleTap()}
>
Conditions of Sale
</Text>
.
</Sans>
<Spacer mb={1} />
<Sans size="2" color="black60">
Have a question?{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleReadOurAuctionFAQsTap()}
>
Read our auction FAQs
</Text>{" "}
or{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleAskASpecialistTap("specialist@artsy.net")}
>
ask a specialist
</Text>
.
</Sans>
</>
)
} else if (isAcquireable || isOfferable) {
return (
<Sans size="2" color="black60">
Have a question?{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleReadOurFAQTap()}
>
Read our FAQ
</Text>{" "}
or{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleAskASpecialistTap("orders@artsy.net")}
>
ask a specialist
</Text>
.
</Sans>
)
} else {
return null
}
}
render() {
const {
artwork: { artists },
} = this.props
// @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏
const consignableArtistsCount = artists.filter((artist) => artist.isConsignable).length
// @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏
const artistName = artists && artists.length === 1 ? artists[0].name : null
return (
<>
{this.renderFAQAndSpecialist()}
{!!consignableArtistsCount && (
<ConsignmentsLink
artistName={consignableArtistsCount > 1 ? "these artists" : artistName ?? "this artist"}
/>
)}
</>
)
}
}
const ConsignmentsLink: React.FC<{ artistName: string }> = ({ artistName }) => {
const isSellTab = useSelectedTab() === "sell"
const tracking = useTracking()
return (
<View>
<Sans size="2" color="black60">
Want to sell a work by {artistName}?{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => {
tracking.trackEvent({
action_name: Schema.ActionNames.ConsignWithArtsy,
action_type: Schema.ActionTypes.Tap,
context_module: Schema.ContextModules.ArtworkExtraLinks,
})
navigate(isSellTab ? "/collections/my-collection/marketing-landing" : "/sales")
}}
>
Consign with Artsy
</Text>
.
</Sans>
</View>
)
}
export const ArtworkExtraLinksFragmentContainer = createFragmentContainer(ArtworkExtraLinks, {
artwork: graphql`
fragment ArtworkExtraLinks_artwork on Artwork {
isAcquireable
isInAuction
isOfferable
title
isForSale
sale {
isClosed
isBenefit
partner {
name
}
}
artists {
isConsignable
name
}
artist {
name
}
}
`,
})
| ditionsOfSaleTap() {
| identifier_name |
index.tsx | import { ArtworkExtraLinks_artwork } from "__generated__/ArtworkExtraLinks_artwork.graphql"
import { AuctionTimerState } from "app/Components/Bidding/Components/Timer"
import { navigate } from "app/navigation/navigate"
import { partnerName } from "app/Scenes/Artwork/Components/ArtworkExtraLinks/partnerName"
import { useSelectedTab } from "app/store/GlobalStore"
import { sendEmail } from "app/utils/sendEmail"
import { Schema, track } from "app/utils/track"
import { Sans, Spacer } from "palette"
import React from "react"
import { Text, View } from "react-native"
import { createFragmentContainer, graphql } from "react-relay"
import { useTracking } from "react-tracking"
export interface ArtworkExtraLinksProps {
artwork: ArtworkExtraLinks_artwork
auctionState: AuctionTimerState
}
@track()
export class ArtworkExtraLinks extends React.Component<ArtworkExtraLinksProps> {
handleReadOurFAQTap = () => {
navigate(`/buy-now-feature-faq`)
}
@track({
action_name: Schema.ActionNames.AskASpecialist,
action_type: Schema.ActionTypes.Tap,
context_module: Schema.ContextModules.ArtworkExtraLinks,
})
// @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏
handleAskASpecialistTap(emailAddress) {
const { artwork } = this.props
const mailtoSubject = `Inquiry on ${artwork.title}`.concat(
artwork.artist && artwork.artist.name ? ` by ${artwork.artist.name}` : ""
)
sendEmail(emailAddress, { subject: mailtoSubject })
}
@track({
action_name: Schema.ActionNames.AuctionsFAQ,
action_type: Schema.ActionTypes.Tap,
context_module: Schema.ContextModules.ArtworkExtraLinks,
})
handleReadOurAuctionFAQsTap() {
navigate(`/auction-faq`)
return
}
@track({
action_name: Schema.ActionNames.ConditionsOfSale,
action_type: Schema.ActionTypes.Tap,
context_module: Schema.ContextModules.ArtworkExtraLinks,
})
handleConditionsOfSaleTap() {
navigate(`/conditions-of-sale`)
}
renderFAQAndSpecialist = () => {
const {
artwork: { isAcquireable, isOfferable, isInAuction, sale, isForSale },
auctionState,
} = this.props
if (isInAuction && sale && isForSale && auctionState !== AuctionTimerState.CLOSED) {
return (
<>
<Sans size="2" color="black60">
By placing a bid you agree to {partnerName(sale)}{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleConditionsOfSaleTap()}
>
Conditions of Sale
</Text> | <Spacer mb={1} />
<Sans size="2" color="black60">
Have a question?{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleReadOurAuctionFAQsTap()}
>
Read our auction FAQs
</Text>{" "}
or{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleAskASpecialistTap("specialist@artsy.net")}
>
ask a specialist
</Text>
.
</Sans>
</>
)
} else if (isAcquireable || isOfferable) {
return (
<Sans size="2" color="black60">
Have a question?{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleReadOurFAQTap()}
>
Read our FAQ
</Text>{" "}
or{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleAskASpecialistTap("orders@artsy.net")}
>
ask a specialist
</Text>
.
</Sans>
)
} else {
return null
}
}
render() {
const {
artwork: { artists },
} = this.props
// @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏
const consignableArtistsCount = artists.filter((artist) => artist.isConsignable).length
// @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏
const artistName = artists && artists.length === 1 ? artists[0].name : null
return (
<>
{this.renderFAQAndSpecialist()}
{!!consignableArtistsCount && (
<ConsignmentsLink
artistName={consignableArtistsCount > 1 ? "these artists" : artistName ?? "this artist"}
/>
)}
</>
)
}
}
const ConsignmentsLink: React.FC<{ artistName: string }> = ({ artistName }) => {
const isSellTab = useSelectedTab() === "sell"
const tracking = useTracking()
return (
<View>
<Sans size="2" color="black60">
Want to sell a work by {artistName}?{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => {
tracking.trackEvent({
action_name: Schema.ActionNames.ConsignWithArtsy,
action_type: Schema.ActionTypes.Tap,
context_module: Schema.ContextModules.ArtworkExtraLinks,
})
navigate(isSellTab ? "/collections/my-collection/marketing-landing" : "/sales")
}}
>
Consign with Artsy
</Text>
.
</Sans>
</View>
)
}
export const ArtworkExtraLinksFragmentContainer = createFragmentContainer(ArtworkExtraLinks, {
artwork: graphql`
fragment ArtworkExtraLinks_artwork on Artwork {
isAcquireable
isInAuction
isOfferable
title
isForSale
sale {
isClosed
isBenefit
partner {
name
}
}
artists {
isConsignable
name
}
artist {
name
}
}
`,
}) | .
</Sans> | random_line_split |
index.tsx | import { ArtworkExtraLinks_artwork } from "__generated__/ArtworkExtraLinks_artwork.graphql"
import { AuctionTimerState } from "app/Components/Bidding/Components/Timer"
import { navigate } from "app/navigation/navigate"
import { partnerName } from "app/Scenes/Artwork/Components/ArtworkExtraLinks/partnerName"
import { useSelectedTab } from "app/store/GlobalStore"
import { sendEmail } from "app/utils/sendEmail"
import { Schema, track } from "app/utils/track"
import { Sans, Spacer } from "palette"
import React from "react"
import { Text, View } from "react-native"
import { createFragmentContainer, graphql } from "react-relay"
import { useTracking } from "react-tracking"
export interface ArtworkExtraLinksProps {
artwork: ArtworkExtraLinks_artwork
auctionState: AuctionTimerState
}
@track()
export class ArtworkExtraLinks extends React.Component<ArtworkExtraLinksProps> {
handleReadOurFAQTap = () => {
navigate(`/buy-now-feature-faq`)
}
@track({
action_name: Schema.ActionNames.AskASpecialist,
action_type: Schema.ActionTypes.Tap,
context_module: Schema.ContextModules.ArtworkExtraLinks,
})
// @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏
handleAskASpecialistTap(emailAddress) {
const { artwork } = this.props
const mailtoSubject = `Inquiry on ${artwork.title}`.concat(
artwork.artist && artwork.artist.name ? ` by ${artwork.artist.name}` : ""
)
sendEmail(emailAddress, { subject: mailtoSubject })
}
@track({
action_name: Schema.ActionNames.AuctionsFAQ,
action_type: Schema.ActionTypes.Tap,
context_module: Schema.ContextModules.ArtworkExtraLinks,
})
handleReadOurAuctionFAQsTap() {
nav | k({
action_name: Schema.ActionNames.ConditionsOfSale,
action_type: Schema.ActionTypes.Tap,
context_module: Schema.ContextModules.ArtworkExtraLinks,
})
handleConditionsOfSaleTap() {
navigate(`/conditions-of-sale`)
}
renderFAQAndSpecialist = () => {
const {
artwork: { isAcquireable, isOfferable, isInAuction, sale, isForSale },
auctionState,
} = this.props
if (isInAuction && sale && isForSale && auctionState !== AuctionTimerState.CLOSED) {
return (
<>
<Sans size="2" color="black60">
By placing a bid you agree to {partnerName(sale)}{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleConditionsOfSaleTap()}
>
Conditions of Sale
</Text>
.
</Sans>
<Spacer mb={1} />
<Sans size="2" color="black60">
Have a question?{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleReadOurAuctionFAQsTap()}
>
Read our auction FAQs
</Text>{" "}
or{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleAskASpecialistTap("specialist@artsy.net")}
>
ask a specialist
</Text>
.
</Sans>
</>
)
} else if (isAcquireable || isOfferable) {
return (
<Sans size="2" color="black60">
Have a question?{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleReadOurFAQTap()}
>
Read our FAQ
</Text>{" "}
or{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => this.handleAskASpecialistTap("orders@artsy.net")}
>
ask a specialist
</Text>
.
</Sans>
)
} else {
return null
}
}
render() {
const {
artwork: { artists },
} = this.props
// @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏
const consignableArtistsCount = artists.filter((artist) => artist.isConsignable).length
// @ts-expect-error STRICTNESS_MIGRATION --- 🚨 Unsafe legacy code 🚨 Please delete this and fix any type errors if you have time 🙏
const artistName = artists && artists.length === 1 ? artists[0].name : null
return (
<>
{this.renderFAQAndSpecialist()}
{!!consignableArtistsCount && (
<ConsignmentsLink
artistName={consignableArtistsCount > 1 ? "these artists" : artistName ?? "this artist"}
/>
)}
</>
)
}
}
const ConsignmentsLink: React.FC<{ artistName: string }> = ({ artistName }) => {
const isSellTab = useSelectedTab() === "sell"
const tracking = useTracking()
return (
<View>
<Sans size="2" color="black60">
Want to sell a work by {artistName}?{" "}
<Text
style={{ textDecorationLine: "underline" }}
onPress={() => {
tracking.trackEvent({
action_name: Schema.ActionNames.ConsignWithArtsy,
action_type: Schema.ActionTypes.Tap,
context_module: Schema.ContextModules.ArtworkExtraLinks,
})
navigate(isSellTab ? "/collections/my-collection/marketing-landing" : "/sales")
}}
>
Consign with Artsy
</Text>
.
</Sans>
</View>
)
}
export const ArtworkExtraLinksFragmentContainer = createFragmentContainer(ArtworkExtraLinks, {
artwork: graphql`
fragment ArtworkExtraLinks_artwork on Artwork {
isAcquireable
isInAuction
isOfferable
title
isForSale
sale {
isClosed
isBenefit
partner {
name
}
}
artists {
isConsignable
name
}
artist {
name
}
}
`,
})
| igate(`/auction-faq`)
return
}
@trac | identifier_body |
test_cli20_natpool.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import logging
import sys
from gbpclient.gbp.v2_0 import groupbasedpolicy as gbp
from gbpclient.tests.unit import test_cli20
class CLITestV20NatPoolJSON(test_cli20.CLITestV20Base):
LOG = logging.getLogger(__name__)
def setUp(self):
super(CLITestV20NatPoolJSON, self).setUp()
def test_create_nat_pool_with_mandatory_params(self):
"""nat-pool-create with all mandatory params."""
resource = 'nat_pool'
cmd = gbp.CreateNatPool(test_cli20.MyApp(sys.stdout), None)
name = 'my-name'
tenant_id = 'my-tenant'
my_id = 'my-id'
args = ['--tenant-id', tenant_id,
name]
position_names = ['name', ]
position_values = [name, ]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
tenant_id=tenant_id)
def test_create_nat_pool_with_all_params(self):
"""nat-pool-create with all params."""
resource = 'nat_pool'
cmd = gbp.CreateNatPool(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
tenant_id = 'mytenant'
description = 'My Nat Pool'
my_id = 'someid'
ip_version = '4'
ip_pool = '192.168.0.0/24'
external_segment_id = "segmentid"
shared = 'true'
args = ['--tenant-id', tenant_id,
'--description', description,
'--ip-version', ip_version,
'--ip-pool', ip_pool,
'--external-segment', external_segment_id,
'--shared', shared,
name]
position_names = ['name', ]
position_values = [name, ]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
tenant_id=tenant_id,
description=description,
ip_version=4,
ip_pool=ip_pool,
external_segment_id=external_segment_id,
shared=shared)
def | (self):
"""nat-pool-list."""
resource = 'nat_pools'
cmd = gbp.ListNatPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resource, cmd, True)
def test_show_nat_pool_name(self):
"""nat-pool-show."""
resource = 'nat_pool'
cmd = gbp.ShowNatPool(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_update_nat_pool(self):
"nat-pool-update myid --name myname --tags a b."
resource = 'nat_pool'
cmd = gbp.UpdateNatPool(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'myname',
'--tags', 'a', 'b'],
{'name': 'myname', 'tags': ['a', 'b'], })
def test_update_nat_pool_with_all_params(self):
resource = 'nat_pool'
cmd = gbp.UpdateNatPool(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
description = 'My Nat Pool'
my_id = 'someid'
external_segment_id = "segmentid"
shared = 'true'
args = ['--name', name,
'--description', description,
'--external-segment', external_segment_id,
'--shared', shared,
my_id]
params = {
'name': name,
'description': description,
'external_segment_id': external_segment_id,
'shared': shared
}
self._test_update_resource(resource, cmd, my_id, args, params)
def test_delete_nat_pool_name(self):
"""nat-pool-delete."""
resource = 'nat_pool'
cmd = gbp.DeleteNatPool(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)
| test_list_nat_pools | identifier_name |
test_cli20_natpool.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import logging | from gbpclient.tests.unit import test_cli20
class CLITestV20NatPoolJSON(test_cli20.CLITestV20Base):
LOG = logging.getLogger(__name__)
def setUp(self):
super(CLITestV20NatPoolJSON, self).setUp()
def test_create_nat_pool_with_mandatory_params(self):
"""nat-pool-create with all mandatory params."""
resource = 'nat_pool'
cmd = gbp.CreateNatPool(test_cli20.MyApp(sys.stdout), None)
name = 'my-name'
tenant_id = 'my-tenant'
my_id = 'my-id'
args = ['--tenant-id', tenant_id,
name]
position_names = ['name', ]
position_values = [name, ]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
tenant_id=tenant_id)
def test_create_nat_pool_with_all_params(self):
"""nat-pool-create with all params."""
resource = 'nat_pool'
cmd = gbp.CreateNatPool(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
tenant_id = 'mytenant'
description = 'My Nat Pool'
my_id = 'someid'
ip_version = '4'
ip_pool = '192.168.0.0/24'
external_segment_id = "segmentid"
shared = 'true'
args = ['--tenant-id', tenant_id,
'--description', description,
'--ip-version', ip_version,
'--ip-pool', ip_pool,
'--external-segment', external_segment_id,
'--shared', shared,
name]
position_names = ['name', ]
position_values = [name, ]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
tenant_id=tenant_id,
description=description,
ip_version=4,
ip_pool=ip_pool,
external_segment_id=external_segment_id,
shared=shared)
def test_list_nat_pools(self):
"""nat-pool-list."""
resource = 'nat_pools'
cmd = gbp.ListNatPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resource, cmd, True)
def test_show_nat_pool_name(self):
"""nat-pool-show."""
resource = 'nat_pool'
cmd = gbp.ShowNatPool(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_update_nat_pool(self):
"nat-pool-update myid --name myname --tags a b."
resource = 'nat_pool'
cmd = gbp.UpdateNatPool(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'myname',
'--tags', 'a', 'b'],
{'name': 'myname', 'tags': ['a', 'b'], })
def test_update_nat_pool_with_all_params(self):
resource = 'nat_pool'
cmd = gbp.UpdateNatPool(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
description = 'My Nat Pool'
my_id = 'someid'
external_segment_id = "segmentid"
shared = 'true'
args = ['--name', name,
'--description', description,
'--external-segment', external_segment_id,
'--shared', shared,
my_id]
params = {
'name': name,
'description': description,
'external_segment_id': external_segment_id,
'shared': shared
}
self._test_update_resource(resource, cmd, my_id, args, params)
def test_delete_nat_pool_name(self):
"""nat-pool-delete."""
resource = 'nat_pool'
cmd = gbp.DeleteNatPool(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args) | import sys
from gbpclient.gbp.v2_0 import groupbasedpolicy as gbp | random_line_split |
test_cli20_natpool.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import logging
import sys
from gbpclient.gbp.v2_0 import groupbasedpolicy as gbp
from gbpclient.tests.unit import test_cli20
class CLITestV20NatPoolJSON(test_cli20.CLITestV20Base):
LOG = logging.getLogger(__name__)
def setUp(self):
super(CLITestV20NatPoolJSON, self).setUp()
def test_create_nat_pool_with_mandatory_params(self):
"""nat-pool-create with all mandatory params."""
resource = 'nat_pool'
cmd = gbp.CreateNatPool(test_cli20.MyApp(sys.stdout), None)
name = 'my-name'
tenant_id = 'my-tenant'
my_id = 'my-id'
args = ['--tenant-id', tenant_id,
name]
position_names = ['name', ]
position_values = [name, ]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
tenant_id=tenant_id)
def test_create_nat_pool_with_all_params(self):
"""nat-pool-create with all params."""
resource = 'nat_pool'
cmd = gbp.CreateNatPool(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
tenant_id = 'mytenant'
description = 'My Nat Pool'
my_id = 'someid'
ip_version = '4'
ip_pool = '192.168.0.0/24'
external_segment_id = "segmentid"
shared = 'true'
args = ['--tenant-id', tenant_id,
'--description', description,
'--ip-version', ip_version,
'--ip-pool', ip_pool,
'--external-segment', external_segment_id,
'--shared', shared,
name]
position_names = ['name', ]
position_values = [name, ]
self._test_create_resource(resource, cmd, name, my_id, args,
position_names, position_values,
tenant_id=tenant_id,
description=description,
ip_version=4,
ip_pool=ip_pool,
external_segment_id=external_segment_id,
shared=shared)
def test_list_nat_pools(self):
|
def test_show_nat_pool_name(self):
"""nat-pool-show."""
resource = 'nat_pool'
cmd = gbp.ShowNatPool(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', self.test_id]
self._test_show_resource(resource, cmd, self.test_id, args, ['id'])
def test_update_nat_pool(self):
"nat-pool-update myid --name myname --tags a b."
resource = 'nat_pool'
cmd = gbp.UpdateNatPool(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'myname',
'--tags', 'a', 'b'],
{'name': 'myname', 'tags': ['a', 'b'], })
def test_update_nat_pool_with_all_params(self):
resource = 'nat_pool'
cmd = gbp.UpdateNatPool(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
description = 'My Nat Pool'
my_id = 'someid'
external_segment_id = "segmentid"
shared = 'true'
args = ['--name', name,
'--description', description,
'--external-segment', external_segment_id,
'--shared', shared,
my_id]
params = {
'name': name,
'description': description,
'external_segment_id': external_segment_id,
'shared': shared
}
self._test_update_resource(resource, cmd, my_id, args, params)
def test_delete_nat_pool_name(self):
"""nat-pool-delete."""
resource = 'nat_pool'
cmd = gbp.DeleteNatPool(test_cli20.MyApp(sys.stdout), None)
my_id = 'my-id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)
| """nat-pool-list."""
resource = 'nat_pools'
cmd = gbp.ListNatPool(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resource, cmd, True) | identifier_body |
depend.js | import { hyphen } from './utils';
/**
* 依赖
*/
export let devDependencies = [];
/**
* 添加依赖
* @param {array|string} dependencies 依赖
*/
export function addDependency(dependencies){
if ( !Array.isArray(dependencies) ){
dependencies = [dependencies];
};
dependencies.map(dependency => {
if ( devDependencies.indexOf(dependency) === -1 ){
devDependencies.push(dependency);
};
});
};
/**
* 移除依赖
* @param {array|string} dependencies 依赖
*/
export function removeDependency(dependencies){
if ( !Array.isArray(dependencies) ){
dependencies = [dependencies];
};
dependencies.map(dependency => {
devDependencies = devDependencies.filter(depend => depend !== dependency);
});
};
export function transformDependencyName(name){
name = name.replace(/_(?=[\d])/g, () => '-')
.replace(/_(?=[^\d])/g, () => ''); | return hyphen(name);
}; | random_line_split | |
depend.js | import { hyphen } from './utils';
/**
* 依赖
*/
export let devDependencies = [];
/**
* 添加依赖
* @param {array|string} dependencies 依赖
*/
export function addDependency(dependencies){
if ( !Array.isArray(dependencies) ){
dependenci | s.map(dependency => {
if ( devDependencies.indexOf(dependency) === -1 ){
devDependencies.push(dependency);
};
});
};
/**
* 移除依赖
* @param {array|string} dependencies 依赖
*/
export function removeDependency(dependencies){
if ( !Array.isArray(dependencies) ){
dependencies = [dependencies];
};
dependencies.map(dependency => {
devDependencies = devDependencies.filter(depend => depend !== dependency);
});
};
export function transformDependencyName(name){
name = name.replace(/_(?=[\d])/g, () => '-')
.replace(/_(?=[^\d])/g, () => '');
return hyphen(name);
}; | es = [dependencies];
};
dependencie | conditional_block |
depend.js | import { hyphen } from './utils';
/**
* 依赖
*/
export let devDependencies = [];
/**
* 添加依赖
* @param {array|string} dependencies 依赖
*/
export function addDependency(dependencies){
if ( !Array.isArray(dependencies) ){
dependencies = [dependencies];
};
dependencies.map(dependency => {
if ( devDependencies.indexOf(dependency) === -1 ){
devDependencies.push(dependency);
};
});
};
/**
* 移除依赖
* @param {array|string} dependencies 依赖
*/
export function removeDependency(dependencies){
if ( !Array.isArray(dependencies) ){
dependencies = [dependencies];
};
dependencies.map(dependency => {
devDependencies = devDependencies.filter(depend => depend !== dependency);
});
};
export function transformDependencyName(name){
name = name.replace(/_(? | =[\d])/g, () => '-')
.replace(/_(?=[^\d])/g, () => '');
return hyphen(name);
}; | identifier_body | |
depend.js | import { hyphen } from './utils';
/**
* 依赖
*/
export let devDependencies = [];
/**
* 添加依赖
* @param {array|string} dependencies 依赖
*/
export function addDependency(de | if ( !Array.isArray(dependencies) ){
dependencies = [dependencies];
};
dependencies.map(dependency => {
if ( devDependencies.indexOf(dependency) === -1 ){
devDependencies.push(dependency);
};
});
};
/**
* 移除依赖
* @param {array|string} dependencies 依赖
*/
export function removeDependency(dependencies){
if ( !Array.isArray(dependencies) ){
dependencies = [dependencies];
};
dependencies.map(dependency => {
devDependencies = devDependencies.filter(depend => depend !== dependency);
});
};
export function transformDependencyName(name){
name = name.replace(/_(?=[\d])/g, () => '-')
.replace(/_(?=[^\d])/g, () => '');
return hyphen(name);
}; | pendencies){
| identifier_name |
__init__.py | """Support for Peewee ORM (https://github.com/coleifer/peewee)."""
from __future__ import annotations
import typing as t
import marshmallow as ma
import muffin
import peewee as pw
from apispec.ext.marshmallow import MarshmallowPlugin
from marshmallow_peewee import ForeignKey, ModelSchema
from muffin.typing import JSONType
from peewee_aio import Manager, Model
from muffin_rest.errors import APIError
from muffin_rest.handler import RESTBase, RESTOptions
from muffin_rest.peewee.filters import PWFilters
from muffin_rest.peewee.openapi import PeeweeOpenAPIMixin
from muffin_rest.peewee.sorting import PWSorting
# XXX: Patch apispec.MarshmallowPlugin to support ForeignKeyField
MarshmallowPlugin.Converter.field_mapping[ForeignKey] = ("integer", None)
class PWRESTOptions(RESTOptions):
"""Support Peewee."""
model: t.Type[pw.Model]
model_pk: t.Optional[pw.Field] = None
manager: Manager
# Base filters class
filters_cls: t.Type[PWFilters] = PWFilters
# Base sorting class
sorting_cls: t.Type[PWSorting] = PWSorting
Schema: t.Type[ModelSchema]
# Schema auto generation params
schema_base: t.Type[ModelSchema] = ModelSchema
# Recursive delete
delete_recursive = False
base_property: str = "model"
def setup(self, cls):
"""Prepare meta options."""
self.name = self.name or self.model._meta.table_name.lower()
self.model_pk = self.model_pk or self.model._meta.primary_key
manager = getattr(self, "manager", getattr(self.model, "_manager", None))
if manager is None:
raise RuntimeError("Peewee-AIO ORM Manager is not available")
self.manager = manager
super().setup(cls)
def setup_schema_meta(self, _):
"""Prepare a schema."""
return type(
"Meta",
(object,),
dict(
{"unknown": self.schema_unknown, "model": self.model},
**self.schema_meta,
),
)
class PWRESTBase(RESTBase):
"""Support Peeweee."""
collection: pw.Query
resource: pw.Model
meta: PWRESTOptions
meta_class: t.Type[PWRESTOptions] = PWRESTOptions
async def prepare_collection(self, _: muffin.Request) -> pw.Query:
"""Initialize Peeewee QuerySet for a binded to the resource model."""
return self.meta.model.select()
async def prepare_resource(self, request: muffin.Request) -> t.Optional[pw.Model]:
"""Load a resource."""
pk = request["path_params"].get(self.meta.name_id)
if not pk:
return None
meta = self.meta
resource = await meta.manager.fetchone(
self.collection.where(meta.model_pk == pk)
)
if resource is None:
raise APIError.NOT_FOUND("Resource not found")
return resource
async def paginate(
self, _: muffin.Request, *, limit: int = 0, offset: int = 0
) -> t.Tuple[pw.Query, int]:
"""Paginate the collection."""
cqs: pw.Select = self.collection.order_by() # type: ignore
if cqs._group_by:
|
count = await self.meta.manager.count(cqs)
return self.collection.offset(offset).limit(limit), count # type: ignore
async def get(self, request, *, resource=None) -> JSONType:
"""Get resource or collection of resources."""
if resource is not None and resource != "":
return await self.dump(request, resource, many=False)
resources = await self.meta.manager.fetchall(self.collection)
return await self.dump(request, resources, many=True)
async def save(self, _: muffin.Request, resource: pw.Model) -> pw.Model:
"""Save the given resource."""
meta = self.meta
if issubclass(meta.model, Model):
await resource.save()
else:
await meta.manager.save(resource)
return resource
async def remove(self, request: muffin.Request, *, resource: pw.Model = None):
"""Remove the given resource."""
meta = self.meta
if resource:
resources = [resource]
else:
data = await request.data()
if not data:
return
model_pk = t.cast(pw.Field, meta.model_pk)
resources = await meta.manager.fetchall(
self.collection.where(model_pk << data)
)
if not resources:
raise APIError.NOT_FOUND()
delete_instance = meta.manager.delete_instance
if issubclass(meta.model, Model):
delete_instance = lambda m: m.delete_instance(recursive=meta.delete_recursive) # type: ignore # noqa
for res in resources:
await delete_instance(res)
delete = remove # noqa
async def get_schema(
self, request: muffin.Request, resource=None, **_
) -> ma.Schema:
"""Initialize marshmallow schema for serialization/deserialization."""
return self.meta.Schema(
instance=resource,
only=request.url.query.get("schema_only"),
exclude=request.url.query.get("schema_exclude", ()),
)
class PWRESTHandler(PWRESTBase, PeeweeOpenAPIMixin): # type: ignore
"""Support peewee."""
pass
| cqs._returning = cqs._group_by | conditional_block |
__init__.py | """Support for Peewee ORM (https://github.com/coleifer/peewee)."""
from __future__ import annotations
import typing as t
import marshmallow as ma
import muffin
import peewee as pw
from apispec.ext.marshmallow import MarshmallowPlugin
from marshmallow_peewee import ForeignKey, ModelSchema
from muffin.typing import JSONType
from peewee_aio import Manager, Model
from muffin_rest.errors import APIError
from muffin_rest.handler import RESTBase, RESTOptions
from muffin_rest.peewee.filters import PWFilters
from muffin_rest.peewee.openapi import PeeweeOpenAPIMixin
from muffin_rest.peewee.sorting import PWSorting
# XXX: Patch apispec.MarshmallowPlugin to support ForeignKeyField
MarshmallowPlugin.Converter.field_mapping[ForeignKey] = ("integer", None)
class PWRESTOptions(RESTOptions):
"""Support Peewee."""
model: t.Type[pw.Model]
model_pk: t.Optional[pw.Field] = None
manager: Manager
# Base filters class
filters_cls: t.Type[PWFilters] = PWFilters
# Base sorting class
sorting_cls: t.Type[PWSorting] = PWSorting
Schema: t.Type[ModelSchema]
# Schema auto generation params
schema_base: t.Type[ModelSchema] = ModelSchema
# Recursive delete
delete_recursive = False
base_property: str = "model"
def setup(self, cls):
"""Prepare meta options."""
self.name = self.name or self.model._meta.table_name.lower()
self.model_pk = self.model_pk or self.model._meta.primary_key
manager = getattr(self, "manager", getattr(self.model, "_manager", None))
if manager is None:
raise RuntimeError("Peewee-AIO ORM Manager is not available")
self.manager = manager
super().setup(cls)
def setup_schema_meta(self, _):
"""Prepare a schema."""
return type(
"Meta",
(object,),
dict(
{"unknown": self.schema_unknown, "model": self.model},
**self.schema_meta,
),
)
class PWRESTBase(RESTBase):
"""Support Peeweee."""
collection: pw.Query
resource: pw.Model
meta: PWRESTOptions
meta_class: t.Type[PWRESTOptions] = PWRESTOptions
async def prepare_collection(self, _: muffin.Request) -> pw.Query:
"""Initialize Peeewee QuerySet for a binded to the resource model."""
return self.meta.model.select()
async def prepare_resource(self, request: muffin.Request) -> t.Optional[pw.Model]:
"""Load a resource."""
pk = request["path_params"].get(self.meta.name_id)
if not pk:
return None
meta = self.meta
resource = await meta.manager.fetchone(
self.collection.where(meta.model_pk == pk)
)
if resource is None:
raise APIError.NOT_FOUND("Resource not found")
return resource
async def paginate(
self, _: muffin.Request, *, limit: int = 0, offset: int = 0
) -> t.Tuple[pw.Query, int]:
|
async def get(self, request, *, resource=None) -> JSONType:
"""Get resource or collection of resources."""
if resource is not None and resource != "":
return await self.dump(request, resource, many=False)
resources = await self.meta.manager.fetchall(self.collection)
return await self.dump(request, resources, many=True)
async def save(self, _: muffin.Request, resource: pw.Model) -> pw.Model:
"""Save the given resource."""
meta = self.meta
if issubclass(meta.model, Model):
await resource.save()
else:
await meta.manager.save(resource)
return resource
async def remove(self, request: muffin.Request, *, resource: pw.Model = None):
"""Remove the given resource."""
meta = self.meta
if resource:
resources = [resource]
else:
data = await request.data()
if not data:
return
model_pk = t.cast(pw.Field, meta.model_pk)
resources = await meta.manager.fetchall(
self.collection.where(model_pk << data)
)
if not resources:
raise APIError.NOT_FOUND()
delete_instance = meta.manager.delete_instance
if issubclass(meta.model, Model):
delete_instance = lambda m: m.delete_instance(recursive=meta.delete_recursive) # type: ignore # noqa
for res in resources:
await delete_instance(res)
delete = remove # noqa
async def get_schema(
self, request: muffin.Request, resource=None, **_
) -> ma.Schema:
"""Initialize marshmallow schema for serialization/deserialization."""
return self.meta.Schema(
instance=resource,
only=request.url.query.get("schema_only"),
exclude=request.url.query.get("schema_exclude", ()),
)
class PWRESTHandler(PWRESTBase, PeeweeOpenAPIMixin): # type: ignore
"""Support peewee."""
pass
| """Paginate the collection."""
cqs: pw.Select = self.collection.order_by() # type: ignore
if cqs._group_by:
cqs._returning = cqs._group_by
count = await self.meta.manager.count(cqs)
return self.collection.offset(offset).limit(limit), count # type: ignore | identifier_body |
__init__.py | """Support for Peewee ORM (https://github.com/coleifer/peewee)."""
from __future__ import annotations
import typing as t
import marshmallow as ma
import muffin
import peewee as pw
from apispec.ext.marshmallow import MarshmallowPlugin
from marshmallow_peewee import ForeignKey, ModelSchema
from muffin.typing import JSONType
from peewee_aio import Manager, Model
from muffin_rest.errors import APIError
from muffin_rest.handler import RESTBase, RESTOptions
from muffin_rest.peewee.filters import PWFilters |
# XXX: Patch apispec.MarshmallowPlugin to support ForeignKeyField
MarshmallowPlugin.Converter.field_mapping[ForeignKey] = ("integer", None)
class PWRESTOptions(RESTOptions):
"""Support Peewee."""
model: t.Type[pw.Model]
model_pk: t.Optional[pw.Field] = None
manager: Manager
# Base filters class
filters_cls: t.Type[PWFilters] = PWFilters
# Base sorting class
sorting_cls: t.Type[PWSorting] = PWSorting
Schema: t.Type[ModelSchema]
# Schema auto generation params
schema_base: t.Type[ModelSchema] = ModelSchema
# Recursive delete
delete_recursive = False
base_property: str = "model"
def setup(self, cls):
"""Prepare meta options."""
self.name = self.name or self.model._meta.table_name.lower()
self.model_pk = self.model_pk or self.model._meta.primary_key
manager = getattr(self, "manager", getattr(self.model, "_manager", None))
if manager is None:
raise RuntimeError("Peewee-AIO ORM Manager is not available")
self.manager = manager
super().setup(cls)
def setup_schema_meta(self, _):
"""Prepare a schema."""
return type(
"Meta",
(object,),
dict(
{"unknown": self.schema_unknown, "model": self.model},
**self.schema_meta,
),
)
class PWRESTBase(RESTBase):
"""Support Peeweee."""
collection: pw.Query
resource: pw.Model
meta: PWRESTOptions
meta_class: t.Type[PWRESTOptions] = PWRESTOptions
async def prepare_collection(self, _: muffin.Request) -> pw.Query:
"""Initialize Peeewee QuerySet for a binded to the resource model."""
return self.meta.model.select()
async def prepare_resource(self, request: muffin.Request) -> t.Optional[pw.Model]:
"""Load a resource."""
pk = request["path_params"].get(self.meta.name_id)
if not pk:
return None
meta = self.meta
resource = await meta.manager.fetchone(
self.collection.where(meta.model_pk == pk)
)
if resource is None:
raise APIError.NOT_FOUND("Resource not found")
return resource
async def paginate(
self, _: muffin.Request, *, limit: int = 0, offset: int = 0
) -> t.Tuple[pw.Query, int]:
"""Paginate the collection."""
cqs: pw.Select = self.collection.order_by() # type: ignore
if cqs._group_by:
cqs._returning = cqs._group_by
count = await self.meta.manager.count(cqs)
return self.collection.offset(offset).limit(limit), count # type: ignore
async def get(self, request, *, resource=None) -> JSONType:
"""Get resource or collection of resources."""
if resource is not None and resource != "":
return await self.dump(request, resource, many=False)
resources = await self.meta.manager.fetchall(self.collection)
return await self.dump(request, resources, many=True)
async def save(self, _: muffin.Request, resource: pw.Model) -> pw.Model:
"""Save the given resource."""
meta = self.meta
if issubclass(meta.model, Model):
await resource.save()
else:
await meta.manager.save(resource)
return resource
async def remove(self, request: muffin.Request, *, resource: pw.Model = None):
"""Remove the given resource."""
meta = self.meta
if resource:
resources = [resource]
else:
data = await request.data()
if not data:
return
model_pk = t.cast(pw.Field, meta.model_pk)
resources = await meta.manager.fetchall(
self.collection.where(model_pk << data)
)
if not resources:
raise APIError.NOT_FOUND()
delete_instance = meta.manager.delete_instance
if issubclass(meta.model, Model):
delete_instance = lambda m: m.delete_instance(recursive=meta.delete_recursive) # type: ignore # noqa
for res in resources:
await delete_instance(res)
delete = remove # noqa
async def get_schema(
self, request: muffin.Request, resource=None, **_
) -> ma.Schema:
"""Initialize marshmallow schema for serialization/deserialization."""
return self.meta.Schema(
instance=resource,
only=request.url.query.get("schema_only"),
exclude=request.url.query.get("schema_exclude", ()),
)
class PWRESTHandler(PWRESTBase, PeeweeOpenAPIMixin): # type: ignore
"""Support peewee."""
pass | from muffin_rest.peewee.openapi import PeeweeOpenAPIMixin
from muffin_rest.peewee.sorting import PWSorting | random_line_split |
__init__.py | """Support for Peewee ORM (https://github.com/coleifer/peewee)."""
from __future__ import annotations
import typing as t
import marshmallow as ma
import muffin
import peewee as pw
from apispec.ext.marshmallow import MarshmallowPlugin
from marshmallow_peewee import ForeignKey, ModelSchema
from muffin.typing import JSONType
from peewee_aio import Manager, Model
from muffin_rest.errors import APIError
from muffin_rest.handler import RESTBase, RESTOptions
from muffin_rest.peewee.filters import PWFilters
from muffin_rest.peewee.openapi import PeeweeOpenAPIMixin
from muffin_rest.peewee.sorting import PWSorting
# XXX: Patch apispec.MarshmallowPlugin to support ForeignKeyField
MarshmallowPlugin.Converter.field_mapping[ForeignKey] = ("integer", None)
class PWRESTOptions(RESTOptions):
"""Support Peewee."""
model: t.Type[pw.Model]
model_pk: t.Optional[pw.Field] = None
manager: Manager
# Base filters class
filters_cls: t.Type[PWFilters] = PWFilters
# Base sorting class
sorting_cls: t.Type[PWSorting] = PWSorting
Schema: t.Type[ModelSchema]
# Schema auto generation params
schema_base: t.Type[ModelSchema] = ModelSchema
# Recursive delete
delete_recursive = False
base_property: str = "model"
def setup(self, cls):
"""Prepare meta options."""
self.name = self.name or self.model._meta.table_name.lower()
self.model_pk = self.model_pk or self.model._meta.primary_key
manager = getattr(self, "manager", getattr(self.model, "_manager", None))
if manager is None:
raise RuntimeError("Peewee-AIO ORM Manager is not available")
self.manager = manager
super().setup(cls)
def setup_schema_meta(self, _):
"""Prepare a schema."""
return type(
"Meta",
(object,),
dict(
{"unknown": self.schema_unknown, "model": self.model},
**self.schema_meta,
),
)
class PWRESTBase(RESTBase):
"""Support Peeweee."""
collection: pw.Query
resource: pw.Model
meta: PWRESTOptions
meta_class: t.Type[PWRESTOptions] = PWRESTOptions
async def prepare_collection(self, _: muffin.Request) -> pw.Query:
"""Initialize Peeewee QuerySet for a binded to the resource model."""
return self.meta.model.select()
async def prepare_resource(self, request: muffin.Request) -> t.Optional[pw.Model]:
"""Load a resource."""
pk = request["path_params"].get(self.meta.name_id)
if not pk:
return None
meta = self.meta
resource = await meta.manager.fetchone(
self.collection.where(meta.model_pk == pk)
)
if resource is None:
raise APIError.NOT_FOUND("Resource not found")
return resource
async def paginate(
self, _: muffin.Request, *, limit: int = 0, offset: int = 0
) -> t.Tuple[pw.Query, int]:
"""Paginate the collection."""
cqs: pw.Select = self.collection.order_by() # type: ignore
if cqs._group_by:
cqs._returning = cqs._group_by
count = await self.meta.manager.count(cqs)
return self.collection.offset(offset).limit(limit), count # type: ignore
async def | (self, request, *, resource=None) -> JSONType:
"""Get resource or collection of resources."""
if resource is not None and resource != "":
return await self.dump(request, resource, many=False)
resources = await self.meta.manager.fetchall(self.collection)
return await self.dump(request, resources, many=True)
async def save(self, _: muffin.Request, resource: pw.Model) -> pw.Model:
"""Save the given resource."""
meta = self.meta
if issubclass(meta.model, Model):
await resource.save()
else:
await meta.manager.save(resource)
return resource
async def remove(self, request: muffin.Request, *, resource: pw.Model = None):
"""Remove the given resource."""
meta = self.meta
if resource:
resources = [resource]
else:
data = await request.data()
if not data:
return
model_pk = t.cast(pw.Field, meta.model_pk)
resources = await meta.manager.fetchall(
self.collection.where(model_pk << data)
)
if not resources:
raise APIError.NOT_FOUND()
delete_instance = meta.manager.delete_instance
if issubclass(meta.model, Model):
delete_instance = lambda m: m.delete_instance(recursive=meta.delete_recursive) # type: ignore # noqa
for res in resources:
await delete_instance(res)
delete = remove # noqa
async def get_schema(
self, request: muffin.Request, resource=None, **_
) -> ma.Schema:
"""Initialize marshmallow schema for serialization/deserialization."""
return self.meta.Schema(
instance=resource,
only=request.url.query.get("schema_only"),
exclude=request.url.query.get("schema_exclude", ()),
)
class PWRESTHandler(PWRESTBase, PeeweeOpenAPIMixin): # type: ignore
"""Support peewee."""
pass
| get | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
# Copyright(C) 2016 Edouard Lambert
#
# This file is part of a weboob module.
#
# This weboob module is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# | # This weboob module 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 weboob module. If not, see <http://www.gnu.org/licenses/>.
from .module import BinckModule
__all__ = ['BinckModule'] | random_line_split | |
color.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Color", inherited=True) %>
<% from data import to_rust_ident %>
<%helpers:longhand name="color" need_clone="True" animatable="True"
spec="https://drafts.csswg.org/css-color/#color">
use cssparser::RGBA;
use std::fmt;
use style_traits::ToCss;
use values::HasViewportPercentage;
use values::specified::{Color, CSSColor, CSSRGBA};
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, context: &Context) -> computed_value::T {
self.0.parsed.to_computed_value(context)
}
#[inline]
fn from_computed_value(computed: &computed_value::T) -> Self {
SpecifiedValue(CSSColor {
parsed: Color::RGBA(*computed),
authored: None,
})
}
}
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct SpecifiedValue(pub CSSColor);
no_viewport_percentage!(SpecifiedValue);
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
self.0.to_css(dest)
}
}
pub mod computed_value {
use cssparser;
pub type T = cssparser::RGBA;
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
RGBA::new(0, 0, 0, 255) // black
}
pub fn | (context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
CSSColor::parse(context, input).map(SpecifiedValue)
}
// FIXME(#15973): Add servo support for system colors
% if product == "gecko":
<%
# These are actually parsed. See nsCSSProps::kColorKTable
system_colors = """activeborder activecaption appworkspace background buttonface
buttonhighlight buttonshadow buttontext captiontext graytext highlight
highlighttext inactiveborder inactivecaption inactivecaptiontext
infobackground infotext menu menutext scrollbar threeddarkshadow
threedface threedhighlight threedlightshadow threedshadow window
windowframe windowtext -moz-buttondefault -moz-buttonhoverface
-moz-buttonhovertext -moz-cellhighlight -moz-cellhighlighttext
-moz-eventreerow -moz-field -moz-fieldtext -moz-dialog -moz-dialogtext
-moz-dragtargetzone -moz-gtk-info-bar-text -moz-html-cellhighlight
-moz-html-cellhighlighttext -moz-mac-buttonactivetext
-moz-mac-chrome-active -moz-mac-chrome-inactive
-moz-mac-defaultbuttontext -moz-mac-focusring -moz-mac-menuselect
-moz-mac-menushadow -moz-mac-menutextdisable -moz-mac-menutextselect
-moz-mac-disabledtoolbartext -moz-mac-secondaryhighlight
-moz-menuhover -moz-menuhovertext -moz-menubartext -moz-menubarhovertext
-moz-oddtreerow -moz-win-mediatext -moz-win-communicationstext
-moz-nativehyperlinktext -moz-comboboxtext -moz-combobox""".split()
# These are not parsed but must be serialized
# They are only ever set directly by Gecko
extra_colors = """WindowBackground WindowForeground WidgetBackground WidgetForeground
WidgetSelectBackground WidgetSelectForeground Widget3DHighlight Widget3DShadow
TextBackground TextForeground TextSelectBackground TextSelectForeground
TextSelectForegroundCustom TextSelectBackgroundDisabled TextSelectBackgroundAttention
TextHighlightBackground TextHighlightForeground IMERawInputBackground
IMERawInputForeground IMERawInputUnderline IMESelectedRawTextBackground
IMESelectedRawTextForeground IMESelectedRawTextUnderline
IMEConvertedTextBackground IMEConvertedTextForeground IMEConvertedTextUnderline
IMESelectedConvertedTextBackground IMESelectedConvertedTextForeground
IMESelectedConvertedTextUnderline SpellCheckerUnderline""".split()
%>
use gecko_bindings::bindings::Gecko_GetLookAndFeelSystemColor;
use gecko_bindings::structs::root::mozilla::LookAndFeel_ColorID;
pub type SystemColor = LookAndFeel_ColorID;
impl ToCss for SystemColor {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let s = match *self {
% for color in system_colors + extra_colors:
LookAndFeel_ColorID::eColorID_${to_rust_ident(color)} => "${color}",
% endfor
LookAndFeel_ColorID::eColorID_LAST_COLOR => unreachable!(),
};
dest.write_str(s)
}
}
impl ToComputedValue for SystemColor {
type ComputedValue = u32; // nscolor
#[inline]
fn to_computed_value(&self, cx: &Context) -> Self::ComputedValue {
unsafe {
Gecko_GetLookAndFeelSystemColor(*self as i32,
&*cx.device.pres_context)
}
}
#[inline]
fn from_computed_value(_: &Self::ComputedValue) -> Self {
unreachable!()
}
}
impl SystemColor {
pub fn parse(input: &mut Parser) -> Result<Self, ()> {
use std::ascii::AsciiExt;
static PARSE_ARRAY: &'static [(&'static str, SystemColor); ${len(system_colors)}] = &[
% for color in system_colors:
("${color}", LookAndFeel_ColorID::eColorID_${to_rust_ident(color)}),
% endfor
];
let ident = input.expect_ident()?;
for &(name, color) in PARSE_ARRAY.iter() {
if name.eq_ignore_ascii_case(&ident) {
return Ok(color)
}
}
Err(())
}
}
% endif
</%helpers:longhand>
| parse | identifier_name |
color.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Color", inherited=True) %>
<% from data import to_rust_ident %>
<%helpers:longhand name="color" need_clone="True" animatable="True"
spec="https://drafts.csswg.org/css-color/#color">
use cssparser::RGBA;
use std::fmt;
use style_traits::ToCss;
use values::HasViewportPercentage;
use values::specified::{Color, CSSColor, CSSRGBA};
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, context: &Context) -> computed_value::T {
self.0.parsed.to_computed_value(context)
}
#[inline]
fn from_computed_value(computed: &computed_value::T) -> Self {
SpecifiedValue(CSSColor {
parsed: Color::RGBA(*computed),
authored: None,
})
}
}
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct SpecifiedValue(pub CSSColor);
no_viewport_percentage!(SpecifiedValue);
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write |
}
pub mod computed_value {
use cssparser;
pub type T = cssparser::RGBA;
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
RGBA::new(0, 0, 0, 255) // black
}
pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
CSSColor::parse(context, input).map(SpecifiedValue)
}
// FIXME(#15973): Add servo support for system colors
% if product == "gecko":
<%
# These are actually parsed. See nsCSSProps::kColorKTable
system_colors = """activeborder activecaption appworkspace background buttonface
buttonhighlight buttonshadow buttontext captiontext graytext highlight
highlighttext inactiveborder inactivecaption inactivecaptiontext
infobackground infotext menu menutext scrollbar threeddarkshadow
threedface threedhighlight threedlightshadow threedshadow window
windowframe windowtext -moz-buttondefault -moz-buttonhoverface
-moz-buttonhovertext -moz-cellhighlight -moz-cellhighlighttext
-moz-eventreerow -moz-field -moz-fieldtext -moz-dialog -moz-dialogtext
-moz-dragtargetzone -moz-gtk-info-bar-text -moz-html-cellhighlight
-moz-html-cellhighlighttext -moz-mac-buttonactivetext
-moz-mac-chrome-active -moz-mac-chrome-inactive
-moz-mac-defaultbuttontext -moz-mac-focusring -moz-mac-menuselect
-moz-mac-menushadow -moz-mac-menutextdisable -moz-mac-menutextselect
-moz-mac-disabledtoolbartext -moz-mac-secondaryhighlight
-moz-menuhover -moz-menuhovertext -moz-menubartext -moz-menubarhovertext
-moz-oddtreerow -moz-win-mediatext -moz-win-communicationstext
-moz-nativehyperlinktext -moz-comboboxtext -moz-combobox""".split()
# These are not parsed but must be serialized
# They are only ever set directly by Gecko
extra_colors = """WindowBackground WindowForeground WidgetBackground WidgetForeground
WidgetSelectBackground WidgetSelectForeground Widget3DHighlight Widget3DShadow
TextBackground TextForeground TextSelectBackground TextSelectForeground
TextSelectForegroundCustom TextSelectBackgroundDisabled TextSelectBackgroundAttention
TextHighlightBackground TextHighlightForeground IMERawInputBackground
IMERawInputForeground IMERawInputUnderline IMESelectedRawTextBackground
IMESelectedRawTextForeground IMESelectedRawTextUnderline
IMEConvertedTextBackground IMEConvertedTextForeground IMEConvertedTextUnderline
IMESelectedConvertedTextBackground IMESelectedConvertedTextForeground
IMESelectedConvertedTextUnderline SpellCheckerUnderline""".split()
%>
use gecko_bindings::bindings::Gecko_GetLookAndFeelSystemColor;
use gecko_bindings::structs::root::mozilla::LookAndFeel_ColorID;
pub type SystemColor = LookAndFeel_ColorID;
impl ToCss for SystemColor {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let s = match *self {
% for color in system_colors + extra_colors:
LookAndFeel_ColorID::eColorID_${to_rust_ident(color)} => "${color}",
% endfor
LookAndFeel_ColorID::eColorID_LAST_COLOR => unreachable!(),
};
dest.write_str(s)
}
}
impl ToComputedValue for SystemColor {
type ComputedValue = u32; // nscolor
#[inline]
fn to_computed_value(&self, cx: &Context) -> Self::ComputedValue {
unsafe {
Gecko_GetLookAndFeelSystemColor(*self as i32,
&*cx.device.pres_context)
}
}
#[inline]
fn from_computed_value(_: &Self::ComputedValue) -> Self {
unreachable!()
}
}
impl SystemColor {
pub fn parse(input: &mut Parser) -> Result<Self, ()> {
use std::ascii::AsciiExt;
static PARSE_ARRAY: &'static [(&'static str, SystemColor); ${len(system_colors)}] = &[
% for color in system_colors:
("${color}", LookAndFeel_ColorID::eColorID_${to_rust_ident(color)}),
% endfor
];
let ident = input.expect_ident()?;
for &(name, color) in PARSE_ARRAY.iter() {
if name.eq_ignore_ascii_case(&ident) {
return Ok(color)
}
}
Err(())
}
}
% endif
</%helpers:longhand>
| {
self.0.to_css(dest)
} | identifier_body |
color.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Color", inherited=True) %>
<% from data import to_rust_ident %>
<%helpers:longhand name="color" need_clone="True" animatable="True"
spec="https://drafts.csswg.org/css-color/#color">
use cssparser::RGBA;
use std::fmt;
use style_traits::ToCss;
use values::HasViewportPercentage;
use values::specified::{Color, CSSColor, CSSRGBA};
impl ToComputedValue for SpecifiedValue { | #[inline]
fn to_computed_value(&self, context: &Context) -> computed_value::T {
self.0.parsed.to_computed_value(context)
}
#[inline]
fn from_computed_value(computed: &computed_value::T) -> Self {
SpecifiedValue(CSSColor {
parsed: Color::RGBA(*computed),
authored: None,
})
}
}
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct SpecifiedValue(pub CSSColor);
no_viewport_percentage!(SpecifiedValue);
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
self.0.to_css(dest)
}
}
pub mod computed_value {
use cssparser;
pub type T = cssparser::RGBA;
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
RGBA::new(0, 0, 0, 255) // black
}
pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
CSSColor::parse(context, input).map(SpecifiedValue)
}
// FIXME(#15973): Add servo support for system colors
% if product == "gecko":
<%
# These are actually parsed. See nsCSSProps::kColorKTable
system_colors = """activeborder activecaption appworkspace background buttonface
buttonhighlight buttonshadow buttontext captiontext graytext highlight
highlighttext inactiveborder inactivecaption inactivecaptiontext
infobackground infotext menu menutext scrollbar threeddarkshadow
threedface threedhighlight threedlightshadow threedshadow window
windowframe windowtext -moz-buttondefault -moz-buttonhoverface
-moz-buttonhovertext -moz-cellhighlight -moz-cellhighlighttext
-moz-eventreerow -moz-field -moz-fieldtext -moz-dialog -moz-dialogtext
-moz-dragtargetzone -moz-gtk-info-bar-text -moz-html-cellhighlight
-moz-html-cellhighlighttext -moz-mac-buttonactivetext
-moz-mac-chrome-active -moz-mac-chrome-inactive
-moz-mac-defaultbuttontext -moz-mac-focusring -moz-mac-menuselect
-moz-mac-menushadow -moz-mac-menutextdisable -moz-mac-menutextselect
-moz-mac-disabledtoolbartext -moz-mac-secondaryhighlight
-moz-menuhover -moz-menuhovertext -moz-menubartext -moz-menubarhovertext
-moz-oddtreerow -moz-win-mediatext -moz-win-communicationstext
-moz-nativehyperlinktext -moz-comboboxtext -moz-combobox""".split()
# These are not parsed but must be serialized
# They are only ever set directly by Gecko
extra_colors = """WindowBackground WindowForeground WidgetBackground WidgetForeground
WidgetSelectBackground WidgetSelectForeground Widget3DHighlight Widget3DShadow
TextBackground TextForeground TextSelectBackground TextSelectForeground
TextSelectForegroundCustom TextSelectBackgroundDisabled TextSelectBackgroundAttention
TextHighlightBackground TextHighlightForeground IMERawInputBackground
IMERawInputForeground IMERawInputUnderline IMESelectedRawTextBackground
IMESelectedRawTextForeground IMESelectedRawTextUnderline
IMEConvertedTextBackground IMEConvertedTextForeground IMEConvertedTextUnderline
IMESelectedConvertedTextBackground IMESelectedConvertedTextForeground
IMESelectedConvertedTextUnderline SpellCheckerUnderline""".split()
%>
use gecko_bindings::bindings::Gecko_GetLookAndFeelSystemColor;
use gecko_bindings::structs::root::mozilla::LookAndFeel_ColorID;
pub type SystemColor = LookAndFeel_ColorID;
impl ToCss for SystemColor {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let s = match *self {
% for color in system_colors + extra_colors:
LookAndFeel_ColorID::eColorID_${to_rust_ident(color)} => "${color}",
% endfor
LookAndFeel_ColorID::eColorID_LAST_COLOR => unreachable!(),
};
dest.write_str(s)
}
}
impl ToComputedValue for SystemColor {
type ComputedValue = u32; // nscolor
#[inline]
fn to_computed_value(&self, cx: &Context) -> Self::ComputedValue {
unsafe {
Gecko_GetLookAndFeelSystemColor(*self as i32,
&*cx.device.pres_context)
}
}
#[inline]
fn from_computed_value(_: &Self::ComputedValue) -> Self {
unreachable!()
}
}
impl SystemColor {
pub fn parse(input: &mut Parser) -> Result<Self, ()> {
use std::ascii::AsciiExt;
static PARSE_ARRAY: &'static [(&'static str, SystemColor); ${len(system_colors)}] = &[
% for color in system_colors:
("${color}", LookAndFeel_ColorID::eColorID_${to_rust_ident(color)}),
% endfor
];
let ident = input.expect_ident()?;
for &(name, color) in PARSE_ARRAY.iter() {
if name.eq_ignore_ascii_case(&ident) {
return Ok(color)
}
}
Err(())
}
}
% endif
</%helpers:longhand> | type ComputedValue = computed_value::T;
| random_line_split |
ScreenSprite.js | //-----------------------------------------------------------------------------
/**
* The sprite which covers the entire game screen.
*
* @class ScreenSprite
* @constructor
*/
function | () {
this.initialize.apply(this, arguments);
}
ScreenSprite.prototype = Object.create(PIXI.Container.prototype);
ScreenSprite.prototype.constructor = ScreenSprite;
ScreenSprite.prototype.initialize = function () {
PIXI.Container.call(this);
this._graphics = new PIXI.Graphics();
this.addChild(this._graphics);
this.opacity = 0;
this._red = -1;
this._green = -1;
this._blue = -1;
this._colorText = '';
this.setBlack();
};
/**
* The opacity of the sprite (0 to 255).
*
* @property opacity
* @type Number
*/
Object.defineProperty(ScreenSprite.prototype, 'opacity', {
get: function () {
return this.alpha * 255;
},
set: function (value) {
this.alpha = value.clamp(0, 255) / 255;
},
configurable: true
});
ScreenSprite.YEPWarned = false;
ScreenSprite.warnYep = function () {
if (!ScreenSprite.YEPWarned) {
console.log("Deprecation warning. Please update YEP_CoreEngine. ScreenSprite is not a sprite, it has graphics inside.");
ScreenSprite.YEPWarned = true;
}
};
Object.defineProperty(ScreenSprite.prototype, 'anchor', {
get: function () {
ScreenSprite.warnYep();
this.scale.x = 1;
this.scale.y = 1;
return {x: 0, y: 0};
},
set: function (value) {
this.alpha = value.clamp(0, 255) / 255;
},
configurable: true
});
Object.defineProperty(ScreenSprite.prototype, 'blendMode', {
get: function () {
return this._graphics.blendMode;
},
set: function (value) {
this._graphics.blendMode = value;
},
configurable: true
});
/**
* Sets black to the color of the screen sprite.
*
* @method setBlack
*/
ScreenSprite.prototype.setBlack = function () {
this.setColor(0, 0, 0);
};
/**
* Sets white to the color of the screen sprite.
*
* @method setWhite
*/
ScreenSprite.prototype.setWhite = function () {
this.setColor(255, 255, 255);
};
/**
* Sets the color of the screen sprite by values.
*
* @method setColor
* @param {Number} r The red value in the range (0, 255)
* @param {Number} g The green value in the range (0, 255)
* @param {Number} b The blue value in the range (0, 255)
*/
ScreenSprite.prototype.setColor = function (r, g, b) {
if (this._red !== r || this._green !== g || this._blue !== b) {
r = Math.round(r || 0).clamp(0, 255);
g = Math.round(g || 0).clamp(0, 255);
b = Math.round(b || 0).clamp(0, 255);
this._red = r;
this._green = g;
this._blue = b;
this._colorText = Utils.rgbToCssColor(r, g, b);
var graphics = this._graphics;
graphics.clear();
var intColor = (r << 16) | (g << 8) | b;
graphics.beginFill(intColor, 1);
//whole screen with zoom. BWAHAHAHAHA
graphics.drawRect(-Graphics.width * 5, -Graphics.height * 5, Graphics.width * 10, Graphics.height * 10);
}
};
| ScreenSprite | identifier_name |
ScreenSprite.js | //-----------------------------------------------------------------------------
/**
* The sprite which covers the entire game screen.
*
* @class ScreenSprite
* @constructor
*/
function ScreenSprite() {
this.initialize.apply(this, arguments);
}
ScreenSprite.prototype = Object.create(PIXI.Container.prototype);
ScreenSprite.prototype.constructor = ScreenSprite;
ScreenSprite.prototype.initialize = function () { |
this._graphics = new PIXI.Graphics();
this.addChild(this._graphics);
this.opacity = 0;
this._red = -1;
this._green = -1;
this._blue = -1;
this._colorText = '';
this.setBlack();
};
/**
* The opacity of the sprite (0 to 255).
*
* @property opacity
* @type Number
*/
Object.defineProperty(ScreenSprite.prototype, 'opacity', {
get: function () {
return this.alpha * 255;
},
set: function (value) {
this.alpha = value.clamp(0, 255) / 255;
},
configurable: true
});
ScreenSprite.YEPWarned = false;
ScreenSprite.warnYep = function () {
if (!ScreenSprite.YEPWarned) {
console.log("Deprecation warning. Please update YEP_CoreEngine. ScreenSprite is not a sprite, it has graphics inside.");
ScreenSprite.YEPWarned = true;
}
};
Object.defineProperty(ScreenSprite.prototype, 'anchor', {
get: function () {
ScreenSprite.warnYep();
this.scale.x = 1;
this.scale.y = 1;
return {x: 0, y: 0};
},
set: function (value) {
this.alpha = value.clamp(0, 255) / 255;
},
configurable: true
});
Object.defineProperty(ScreenSprite.prototype, 'blendMode', {
get: function () {
return this._graphics.blendMode;
},
set: function (value) {
this._graphics.blendMode = value;
},
configurable: true
});
/**
* Sets black to the color of the screen sprite.
*
* @method setBlack
*/
ScreenSprite.prototype.setBlack = function () {
this.setColor(0, 0, 0);
};
/**
* Sets white to the color of the screen sprite.
*
* @method setWhite
*/
ScreenSprite.prototype.setWhite = function () {
this.setColor(255, 255, 255);
};
/**
* Sets the color of the screen sprite by values.
*
* @method setColor
* @param {Number} r The red value in the range (0, 255)
* @param {Number} g The green value in the range (0, 255)
* @param {Number} b The blue value in the range (0, 255)
*/
ScreenSprite.prototype.setColor = function (r, g, b) {
if (this._red !== r || this._green !== g || this._blue !== b) {
r = Math.round(r || 0).clamp(0, 255);
g = Math.round(g || 0).clamp(0, 255);
b = Math.round(b || 0).clamp(0, 255);
this._red = r;
this._green = g;
this._blue = b;
this._colorText = Utils.rgbToCssColor(r, g, b);
var graphics = this._graphics;
graphics.clear();
var intColor = (r << 16) | (g << 8) | b;
graphics.beginFill(intColor, 1);
//whole screen with zoom. BWAHAHAHAHA
graphics.drawRect(-Graphics.width * 5, -Graphics.height * 5, Graphics.width * 10, Graphics.height * 10);
}
}; | PIXI.Container.call(this); | random_line_split |
ScreenSprite.js | //-----------------------------------------------------------------------------
/**
* The sprite which covers the entire game screen.
*
* @class ScreenSprite
* @constructor
*/
function ScreenSprite() |
ScreenSprite.prototype = Object.create(PIXI.Container.prototype);
ScreenSprite.prototype.constructor = ScreenSprite;
ScreenSprite.prototype.initialize = function () {
PIXI.Container.call(this);
this._graphics = new PIXI.Graphics();
this.addChild(this._graphics);
this.opacity = 0;
this._red = -1;
this._green = -1;
this._blue = -1;
this._colorText = '';
this.setBlack();
};
/**
* The opacity of the sprite (0 to 255).
*
* @property opacity
* @type Number
*/
Object.defineProperty(ScreenSprite.prototype, 'opacity', {
get: function () {
return this.alpha * 255;
},
set: function (value) {
this.alpha = value.clamp(0, 255) / 255;
},
configurable: true
});
ScreenSprite.YEPWarned = false;
ScreenSprite.warnYep = function () {
if (!ScreenSprite.YEPWarned) {
console.log("Deprecation warning. Please update YEP_CoreEngine. ScreenSprite is not a sprite, it has graphics inside.");
ScreenSprite.YEPWarned = true;
}
};
Object.defineProperty(ScreenSprite.prototype, 'anchor', {
get: function () {
ScreenSprite.warnYep();
this.scale.x = 1;
this.scale.y = 1;
return {x: 0, y: 0};
},
set: function (value) {
this.alpha = value.clamp(0, 255) / 255;
},
configurable: true
});
Object.defineProperty(ScreenSprite.prototype, 'blendMode', {
get: function () {
return this._graphics.blendMode;
},
set: function (value) {
this._graphics.blendMode = value;
},
configurable: true
});
/**
* Sets black to the color of the screen sprite.
*
* @method setBlack
*/
ScreenSprite.prototype.setBlack = function () {
this.setColor(0, 0, 0);
};
/**
* Sets white to the color of the screen sprite.
*
* @method setWhite
*/
ScreenSprite.prototype.setWhite = function () {
this.setColor(255, 255, 255);
};
/**
* Sets the color of the screen sprite by values.
*
* @method setColor
* @param {Number} r The red value in the range (0, 255)
* @param {Number} g The green value in the range (0, 255)
* @param {Number} b The blue value in the range (0, 255)
*/
ScreenSprite.prototype.setColor = function (r, g, b) {
if (this._red !== r || this._green !== g || this._blue !== b) {
r = Math.round(r || 0).clamp(0, 255);
g = Math.round(g || 0).clamp(0, 255);
b = Math.round(b || 0).clamp(0, 255);
this._red = r;
this._green = g;
this._blue = b;
this._colorText = Utils.rgbToCssColor(r, g, b);
var graphics = this._graphics;
graphics.clear();
var intColor = (r << 16) | (g << 8) | b;
graphics.beginFill(intColor, 1);
//whole screen with zoom. BWAHAHAHAHA
graphics.drawRect(-Graphics.width * 5, -Graphics.height * 5, Graphics.width * 10, Graphics.height * 10);
}
};
| {
this.initialize.apply(this, arguments);
} | identifier_body |
ScreenSprite.js | //-----------------------------------------------------------------------------
/**
* The sprite which covers the entire game screen.
*
* @class ScreenSprite
* @constructor
*/
function ScreenSprite() {
this.initialize.apply(this, arguments);
}
ScreenSprite.prototype = Object.create(PIXI.Container.prototype);
ScreenSprite.prototype.constructor = ScreenSprite;
ScreenSprite.prototype.initialize = function () {
PIXI.Container.call(this);
this._graphics = new PIXI.Graphics();
this.addChild(this._graphics);
this.opacity = 0;
this._red = -1;
this._green = -1;
this._blue = -1;
this._colorText = '';
this.setBlack();
};
/**
* The opacity of the sprite (0 to 255).
*
* @property opacity
* @type Number
*/
Object.defineProperty(ScreenSprite.prototype, 'opacity', {
get: function () {
return this.alpha * 255;
},
set: function (value) {
this.alpha = value.clamp(0, 255) / 255;
},
configurable: true
});
ScreenSprite.YEPWarned = false;
ScreenSprite.warnYep = function () {
if (!ScreenSprite.YEPWarned) {
console.log("Deprecation warning. Please update YEP_CoreEngine. ScreenSprite is not a sprite, it has graphics inside.");
ScreenSprite.YEPWarned = true;
}
};
Object.defineProperty(ScreenSprite.prototype, 'anchor', {
get: function () {
ScreenSprite.warnYep();
this.scale.x = 1;
this.scale.y = 1;
return {x: 0, y: 0};
},
set: function (value) {
this.alpha = value.clamp(0, 255) / 255;
},
configurable: true
});
Object.defineProperty(ScreenSprite.prototype, 'blendMode', {
get: function () {
return this._graphics.blendMode;
},
set: function (value) {
this._graphics.blendMode = value;
},
configurable: true
});
/**
* Sets black to the color of the screen sprite.
*
* @method setBlack
*/
ScreenSprite.prototype.setBlack = function () {
this.setColor(0, 0, 0);
};
/**
* Sets white to the color of the screen sprite.
*
* @method setWhite
*/
ScreenSprite.prototype.setWhite = function () {
this.setColor(255, 255, 255);
};
/**
* Sets the color of the screen sprite by values.
*
* @method setColor
* @param {Number} r The red value in the range (0, 255)
* @param {Number} g The green value in the range (0, 255)
* @param {Number} b The blue value in the range (0, 255)
*/
ScreenSprite.prototype.setColor = function (r, g, b) {
if (this._red !== r || this._green !== g || this._blue !== b) |
};
| {
r = Math.round(r || 0).clamp(0, 255);
g = Math.round(g || 0).clamp(0, 255);
b = Math.round(b || 0).clamp(0, 255);
this._red = r;
this._green = g;
this._blue = b;
this._colorText = Utils.rgbToCssColor(r, g, b);
var graphics = this._graphics;
graphics.clear();
var intColor = (r << 16) | (g << 8) | b;
graphics.beginFill(intColor, 1);
//whole screen with zoom. BWAHAHAHAHA
graphics.drawRect(-Graphics.width * 5, -Graphics.height * 5, Graphics.width * 10, Graphics.height * 10);
} | conditional_block |
AbstractNavItem.js | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
var _classnames = _interopRequireDefault(require("classnames"));
var _react = _interopRequireDefault(require("react"));
var _NavContext = _interopRequireDefault(require("./NavContext"));
var _SelectableContext = _interopRequireWildcard(require("./SelectableContext"));
var defaultProps = {
disabled: false
};
var AbstractNavItem =
/*#__PURE__*/
function (_React$Component) {
(0, _inheritsLoose2.default)(AbstractNavItem, _React$Component);
function AbstractNavItem() |
var _proto = AbstractNavItem.prototype;
_proto.render = function render() {
var _this = this;
var _this$props = this.props,
active = _this$props.active,
className = _this$props.className,
tabIndex = _this$props.tabIndex,
eventKey = _this$props.eventKey,
onSelect = _this$props.onSelect,
Component = _this$props.as,
props = (0, _objectWithoutPropertiesLoose2.default)(_this$props, ["active", "className", "tabIndex", "eventKey", "onSelect", "as"]);
var navKey = (0, _SelectableContext.makeEventKey)(eventKey, props.href);
return _react.default.createElement(_SelectableContext.default.Consumer, null, function (parentOnSelect) {
return _react.default.createElement(_NavContext.default.Consumer, null, function (navContext) {
var isActive = active;
if (navContext) {
if (!props.role && navContext.role === 'tablist') props.role = 'tab';
props['data-rb-event-key'] = navKey;
props.id = navContext.getControllerId(navKey);
props['aria-controls'] = navContext.getControlledId(navKey);
isActive = active == null && navKey != null ? navContext.activeKey === navKey : active;
}
if (props.role === 'tab') {
props.tabIndex = isActive ? tabIndex : -1;
props['aria-selected'] = isActive;
}
return _react.default.createElement(Component, (0, _extends2.default)({}, props, {
className: (0, _classnames.default)(className, isActive && 'active'),
onClick: function onClick(e) {
var onClick = _this.props.onClick;
if (onClick) onClick(e);
if (navKey == null) return;
if (onSelect) onSelect(navKey, e);
if (parentOnSelect) parentOnSelect(navKey, e);
}
}));
});
});
};
return AbstractNavItem;
}(_react.default.Component);
AbstractNavItem.defaultProps = defaultProps;
var _default = AbstractNavItem;
exports.default = _default;
module.exports = exports["default"]; | {
return _React$Component.apply(this, arguments) || this;
} | identifier_body |
AbstractNavItem.js | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
var _classnames = _interopRequireDefault(require("classnames"));
var _react = _interopRequireDefault(require("react"));
var _NavContext = _interopRequireDefault(require("./NavContext"));
var _SelectableContext = _interopRequireWildcard(require("./SelectableContext"));
var defaultProps = {
disabled: false
};
var AbstractNavItem =
/*#__PURE__*/
function (_React$Component) {
(0, _inheritsLoose2.default)(AbstractNavItem, _React$Component);
function | () {
return _React$Component.apply(this, arguments) || this;
}
var _proto = AbstractNavItem.prototype;
_proto.render = function render() {
var _this = this;
var _this$props = this.props,
active = _this$props.active,
className = _this$props.className,
tabIndex = _this$props.tabIndex,
eventKey = _this$props.eventKey,
onSelect = _this$props.onSelect,
Component = _this$props.as,
props = (0, _objectWithoutPropertiesLoose2.default)(_this$props, ["active", "className", "tabIndex", "eventKey", "onSelect", "as"]);
var navKey = (0, _SelectableContext.makeEventKey)(eventKey, props.href);
return _react.default.createElement(_SelectableContext.default.Consumer, null, function (parentOnSelect) {
return _react.default.createElement(_NavContext.default.Consumer, null, function (navContext) {
var isActive = active;
if (navContext) {
if (!props.role && navContext.role === 'tablist') props.role = 'tab';
props['data-rb-event-key'] = navKey;
props.id = navContext.getControllerId(navKey);
props['aria-controls'] = navContext.getControlledId(navKey);
isActive = active == null && navKey != null ? navContext.activeKey === navKey : active;
}
if (props.role === 'tab') {
props.tabIndex = isActive ? tabIndex : -1;
props['aria-selected'] = isActive;
}
return _react.default.createElement(Component, (0, _extends2.default)({}, props, {
className: (0, _classnames.default)(className, isActive && 'active'),
onClick: function onClick(e) {
var onClick = _this.props.onClick;
if (onClick) onClick(e);
if (navKey == null) return;
if (onSelect) onSelect(navKey, e);
if (parentOnSelect) parentOnSelect(navKey, e);
}
}));
});
});
};
return AbstractNavItem;
}(_react.default.Component);
AbstractNavItem.defaultProps = defaultProps;
var _default = AbstractNavItem;
exports.default = _default;
module.exports = exports["default"]; | AbstractNavItem | identifier_name |
AbstractNavItem.js | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
var _classnames = _interopRequireDefault(require("classnames"));
var _react = _interopRequireDefault(require("react"));
var _NavContext = _interopRequireDefault(require("./NavContext"));
var _SelectableContext = _interopRequireWildcard(require("./SelectableContext"));
var defaultProps = {
disabled: false
};
var AbstractNavItem =
/*#__PURE__*/
function (_React$Component) {
(0, _inheritsLoose2.default)(AbstractNavItem, _React$Component);
function AbstractNavItem() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = AbstractNavItem.prototype;
_proto.render = function render() {
var _this = this;
var _this$props = this.props,
active = _this$props.active,
className = _this$props.className,
tabIndex = _this$props.tabIndex,
eventKey = _this$props.eventKey,
onSelect = _this$props.onSelect,
Component = _this$props.as,
props = (0, _objectWithoutPropertiesLoose2.default)(_this$props, ["active", "className", "tabIndex", "eventKey", "onSelect", "as"]);
var navKey = (0, _SelectableContext.makeEventKey)(eventKey, props.href);
return _react.default.createElement(_SelectableContext.default.Consumer, null, function (parentOnSelect) {
return _react.default.createElement(_NavContext.default.Consumer, null, function (navContext) {
var isActive = active;
if (navContext) {
if (!props.role && navContext.role === 'tablist') props.role = 'tab';
props['data-rb-event-key'] = navKey;
props.id = navContext.getControllerId(navKey);
props['aria-controls'] = navContext.getControlledId(navKey);
isActive = active == null && navKey != null ? navContext.activeKey === navKey : active;
}
if (props.role === 'tab') {
props.tabIndex = isActive ? tabIndex : -1;
props['aria-selected'] = isActive;
}
return _react.default.createElement(Component, (0, _extends2.default)({}, props, {
className: (0, _classnames.default)(className, isActive && 'active'),
onClick: function onClick(e) {
var onClick = _this.props.onClick;
if (onClick) onClick(e);
if (navKey == null) return;
if (onSelect) onSelect(navKey, e);
if (parentOnSelect) parentOnSelect(navKey, e);
}
}));
});
});
};
return AbstractNavItem;
}(_react.default.Component); | var _default = AbstractNavItem;
exports.default = _default;
module.exports = exports["default"]; |
AbstractNavItem.defaultProps = defaultProps; | random_line_split |
win_msg.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Jon Hawkesworth (@jhawkesworth) <figs@unity.demon.co.uk>
#
# 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 is a windows documentation stub. actual code lives in the .ps1
# file of the same name
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_msg
version_added: "2.3"
short_description: Sends a message to logged in users on Windows hosts.
description:
- Wraps the msg.exe command in order to send messages to Windows hosts.
options:
to:
description:
- Who to send the message to. Can be a username, sessionname or sessionid.
default: '*'
display_seconds:
description:
- How long to wait for receiver to acknowledge message, in seconds.
default: 10
wait:
description:
- Whether to wait for users to respond. Module will only wait for the number of seconds specified in display_seconds or 10 seconds if not specified.
However, if I(wait) is true, the message is sent to each logged on user in turn, waiting for the user to either press 'ok' or for
the timeout to elapse before moving on to the next user.
type: bool
default: 'no'
msg:
description:
- The text of the message to be displayed.
- The message must be less than 256 characters.
default: Hello world!
author:
- Jon Hawkesworth (@jhawkesworth)
notes:
- This module must run on a windows host, so ensure your play targets windows
hosts, or delegates to a windows host.
- Messages are only sent to the local host where the module is run.
- The module does not support sending to users listed in a file.
- Setting wait to true can result in long run times on systems with many logged in users.
'''
EXAMPLES = r'''
- name: Warn logged in users of impending upgrade
win_msg:
display_seconds: 60
msg: Automated upgrade about to start. Please save your work and log off before {{ deployment_start_time }}
'''
RETURN = r'''
msg:
description: Test of the message that was sent.
returned: changed
type: string
sample: Automated upgrade about to start. Please save your work and log off before 22 July 2016 18:00:00
display_seconds:
description: Value of display_seconds module parameter.
returned: success
type: string | description: The return code of the API call
returned: always
type: int
sample: 0
runtime_seconds:
description: How long the module took to run on the remote windows host.
returned: success
type: string
sample: 22 July 2016 17:45:51
sent_localtime:
description: local time from windows host when the message was sent.
returned: success
type: string
sample: 22 July 2016 17:45:51
wait:
description: Value of wait module parameter.
returned: success
type: boolean
sample: false
''' | sample: 10
rc: | random_line_split |
increment.py | config = ConfigParser.ConfigParser()
config.read(CONFIG)
if not config.has_section(SECTIONS['INCREMENTS']):
config.add_section(SECTIONS['INCREMENTS'])
with open(CONFIG, 'w') as f:
config.write(f)
def read_since_ids(users):
"""
Read max ids of the last downloads
:param users: A list of users
Return a dictionary mapping users to ids
"""
since_ids = {}
for user in users:
if config.has_option(SECTIONS['INCREMENTS'], user):
since_ids[user] = config.getint(SECTIONS['INCREMENTS'], user) + 1
return since_ids
def set_max_ids(max_ids):
"""
Set max ids of the current downloads
:param max_ids: A dictionary mapping users to ids
"""
config.read(CONFIG)
for user, max_id in max_ids.items():
config.set(SECTIONS['INCREMENTS'], user, str(max_id))
with open(CONFIG, 'w') as f:
config.write(f)
def remove_since_id(user):
if config.has_option(SECTIONS['INCREMENTS'], user):
config.remove_option(SECTIONS['INCREMENTS'], user)
with open(CONFIG, 'w') as f:
config.write(f) | import ConfigParser
from .settings import SECTIONS, CONFIG
| random_line_split | |
increment.py | import ConfigParser
from .settings import SECTIONS, CONFIG
config = ConfigParser.ConfigParser()
config.read(CONFIG)
if not config.has_section(SECTIONS['INCREMENTS']):
config.add_section(SECTIONS['INCREMENTS'])
with open(CONFIG, 'w') as f:
config.write(f)
def read_since_ids(users):
|
def set_max_ids(max_ids):
"""
Set max ids of the current downloads
:param max_ids: A dictionary mapping users to ids
"""
config.read(CONFIG)
for user, max_id in max_ids.items():
config.set(SECTIONS['INCREMENTS'], user, str(max_id))
with open(CONFIG, 'w') as f:
config.write(f)
def remove_since_id(user):
if config.has_option(SECTIONS['INCREMENTS'], user):
config.remove_option(SECTIONS['INCREMENTS'], user)
with open(CONFIG, 'w') as f:
config.write(f)
| """
Read max ids of the last downloads
:param users: A list of users
Return a dictionary mapping users to ids
"""
since_ids = {}
for user in users:
if config.has_option(SECTIONS['INCREMENTS'], user):
since_ids[user] = config.getint(SECTIONS['INCREMENTS'], user) + 1
return since_ids | identifier_body |
increment.py | import ConfigParser
from .settings import SECTIONS, CONFIG
config = ConfigParser.ConfigParser()
config.read(CONFIG)
if not config.has_section(SECTIONS['INCREMENTS']):
config.add_section(SECTIONS['INCREMENTS'])
with open(CONFIG, 'w') as f:
config.write(f)
def read_since_ids(users):
"""
Read max ids of the last downloads
:param users: A list of users
Return a dictionary mapping users to ids
"""
since_ids = {}
for user in users:
|
return since_ids
def set_max_ids(max_ids):
"""
Set max ids of the current downloads
:param max_ids: A dictionary mapping users to ids
"""
config.read(CONFIG)
for user, max_id in max_ids.items():
config.set(SECTIONS['INCREMENTS'], user, str(max_id))
with open(CONFIG, 'w') as f:
config.write(f)
def remove_since_id(user):
if config.has_option(SECTIONS['INCREMENTS'], user):
config.remove_option(SECTIONS['INCREMENTS'], user)
with open(CONFIG, 'w') as f:
config.write(f)
| if config.has_option(SECTIONS['INCREMENTS'], user):
since_ids[user] = config.getint(SECTIONS['INCREMENTS'], user) + 1 | conditional_block |
increment.py | import ConfigParser
from .settings import SECTIONS, CONFIG
config = ConfigParser.ConfigParser()
config.read(CONFIG)
if not config.has_section(SECTIONS['INCREMENTS']):
config.add_section(SECTIONS['INCREMENTS'])
with open(CONFIG, 'w') as f:
config.write(f)
def read_since_ids(users):
"""
Read max ids of the last downloads
:param users: A list of users
Return a dictionary mapping users to ids
"""
since_ids = {}
for user in users:
if config.has_option(SECTIONS['INCREMENTS'], user):
since_ids[user] = config.getint(SECTIONS['INCREMENTS'], user) + 1
return since_ids
def set_max_ids(max_ids):
"""
Set max ids of the current downloads
:param max_ids: A dictionary mapping users to ids
"""
config.read(CONFIG)
for user, max_id in max_ids.items():
config.set(SECTIONS['INCREMENTS'], user, str(max_id))
with open(CONFIG, 'w') as f:
config.write(f)
def | (user):
if config.has_option(SECTIONS['INCREMENTS'], user):
config.remove_option(SECTIONS['INCREMENTS'], user)
with open(CONFIG, 'w') as f:
config.write(f)
| remove_since_id | identifier_name |
sunburst.js | /*
* Copyright 2013 Google Inc. All Rights Reserved.
* 2015 Hauke Petersen <devel@haukepetersen.de>
*
* 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.
*
* @author Kerry Rodden
* @author Hauke Petersen <devel@haukepetersen.de>
*/
// Dimensions of sunburst.
var width = 900;
var height = 900;
var radius = Math.min(width, height) / 2;
// Breadcrumb dimensions: width, height, spacing, width of tip/tail.
var b = {
w: 100, h: 30, s: 3, t: 10
};
// Mapping of step names to colors.
var colors = {
"core": "#a173d1",
"cpu": "#7b615c",
"boards": "#de783b",
"drivers": "#35a9b5",
"sys": "#5687d1",
"newlib": "#6ab975",
"fill": "#bbbbbb"
};
var DEFAULT_INPUTFILE = 'mem_t.csv'
// Total size of all segments; we set this later, after loading the data.
var totalSize = 0;
var vis;
// the complete dataset
var info;
var dataset;
var cur_view;
var partition = d3.layout.partition()
.size([2 * Math.PI, radius * radius])
.value(function(d) { return d.size; });
var arc = d3.svg.arc()
.startAngle(function(d) { return d.x; })
.endAngle(function(d) { return d.x + d.dx; })
.innerRadius(function(d) { return Math.sqrt(d.y); })
.outerRadius(function(d) { return Math.sqrt(d.y + d.dy); });
function createVisualization() {
// Basic setup of page elements.
initializeBreadcrumbTrail();
drawLegend();
d3.select("#btnExport").on("click", exportstuff);
d3.select("#btnT").on("click", function() {
update(['t']);
});
d3.select("#btnD").on("click", function() {
update(['d']);
});
d3.select("#btnB").on("click", function() {
update(['b']);
});
d3.select("#btnSum").on("click", function() {
update(['t', 'd', 'b']);
});
};
function updateChart(data) {
d3.select("#chart svg").remove();
vis = d3.select("#chart").append("svg:svg")
.attr("width", width)
.attr("height", height)
.append("svg:g")
.attr("id", "container")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// Bounding circle underneath the sunburst, to make it easier to detect
// when the mouse leaves the parent g.
vis.append("svg:circle")
.attr("r", radius)
.style("opacity", 0);
var nodes = partition.nodes(data);
var path = vis.data([data]).selectAll("path")
.data(nodes)
.enter().append("svg:path")
.attr("display", function(d) { return d.depth ? null : "none"; })
.attr("d", arc)
.attr("fill-rule", "evenodd")
.style("fill", function(d) {
tmp = d;
if (!tmp.parent) {
return "#333";
}
while (tmp.parent.parent) {
tmp = tmp.parent;
}
return d3.rgb(colors[tmp.name]).darker(d.depth / 6);
})
.style("opacity", 1)
.on("click", zoomIn)
.on("mouseover", mouseover)
.append("text").attr("dx", 12).attr("dy", ".35em").text(function(d) {return d.name });
// Add the mouseleave handler to the bounding circle.
d3.select("#container")
.on("mouseleave", mouseleave)
.on("contextmenu", zoomOut);
// Get total size of the tree = value of root node from partition.
totalSize = path.node().__data__.value;
d3.select("#expl_per").text("100%");
d3.select("#expl_sym").text(info.app);
d3.select("#expl_size").text(totalSize + " byte");
};
// export svg to pdf of something else
function exportstuff(d) {
console.log("ding ding", d);
};
function zoomIn(d) {
console.log("zoom", d);
updateChart(d);
};
function zoomOut(d) {
d3.event.preventDefault();
console.log("right click", d);
updateChart(cur_view);
};
function updateTable(d) {
var table = d3.select("#table");
table.selectAll("tbody").remove();
var body = table.append("tbody");
tableAdd(d, body, 1);
};
function tableAdd(d, body, layer) {
var row = body.append("tr").classed("l" + layer, true);
row.append("td").text(d.name);
row.append("td").text(d.value).classed("size", true);
if (d.children && layer < 2) {
for (var i = 0; i < d.children.length; i++) {
tableAdd(d.children[i], body, layer + 1);
}
}
};
// Fade all but the current sequence, and show it in the breadcrumb trail.
function | (d) {
updateTable(d);
var percentage = (100 * d.value / totalSize).toPrecision(3);
var percentageString = percentage + "%";
if (percentage < 0.1) {
percentageString = "< 0.1%";
}
d3.select("#expl_per").text(percentageString);
d3.select("#expl_sym").text(d.name);
d3.select("#expl_size").text(d.value + " byte");
// d3.select("#explanation")
// .style("visibility", "");
var sequenceArray = getAncestors(d);
updateBreadcrumbs(sequenceArray, percentageString);
// Fade all the segments.
d3.selectAll("path")
.style("opacity", 0.3);
// Then highlight only those that are an ancestor of the current segment.
vis.selectAll("path")
.filter(function(node) {
return (sequenceArray.indexOf(node) >= 0);
})
.style("opacity", 1);
}
// Restore everything to full opacity when moving off the visualization.
function mouseleave(d) {
updateTable(d);
var name = (d.name == 'root') ? info['app'] : d.name;
// show generic stats
d3.select("#expl_per").text("100%");
d3.select("#expl_sym").text(name);
d3.select("#expl_size").text(totalSize + " byte");
// Hide the breadcrumb trail
d3.select("#trail")
.style("visibility", "hidden");
// Deactivate all segments during transition.
d3.selectAll("path").on("mouseover", null);
// Transition each segment to full opacity and then reactivate it.
d3.selectAll("path")
.transition()
.duration(100)
.style("opacity", 1)
.each("end", function() {
d3.select(this).on("mouseover", mouseover);
});
// d3.select("#explanation")
// .style("visibility", "hidden");
}
// Given a node in a partition layout, return an array of all of its ancestor
// nodes, highest first, but excluding the root.
function getAncestors(node) {
var path = [];
var current = node;
while (current.parent) {
path.unshift(current);
current = current.parent;
}
return path;
}
function initializeBreadcrumbTrail() {
// Add the svg area.
var trail = d3.select("#sequence").append("svg:svg")
.attr("width", width)
.attr("height", 50)
.attr("id", "trail");
// Add the label at the end, for the percentage.
trail.append("svg:text")
.attr("id", "endlabel")
.style("fill", "#000");
}
// Generate a string that describes the points of a breadcrumb polygon.
function breadcrumbPoints(d, i) {
var points = [];
points.push("0,0");
points.push(b.w + ",0");
points.push(b.w + b.t + "," + (b.h / 2));
points.push(b.w + "," + b.h);
points.push("0," + b.h);
if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.
points.push(b.t + "," + (b.h / 2));
}
return points.join(" ");
}
// Update the breadcrumb trail to show the current sequence and percentage.
function updateBreadcrumbs(nodeArray, percentageString) {
// Data join; key function combines name and depth (= position in sequence).
var g = d3.select("#trail")
.selectAll("g")
.data(nodeArray, function(d) { return d.name + d.depth; });
// Add breadcrumb and label for entering nodes.
var entering = g.enter().append("svg:g");
entering.append("svg:polygon")
.attr("points", breadcrumbPoints)
// .style("fill", function(d) { return colors[d.name]; });
.style("fill", function(d) {
return d3.rgb(colors[nodeArray[0].name]).darker(d.depth / 6);
});
entering.append("svg:text")
.attr("x", (b.w + b.t) / 2)
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; });
// Set position for entering and updating nodes.
g.attr("transform", function(d, i) {
return "translate(" + i * (b.w + b.s) + ", 0)";
});
// Remove exiting nodes.
g.exit().remove();
// Now move and update the percentage at the end.
d3.select("#trail").select("#endlabel")
.attr("x", (nodeArray.length + 0.5) * (b.w + b.s))
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(percentageString);
// Make the breadcrumb trail visible, if it's hidden.
d3.select("#trail")
.style("visibility", "");
}
function drawLegend() {
// Dimensions of legend item: width, height, spacing, radius of rounded rect.
var li = {
w: 75, h: 30, s: 3, r: 3
};
d3.select("#legend svg").remove();
var legend = d3.select("#legend").append("svg:svg")
.attr("width", li.w)
.attr("height", d3.keys(colors).length * (li.h + li.s));
var g = legend.selectAll("g")
.data(d3.entries(colors))
.enter().append("svg:g")
.attr("transform", function(d, i) {
return "translate(0," + i * (li.h + li.s) + ")";
});
g.append("svg:rect")
.attr("rx", li.r)
.attr("ry", li.r)
.attr("width", li.w)
.attr("height", li.h)
.style("fill", function(d) { return d.value; });
g.append("svg:text")
.attr("x", li.w / 2)
.attr("y", li.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.key; });
legend.style("visibility", "");
}
function filter(type, depth, root) {
if (!root) {
root = info['app']; /* put application name here */
}
var r = {'name': root, 'children': []};
for (var i = 0; i < dataset.length; i++) {
// filter only requested types
if (type.indexOf(dataset[i].type) == -1) {
continue;
}
// add element to tree
var e = r;
var path = dataset[i]['path'].slice();
path.push(dataset[i]['obj'])
for (var j = 0; j < path.length; j++) {
var child = undefined;
// search for part
for (var k = 0; k < e.children.length; k++) {
if (e.children[k]['name'] == path[j]) {
child = e.children[k];
}
}
if (!child) {
e.children.push({'name': path[j], 'children': []}) - 1;
child = e.children[e.children.length - 1];
}
e = child;
}
/* build the branch, now adding the leaf */
e.children.push({'name': dataset[i]['sym'], 'size': dataset[i]['size']});
}
return r;
}
function update(fil) {
cur_view = {};
cur_view = filter(fil);
updateChart(cur_view);
updateTable(cur_view);
}
// bootstrap the whole damn thing
createVisualization();
d3.json("symbols.json", function(data) {
info = data;
dataset = data['symbols'];
update(['t']);
});
| mouseover | identifier_name |
sunburst.js | /*
* Copyright 2013 Google Inc. All Rights Reserved.
* 2015 Hauke Petersen <devel@haukepetersen.de>
*
* 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.
*
* @author Kerry Rodden
* @author Hauke Petersen <devel@haukepetersen.de>
*/
// Dimensions of sunburst.
var width = 900;
var height = 900;
var radius = Math.min(width, height) / 2;
// Breadcrumb dimensions: width, height, spacing, width of tip/tail.
var b = {
w: 100, h: 30, s: 3, t: 10
};
// Mapping of step names to colors.
var colors = {
"core": "#a173d1",
"cpu": "#7b615c",
"boards": "#de783b",
"drivers": "#35a9b5",
"sys": "#5687d1",
"newlib": "#6ab975",
"fill": "#bbbbbb"
};
var DEFAULT_INPUTFILE = 'mem_t.csv'
// Total size of all segments; we set this later, after loading the data.
var totalSize = 0;
var vis;
// the complete dataset
var info;
var dataset;
var cur_view;
var partition = d3.layout.partition()
.size([2 * Math.PI, radius * radius])
.value(function(d) { return d.size; });
var arc = d3.svg.arc()
.startAngle(function(d) { return d.x; })
.endAngle(function(d) { return d.x + d.dx; })
.innerRadius(function(d) { return Math.sqrt(d.y); })
.outerRadius(function(d) { return Math.sqrt(d.y + d.dy); });
function createVisualization() {
// Basic setup of page elements.
initializeBreadcrumbTrail();
drawLegend();
d3.select("#btnExport").on("click", exportstuff);
d3.select("#btnT").on("click", function() {
update(['t']);
});
d3.select("#btnD").on("click", function() {
update(['d']);
});
d3.select("#btnB").on("click", function() {
update(['b']);
});
d3.select("#btnSum").on("click", function() {
update(['t', 'd', 'b']);
});
};
function updateChart(data) {
d3.select("#chart svg").remove();
vis = d3.select("#chart").append("svg:svg")
.attr("width", width)
.attr("height", height)
.append("svg:g")
.attr("id", "container")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// Bounding circle underneath the sunburst, to make it easier to detect
// when the mouse leaves the parent g.
vis.append("svg:circle")
.attr("r", radius)
.style("opacity", 0);
var nodes = partition.nodes(data);
var path = vis.data([data]).selectAll("path")
.data(nodes)
.enter().append("svg:path")
.attr("display", function(d) { return d.depth ? null : "none"; })
.attr("d", arc)
.attr("fill-rule", "evenodd")
.style("fill", function(d) {
tmp = d;
if (!tmp.parent) {
return "#333";
}
while (tmp.parent.parent) {
tmp = tmp.parent;
}
return d3.rgb(colors[tmp.name]).darker(d.depth / 6);
})
.style("opacity", 1)
.on("click", zoomIn)
.on("mouseover", mouseover)
.append("text").attr("dx", 12).attr("dy", ".35em").text(function(d) {return d.name });
// Add the mouseleave handler to the bounding circle.
d3.select("#container")
.on("mouseleave", mouseleave)
.on("contextmenu", zoomOut);
// Get total size of the tree = value of root node from partition.
totalSize = path.node().__data__.value;
d3.select("#expl_per").text("100%");
d3.select("#expl_sym").text(info.app);
d3.select("#expl_size").text(totalSize + " byte");
};
// export svg to pdf of something else
function exportstuff(d) {
console.log("ding ding", d);
};
function zoomIn(d) {
console.log("zoom", d);
updateChart(d);
}; | };
function updateTable(d) {
var table = d3.select("#table");
table.selectAll("tbody").remove();
var body = table.append("tbody");
tableAdd(d, body, 1);
};
function tableAdd(d, body, layer) {
var row = body.append("tr").classed("l" + layer, true);
row.append("td").text(d.name);
row.append("td").text(d.value).classed("size", true);
if (d.children && layer < 2) {
for (var i = 0; i < d.children.length; i++) {
tableAdd(d.children[i], body, layer + 1);
}
}
};
// Fade all but the current sequence, and show it in the breadcrumb trail.
function mouseover(d) {
updateTable(d);
var percentage = (100 * d.value / totalSize).toPrecision(3);
var percentageString = percentage + "%";
if (percentage < 0.1) {
percentageString = "< 0.1%";
}
d3.select("#expl_per").text(percentageString);
d3.select("#expl_sym").text(d.name);
d3.select("#expl_size").text(d.value + " byte");
// d3.select("#explanation")
// .style("visibility", "");
var sequenceArray = getAncestors(d);
updateBreadcrumbs(sequenceArray, percentageString);
// Fade all the segments.
d3.selectAll("path")
.style("opacity", 0.3);
// Then highlight only those that are an ancestor of the current segment.
vis.selectAll("path")
.filter(function(node) {
return (sequenceArray.indexOf(node) >= 0);
})
.style("opacity", 1);
}
// Restore everything to full opacity when moving off the visualization.
function mouseleave(d) {
updateTable(d);
var name = (d.name == 'root') ? info['app'] : d.name;
// show generic stats
d3.select("#expl_per").text("100%");
d3.select("#expl_sym").text(name);
d3.select("#expl_size").text(totalSize + " byte");
// Hide the breadcrumb trail
d3.select("#trail")
.style("visibility", "hidden");
// Deactivate all segments during transition.
d3.selectAll("path").on("mouseover", null);
// Transition each segment to full opacity and then reactivate it.
d3.selectAll("path")
.transition()
.duration(100)
.style("opacity", 1)
.each("end", function() {
d3.select(this).on("mouseover", mouseover);
});
// d3.select("#explanation")
// .style("visibility", "hidden");
}
// Given a node in a partition layout, return an array of all of its ancestor
// nodes, highest first, but excluding the root.
function getAncestors(node) {
var path = [];
var current = node;
while (current.parent) {
path.unshift(current);
current = current.parent;
}
return path;
}
function initializeBreadcrumbTrail() {
// Add the svg area.
var trail = d3.select("#sequence").append("svg:svg")
.attr("width", width)
.attr("height", 50)
.attr("id", "trail");
// Add the label at the end, for the percentage.
trail.append("svg:text")
.attr("id", "endlabel")
.style("fill", "#000");
}
// Generate a string that describes the points of a breadcrumb polygon.
function breadcrumbPoints(d, i) {
var points = [];
points.push("0,0");
points.push(b.w + ",0");
points.push(b.w + b.t + "," + (b.h / 2));
points.push(b.w + "," + b.h);
points.push("0," + b.h);
if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.
points.push(b.t + "," + (b.h / 2));
}
return points.join(" ");
}
// Update the breadcrumb trail to show the current sequence and percentage.
function updateBreadcrumbs(nodeArray, percentageString) {
// Data join; key function combines name and depth (= position in sequence).
var g = d3.select("#trail")
.selectAll("g")
.data(nodeArray, function(d) { return d.name + d.depth; });
// Add breadcrumb and label for entering nodes.
var entering = g.enter().append("svg:g");
entering.append("svg:polygon")
.attr("points", breadcrumbPoints)
// .style("fill", function(d) { return colors[d.name]; });
.style("fill", function(d) {
return d3.rgb(colors[nodeArray[0].name]).darker(d.depth / 6);
});
entering.append("svg:text")
.attr("x", (b.w + b.t) / 2)
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; });
// Set position for entering and updating nodes.
g.attr("transform", function(d, i) {
return "translate(" + i * (b.w + b.s) + ", 0)";
});
// Remove exiting nodes.
g.exit().remove();
// Now move and update the percentage at the end.
d3.select("#trail").select("#endlabel")
.attr("x", (nodeArray.length + 0.5) * (b.w + b.s))
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(percentageString);
// Make the breadcrumb trail visible, if it's hidden.
d3.select("#trail")
.style("visibility", "");
}
function drawLegend() {
// Dimensions of legend item: width, height, spacing, radius of rounded rect.
var li = {
w: 75, h: 30, s: 3, r: 3
};
d3.select("#legend svg").remove();
var legend = d3.select("#legend").append("svg:svg")
.attr("width", li.w)
.attr("height", d3.keys(colors).length * (li.h + li.s));
var g = legend.selectAll("g")
.data(d3.entries(colors))
.enter().append("svg:g")
.attr("transform", function(d, i) {
return "translate(0," + i * (li.h + li.s) + ")";
});
g.append("svg:rect")
.attr("rx", li.r)
.attr("ry", li.r)
.attr("width", li.w)
.attr("height", li.h)
.style("fill", function(d) { return d.value; });
g.append("svg:text")
.attr("x", li.w / 2)
.attr("y", li.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.key; });
legend.style("visibility", "");
}
function filter(type, depth, root) {
if (!root) {
root = info['app']; /* put application name here */
}
var r = {'name': root, 'children': []};
for (var i = 0; i < dataset.length; i++) {
// filter only requested types
if (type.indexOf(dataset[i].type) == -1) {
continue;
}
// add element to tree
var e = r;
var path = dataset[i]['path'].slice();
path.push(dataset[i]['obj'])
for (var j = 0; j < path.length; j++) {
var child = undefined;
// search for part
for (var k = 0; k < e.children.length; k++) {
if (e.children[k]['name'] == path[j]) {
child = e.children[k];
}
}
if (!child) {
e.children.push({'name': path[j], 'children': []}) - 1;
child = e.children[e.children.length - 1];
}
e = child;
}
/* build the branch, now adding the leaf */
e.children.push({'name': dataset[i]['sym'], 'size': dataset[i]['size']});
}
return r;
}
function update(fil) {
cur_view = {};
cur_view = filter(fil);
updateChart(cur_view);
updateTable(cur_view);
}
// bootstrap the whole damn thing
createVisualization();
d3.json("symbols.json", function(data) {
info = data;
dataset = data['symbols'];
update(['t']);
}); |
function zoomOut(d) {
d3.event.preventDefault();
console.log("right click", d);
updateChart(cur_view); | random_line_split |
sunburst.js | /*
* Copyright 2013 Google Inc. All Rights Reserved.
* 2015 Hauke Petersen <devel@haukepetersen.de>
*
* 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.
*
* @author Kerry Rodden
* @author Hauke Petersen <devel@haukepetersen.de>
*/
// Dimensions of sunburst.
var width = 900;
var height = 900;
var radius = Math.min(width, height) / 2;
// Breadcrumb dimensions: width, height, spacing, width of tip/tail.
var b = {
w: 100, h: 30, s: 3, t: 10
};
// Mapping of step names to colors.
var colors = {
"core": "#a173d1",
"cpu": "#7b615c",
"boards": "#de783b",
"drivers": "#35a9b5",
"sys": "#5687d1",
"newlib": "#6ab975",
"fill": "#bbbbbb"
};
var DEFAULT_INPUTFILE = 'mem_t.csv'
// Total size of all segments; we set this later, after loading the data.
var totalSize = 0;
var vis;
// the complete dataset
var info;
var dataset;
var cur_view;
var partition = d3.layout.partition()
.size([2 * Math.PI, radius * radius])
.value(function(d) { return d.size; });
var arc = d3.svg.arc()
.startAngle(function(d) { return d.x; })
.endAngle(function(d) { return d.x + d.dx; })
.innerRadius(function(d) { return Math.sqrt(d.y); })
.outerRadius(function(d) { return Math.sqrt(d.y + d.dy); });
function createVisualization() {
// Basic setup of page elements.
initializeBreadcrumbTrail();
drawLegend();
d3.select("#btnExport").on("click", exportstuff);
d3.select("#btnT").on("click", function() {
update(['t']);
});
d3.select("#btnD").on("click", function() {
update(['d']);
});
d3.select("#btnB").on("click", function() {
update(['b']);
});
d3.select("#btnSum").on("click", function() {
update(['t', 'd', 'b']);
});
};
function updateChart(data) {
d3.select("#chart svg").remove();
vis = d3.select("#chart").append("svg:svg")
.attr("width", width)
.attr("height", height)
.append("svg:g")
.attr("id", "container")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// Bounding circle underneath the sunburst, to make it easier to detect
// when the mouse leaves the parent g.
vis.append("svg:circle")
.attr("r", radius)
.style("opacity", 0);
var nodes = partition.nodes(data);
var path = vis.data([data]).selectAll("path")
.data(nodes)
.enter().append("svg:path")
.attr("display", function(d) { return d.depth ? null : "none"; })
.attr("d", arc)
.attr("fill-rule", "evenodd")
.style("fill", function(d) {
tmp = d;
if (!tmp.parent) {
return "#333";
}
while (tmp.parent.parent) {
tmp = tmp.parent;
}
return d3.rgb(colors[tmp.name]).darker(d.depth / 6);
})
.style("opacity", 1)
.on("click", zoomIn)
.on("mouseover", mouseover)
.append("text").attr("dx", 12).attr("dy", ".35em").text(function(d) {return d.name });
// Add the mouseleave handler to the bounding circle.
d3.select("#container")
.on("mouseleave", mouseleave)
.on("contextmenu", zoomOut);
// Get total size of the tree = value of root node from partition.
totalSize = path.node().__data__.value;
d3.select("#expl_per").text("100%");
d3.select("#expl_sym").text(info.app);
d3.select("#expl_size").text(totalSize + " byte");
};
// export svg to pdf of something else
function exportstuff(d) {
console.log("ding ding", d);
};
function zoomIn(d) {
console.log("zoom", d);
updateChart(d);
};
function zoomOut(d) {
d3.event.preventDefault();
console.log("right click", d);
updateChart(cur_view);
};
function updateTable(d) {
var table = d3.select("#table");
table.selectAll("tbody").remove();
var body = table.append("tbody");
tableAdd(d, body, 1);
};
function tableAdd(d, body, layer) {
var row = body.append("tr").classed("l" + layer, true);
row.append("td").text(d.name);
row.append("td").text(d.value).classed("size", true);
if (d.children && layer < 2) {
for (var i = 0; i < d.children.length; i++) {
tableAdd(d.children[i], body, layer + 1);
}
}
};
// Fade all but the current sequence, and show it in the breadcrumb trail.
function mouseover(d) {
updateTable(d);
var percentage = (100 * d.value / totalSize).toPrecision(3);
var percentageString = percentage + "%";
if (percentage < 0.1) {
percentageString = "< 0.1%";
}
d3.select("#expl_per").text(percentageString);
d3.select("#expl_sym").text(d.name);
d3.select("#expl_size").text(d.value + " byte");
// d3.select("#explanation")
// .style("visibility", "");
var sequenceArray = getAncestors(d);
updateBreadcrumbs(sequenceArray, percentageString);
// Fade all the segments.
d3.selectAll("path")
.style("opacity", 0.3);
// Then highlight only those that are an ancestor of the current segment.
vis.selectAll("path")
.filter(function(node) {
return (sequenceArray.indexOf(node) >= 0);
})
.style("opacity", 1);
}
// Restore everything to full opacity when moving off the visualization.
function mouseleave(d) {
updateTable(d);
var name = (d.name == 'root') ? info['app'] : d.name;
// show generic stats
d3.select("#expl_per").text("100%");
d3.select("#expl_sym").text(name);
d3.select("#expl_size").text(totalSize + " byte");
// Hide the breadcrumb trail
d3.select("#trail")
.style("visibility", "hidden");
// Deactivate all segments during transition.
d3.selectAll("path").on("mouseover", null);
// Transition each segment to full opacity and then reactivate it.
d3.selectAll("path")
.transition()
.duration(100)
.style("opacity", 1)
.each("end", function() {
d3.select(this).on("mouseover", mouseover);
});
// d3.select("#explanation")
// .style("visibility", "hidden");
}
// Given a node in a partition layout, return an array of all of its ancestor
// nodes, highest first, but excluding the root.
function getAncestors(node) {
var path = [];
var current = node;
while (current.parent) {
path.unshift(current);
current = current.parent;
}
return path;
}
function initializeBreadcrumbTrail() {
// Add the svg area.
var trail = d3.select("#sequence").append("svg:svg")
.attr("width", width)
.attr("height", 50)
.attr("id", "trail");
// Add the label at the end, for the percentage.
trail.append("svg:text")
.attr("id", "endlabel")
.style("fill", "#000");
}
// Generate a string that describes the points of a breadcrumb polygon.
function breadcrumbPoints(d, i) {
var points = [];
points.push("0,0");
points.push(b.w + ",0");
points.push(b.w + b.t + "," + (b.h / 2));
points.push(b.w + "," + b.h);
points.push("0," + b.h);
if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.
points.push(b.t + "," + (b.h / 2));
}
return points.join(" ");
}
// Update the breadcrumb trail to show the current sequence and percentage.
function updateBreadcrumbs(nodeArray, percentageString) {
// Data join; key function combines name and depth (= position in sequence).
var g = d3.select("#trail")
.selectAll("g")
.data(nodeArray, function(d) { return d.name + d.depth; });
// Add breadcrumb and label for entering nodes.
var entering = g.enter().append("svg:g");
entering.append("svg:polygon")
.attr("points", breadcrumbPoints)
// .style("fill", function(d) { return colors[d.name]; });
.style("fill", function(d) {
return d3.rgb(colors[nodeArray[0].name]).darker(d.depth / 6);
});
entering.append("svg:text")
.attr("x", (b.w + b.t) / 2)
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; });
// Set position for entering and updating nodes.
g.attr("transform", function(d, i) {
return "translate(" + i * (b.w + b.s) + ", 0)";
});
// Remove exiting nodes.
g.exit().remove();
// Now move and update the percentage at the end.
d3.select("#trail").select("#endlabel")
.attr("x", (nodeArray.length + 0.5) * (b.w + b.s))
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(percentageString);
// Make the breadcrumb trail visible, if it's hidden.
d3.select("#trail")
.style("visibility", "");
}
function drawLegend() {
// Dimensions of legend item: width, height, spacing, radius of rounded rect.
var li = {
w: 75, h: 30, s: 3, r: 3
};
d3.select("#legend svg").remove();
var legend = d3.select("#legend").append("svg:svg")
.attr("width", li.w)
.attr("height", d3.keys(colors).length * (li.h + li.s));
var g = legend.selectAll("g")
.data(d3.entries(colors))
.enter().append("svg:g")
.attr("transform", function(d, i) {
return "translate(0," + i * (li.h + li.s) + ")";
});
g.append("svg:rect")
.attr("rx", li.r)
.attr("ry", li.r)
.attr("width", li.w)
.attr("height", li.h)
.style("fill", function(d) { return d.value; });
g.append("svg:text")
.attr("x", li.w / 2)
.attr("y", li.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.key; });
legend.style("visibility", "");
}
function filter(type, depth, root) {
if (!root) {
root = info['app']; /* put application name here */
}
var r = {'name': root, 'children': []};
for (var i = 0; i < dataset.length; i++) {
// filter only requested types
if (type.indexOf(dataset[i].type) == -1) {
continue;
}
// add element to tree
var e = r;
var path = dataset[i]['path'].slice();
path.push(dataset[i]['obj'])
for (var j = 0; j < path.length; j++) |
/* build the branch, now adding the leaf */
e.children.push({'name': dataset[i]['sym'], 'size': dataset[i]['size']});
}
return r;
}
function update(fil) {
cur_view = {};
cur_view = filter(fil);
updateChart(cur_view);
updateTable(cur_view);
}
// bootstrap the whole damn thing
createVisualization();
d3.json("symbols.json", function(data) {
info = data;
dataset = data['symbols'];
update(['t']);
});
| {
var child = undefined;
// search for part
for (var k = 0; k < e.children.length; k++) {
if (e.children[k]['name'] == path[j]) {
child = e.children[k];
}
}
if (!child) {
e.children.push({'name': path[j], 'children': []}) - 1;
child = e.children[e.children.length - 1];
}
e = child;
} | conditional_block |
sunburst.js | /*
* Copyright 2013 Google Inc. All Rights Reserved.
* 2015 Hauke Petersen <devel@haukepetersen.de>
*
* 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.
*
* @author Kerry Rodden
* @author Hauke Petersen <devel@haukepetersen.de>
*/
// Dimensions of sunburst.
var width = 900;
var height = 900;
var radius = Math.min(width, height) / 2;
// Breadcrumb dimensions: width, height, spacing, width of tip/tail.
var b = {
w: 100, h: 30, s: 3, t: 10
};
// Mapping of step names to colors.
var colors = {
"core": "#a173d1",
"cpu": "#7b615c",
"boards": "#de783b",
"drivers": "#35a9b5",
"sys": "#5687d1",
"newlib": "#6ab975",
"fill": "#bbbbbb"
};
var DEFAULT_INPUTFILE = 'mem_t.csv'
// Total size of all segments; we set this later, after loading the data.
var totalSize = 0;
var vis;
// the complete dataset
var info;
var dataset;
var cur_view;
var partition = d3.layout.partition()
.size([2 * Math.PI, radius * radius])
.value(function(d) { return d.size; });
var arc = d3.svg.arc()
.startAngle(function(d) { return d.x; })
.endAngle(function(d) { return d.x + d.dx; })
.innerRadius(function(d) { return Math.sqrt(d.y); })
.outerRadius(function(d) { return Math.sqrt(d.y + d.dy); });
function createVisualization() {
// Basic setup of page elements.
initializeBreadcrumbTrail();
drawLegend();
d3.select("#btnExport").on("click", exportstuff);
d3.select("#btnT").on("click", function() {
update(['t']);
});
d3.select("#btnD").on("click", function() {
update(['d']);
});
d3.select("#btnB").on("click", function() {
update(['b']);
});
d3.select("#btnSum").on("click", function() {
update(['t', 'd', 'b']);
});
};
function updateChart(data) {
d3.select("#chart svg").remove();
vis = d3.select("#chart").append("svg:svg")
.attr("width", width)
.attr("height", height)
.append("svg:g")
.attr("id", "container")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// Bounding circle underneath the sunburst, to make it easier to detect
// when the mouse leaves the parent g.
vis.append("svg:circle")
.attr("r", radius)
.style("opacity", 0);
var nodes = partition.nodes(data);
var path = vis.data([data]).selectAll("path")
.data(nodes)
.enter().append("svg:path")
.attr("display", function(d) { return d.depth ? null : "none"; })
.attr("d", arc)
.attr("fill-rule", "evenodd")
.style("fill", function(d) {
tmp = d;
if (!tmp.parent) {
return "#333";
}
while (tmp.parent.parent) {
tmp = tmp.parent;
}
return d3.rgb(colors[tmp.name]).darker(d.depth / 6);
})
.style("opacity", 1)
.on("click", zoomIn)
.on("mouseover", mouseover)
.append("text").attr("dx", 12).attr("dy", ".35em").text(function(d) {return d.name });
// Add the mouseleave handler to the bounding circle.
d3.select("#container")
.on("mouseleave", mouseleave)
.on("contextmenu", zoomOut);
// Get total size of the tree = value of root node from partition.
totalSize = path.node().__data__.value;
d3.select("#expl_per").text("100%");
d3.select("#expl_sym").text(info.app);
d3.select("#expl_size").text(totalSize + " byte");
};
// export svg to pdf of something else
function exportstuff(d) {
console.log("ding ding", d);
};
function zoomIn(d) {
console.log("zoom", d);
updateChart(d);
};
function zoomOut(d) {
d3.event.preventDefault();
console.log("right click", d);
updateChart(cur_view);
};
function updateTable(d) | ;
function tableAdd(d, body, layer) {
var row = body.append("tr").classed("l" + layer, true);
row.append("td").text(d.name);
row.append("td").text(d.value).classed("size", true);
if (d.children && layer < 2) {
for (var i = 0; i < d.children.length; i++) {
tableAdd(d.children[i], body, layer + 1);
}
}
};
// Fade all but the current sequence, and show it in the breadcrumb trail.
function mouseover(d) {
updateTable(d);
var percentage = (100 * d.value / totalSize).toPrecision(3);
var percentageString = percentage + "%";
if (percentage < 0.1) {
percentageString = "< 0.1%";
}
d3.select("#expl_per").text(percentageString);
d3.select("#expl_sym").text(d.name);
d3.select("#expl_size").text(d.value + " byte");
// d3.select("#explanation")
// .style("visibility", "");
var sequenceArray = getAncestors(d);
updateBreadcrumbs(sequenceArray, percentageString);
// Fade all the segments.
d3.selectAll("path")
.style("opacity", 0.3);
// Then highlight only those that are an ancestor of the current segment.
vis.selectAll("path")
.filter(function(node) {
return (sequenceArray.indexOf(node) >= 0);
})
.style("opacity", 1);
}
// Restore everything to full opacity when moving off the visualization.
function mouseleave(d) {
updateTable(d);
var name = (d.name == 'root') ? info['app'] : d.name;
// show generic stats
d3.select("#expl_per").text("100%");
d3.select("#expl_sym").text(name);
d3.select("#expl_size").text(totalSize + " byte");
// Hide the breadcrumb trail
d3.select("#trail")
.style("visibility", "hidden");
// Deactivate all segments during transition.
d3.selectAll("path").on("mouseover", null);
// Transition each segment to full opacity and then reactivate it.
d3.selectAll("path")
.transition()
.duration(100)
.style("opacity", 1)
.each("end", function() {
d3.select(this).on("mouseover", mouseover);
});
// d3.select("#explanation")
// .style("visibility", "hidden");
}
// Given a node in a partition layout, return an array of all of its ancestor
// nodes, highest first, but excluding the root.
function getAncestors(node) {
var path = [];
var current = node;
while (current.parent) {
path.unshift(current);
current = current.parent;
}
return path;
}
function initializeBreadcrumbTrail() {
// Add the svg area.
var trail = d3.select("#sequence").append("svg:svg")
.attr("width", width)
.attr("height", 50)
.attr("id", "trail");
// Add the label at the end, for the percentage.
trail.append("svg:text")
.attr("id", "endlabel")
.style("fill", "#000");
}
// Generate a string that describes the points of a breadcrumb polygon.
function breadcrumbPoints(d, i) {
var points = [];
points.push("0,0");
points.push(b.w + ",0");
points.push(b.w + b.t + "," + (b.h / 2));
points.push(b.w + "," + b.h);
points.push("0," + b.h);
if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.
points.push(b.t + "," + (b.h / 2));
}
return points.join(" ");
}
// Update the breadcrumb trail to show the current sequence and percentage.
function updateBreadcrumbs(nodeArray, percentageString) {
// Data join; key function combines name and depth (= position in sequence).
var g = d3.select("#trail")
.selectAll("g")
.data(nodeArray, function(d) { return d.name + d.depth; });
// Add breadcrumb and label for entering nodes.
var entering = g.enter().append("svg:g");
entering.append("svg:polygon")
.attr("points", breadcrumbPoints)
// .style("fill", function(d) { return colors[d.name]; });
.style("fill", function(d) {
return d3.rgb(colors[nodeArray[0].name]).darker(d.depth / 6);
});
entering.append("svg:text")
.attr("x", (b.w + b.t) / 2)
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; });
// Set position for entering and updating nodes.
g.attr("transform", function(d, i) {
return "translate(" + i * (b.w + b.s) + ", 0)";
});
// Remove exiting nodes.
g.exit().remove();
// Now move and update the percentage at the end.
d3.select("#trail").select("#endlabel")
.attr("x", (nodeArray.length + 0.5) * (b.w + b.s))
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(percentageString);
// Make the breadcrumb trail visible, if it's hidden.
d3.select("#trail")
.style("visibility", "");
}
function drawLegend() {
// Dimensions of legend item: width, height, spacing, radius of rounded rect.
var li = {
w: 75, h: 30, s: 3, r: 3
};
d3.select("#legend svg").remove();
var legend = d3.select("#legend").append("svg:svg")
.attr("width", li.w)
.attr("height", d3.keys(colors).length * (li.h + li.s));
var g = legend.selectAll("g")
.data(d3.entries(colors))
.enter().append("svg:g")
.attr("transform", function(d, i) {
return "translate(0," + i * (li.h + li.s) + ")";
});
g.append("svg:rect")
.attr("rx", li.r)
.attr("ry", li.r)
.attr("width", li.w)
.attr("height", li.h)
.style("fill", function(d) { return d.value; });
g.append("svg:text")
.attr("x", li.w / 2)
.attr("y", li.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.key; });
legend.style("visibility", "");
}
function filter(type, depth, root) {
if (!root) {
root = info['app']; /* put application name here */
}
var r = {'name': root, 'children': []};
for (var i = 0; i < dataset.length; i++) {
// filter only requested types
if (type.indexOf(dataset[i].type) == -1) {
continue;
}
// add element to tree
var e = r;
var path = dataset[i]['path'].slice();
path.push(dataset[i]['obj'])
for (var j = 0; j < path.length; j++) {
var child = undefined;
// search for part
for (var k = 0; k < e.children.length; k++) {
if (e.children[k]['name'] == path[j]) {
child = e.children[k];
}
}
if (!child) {
e.children.push({'name': path[j], 'children': []}) - 1;
child = e.children[e.children.length - 1];
}
e = child;
}
/* build the branch, now adding the leaf */
e.children.push({'name': dataset[i]['sym'], 'size': dataset[i]['size']});
}
return r;
}
function update(fil) {
cur_view = {};
cur_view = filter(fil);
updateChart(cur_view);
updateTable(cur_view);
}
// bootstrap the whole damn thing
createVisualization();
d3.json("symbols.json", function(data) {
info = data;
dataset = data['symbols'];
update(['t']);
});
| {
var table = d3.select("#table");
table.selectAll("tbody").remove();
var body = table.append("tbody");
tableAdd(d, body, 1);
} | identifier_body |
RaceData.js | var RaceData = {
human: {
name: 'Human',
physical: 6,
personal: 6, | genders: 'male|female',
},
dwarf: {
name: 'Dwarf',
physical: 8,
personal: 0,
mental: 4,
magical: 4,
genders: 'male',
defenses: { moist:5 },
},
elf: {
name: 'Elf',
physical: 0,
personal: 6,
mental: 2,
magical: 8,
genders: 'female',
abilities: ['royalRainbow'],
defenses: { sad:5 },
},
troll: {
name: 'Troll',
physical: 12,
personal: 2,
mental: 0,
magical: 2,
genders: 'male',
abilities: ['biteAttack'],
defenses: { slash:1, crush:1 },
}
}; | mental: 4,
magical: 0, | random_line_split |
ajax.js | jQuery(document).ready(function(){
jQuery("#ResponsiveContactForm").validate({
submitHandler: function(form)
{
jQuery.ajax({
type: "POST",
dataType: "json",
url:MyAjax,
data:{
action: 'ai_action',
fdata : jQuery(document.formValidate).serialize()
},
success:function(response) {
if(response == 1) | else if(response == 2){
jQuery("#fmsg").slideDown(function(){
jQuery(this).show().delay(8000).slideUp("fast")});
jQuery("#captcha").removeClass("valid").addClass("error");
jQuery("#captcha").next('label.valid').removeClass("valid").addClass("error");
jQuery('#captcha').val('');
refreshCaptcha();
}else{
alert(response);
}
}
});
}
});
}); | {
jQuery("#smsg").slideDown(function(){
jQuery('html, body').animate({scrollTop: jQuery("#smsg").offset().top},'fast');
jQuery(this).show().delay(8000).slideUp("fast")});
document.getElementById('ResponsiveContactForm').reset();
refreshCaptcha();
jQuery(".input-xlarge").removeClass("valid");
jQuery(".input-xlarge").next('label.valid').remove();
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.