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 |
|---|---|---|---|---|
blob_storage.rs | use services::blob_storage::BlobStorageService;
use std::rc::Rc;
use errors::prelude::*;
pub enum BlobStorageCommand {
OpenReader(
String, // type
String, // config
Box<Fn(IndyResult<i32 /* handle */>) + Send>),
OpenWriter(
String, // writer type
String, // writer config JSON
Box<Fn(IndyResult<i32 /* handle */>) + Send>),
}
pub struct BlobStorageCommandExecutor {
blob_storage_service: Rc<BlobStorageService>
}
impl BlobStorageCommandExecutor {
pub fn new(blob_storage_service: Rc<BlobStorageService>) -> BlobStorageCommandExecutor {
BlobStorageCommandExecutor {
blob_storage_service
}
}
pub fn | (&self, command: BlobStorageCommand) {
match command {
BlobStorageCommand::OpenReader(type_, config, cb) => {
info!("OpenReader command received");
cb(self.open_reader(&type_, &config));
}
BlobStorageCommand::OpenWriter(writer_type, writer_config, cb) => {
info!("OpenWriter command received");
cb(self.open_writer(&writer_type, &writer_config));
}
}
}
fn open_reader(&self, type_: &str, config: &str) -> IndyResult<i32> {
debug!("open_reader >>> type_: {:?}, config: {:?}", type_, config);
let res = self.blob_storage_service.open_reader(type_, config).map_err(IndyError::from);
debug!("open_reader << res: {:?}", res);
res
}
fn open_writer(&self, type_: &str, config: &str) -> IndyResult<i32> {
debug!("open_writer >>> type_: {:?}, config: {:?}", type_, config);
let res = self.blob_storage_service.open_writer(type_, config).map_err(IndyError::from);
debug!("open_writer << res: {:?}", res);
res
}
}
| execute | identifier_name |
blob_storage.rs | use services::blob_storage::BlobStorageService;
use std::rc::Rc;
use errors::prelude::*;
pub enum BlobStorageCommand {
OpenReader(
String, // type
String, // config
Box<Fn(IndyResult<i32 /* handle */>) + Send>),
OpenWriter(
String, // writer type
String, // writer config JSON
Box<Fn(IndyResult<i32 /* handle */>) + Send>),
}
pub struct BlobStorageCommandExecutor {
blob_storage_service: Rc<BlobStorageService>
}
impl BlobStorageCommandExecutor {
pub fn new(blob_storage_service: Rc<BlobStorageService>) -> BlobStorageCommandExecutor {
BlobStorageCommandExecutor {
blob_storage_service
}
}
pub fn execute(&self, command: BlobStorageCommand) {
match command {
BlobStorageCommand::OpenReader(type_, config, cb) => {
info!("OpenReader command received");
cb(self.open_reader(&type_, &config));
}
BlobStorageCommand::OpenWriter(writer_type, writer_config, cb) => {
info!("OpenWriter command received");
cb(self.open_writer(&writer_type, &writer_config));
}
}
}
fn open_reader(&self, type_: &str, config: &str) -> IndyResult<i32> |
fn open_writer(&self, type_: &str, config: &str) -> IndyResult<i32> {
debug!("open_writer >>> type_: {:?}, config: {:?}", type_, config);
let res = self.blob_storage_service.open_writer(type_, config).map_err(IndyError::from);
debug!("open_writer << res: {:?}", res);
res
}
}
| {
debug!("open_reader >>> type_: {:?}, config: {:?}", type_, config);
let res = self.blob_storage_service.open_reader(type_, config).map_err(IndyError::from);
debug!("open_reader << res: {:?}", res);
res
} | identifier_body |
filters.component.ts | import { FilterService, Filter, FilterTree, FilterType, FilterIndex } from 'lib/filter';
import { Component, EventEmitter, OnInit, Input, Output } from '@angular/core';
@Component({
selector: 'iw-filters',
templateUrl: './filters.component.html',
styleUrls: ['./filters.component.css'],
providers: [FilterService]
})
export class FiltersComponent implements OnInit {
@Input() rows: any[];
// @Input() keys: string[];
@Input() filters: Filter[] = [];
@Input() overrideFilters: FilterIndex = {};
@Input() advancedFiltering = false; // Disabled by default.
@Input() operator: 'and' | 'or' = 'and';
@Output() filter = new EventEmitter<any[]>();
constructor(private filterService: FilterService) { }
ngOnInit() {
this.filters = this.filterService.detectFilters(this.rows, this.overrideFilters);
this.createNestedFilters();
}
getLabel(filter: Filter) {
return filter.label ? filter.label : filter.key;
}
filterAnyFields(value: any) {
const filterTree: FilterTree = {
operator: 'or',
filters: this.filters.map((f) => {
f.value = value;
return f;
})
};
const filtered = this.filterService.filterByTree(this.rows, filterTree);
this.filter.emit(filtered);
}
toggleAdvancedFiltering() {
this.advancedFiltering = !this.advancedFiltering;
}
| (operator: 'and' | 'or') {
this.operator = operator;
this.executeFiltering();
}
onFilterChange() {
this.executeFiltering();
}
isSimpleFilter(filter: Filter) {
return [FilterType.Array, FilterType.Object].indexOf(filter.type) < 0;
}
executeFiltering() {
const filterTree = {
operator: this.operator,
filters: this.filters
};
const filteredRows = this.filterService.filterByTree(this.rows, filterTree);
this.filter.emit(filteredRows);
}
onNestedFilterChange(filter: Filter, nestedFilter: Filter) {
filter.value = (<Filter[]>filter.filters).some((nf: any) => nf.value) ? 'any' : undefined;
this.executeFiltering();
}
private createNestedFilters() {
this.filters.forEach((filter) => {
const parentFilter = this.filters.find(f => f.key === filter.key);
if (parentFilter) {
if (filter.type === FilterType.Array) {
parentFilter.filters = this.filterService
.detectFilters(this.getSubRows(filter.key));
} else if (filter.type === FilterType.Object) {
parentFilter.filters = this.filterService
.detectFilters(this.getNestedObjects(filter.key));
}
}
});
}
private getNestedObjects(key: string) {
return this.rows.reduce((result, row) => {
result.push(row[key]);
return result;
}, []);
}
private getSubRows(key: string) {
return this.rows.reduce((result, row) => result.concat(row[key]), []);
}
}
| changeOperator | identifier_name |
filters.component.ts | import { FilterService, Filter, FilterTree, FilterType, FilterIndex } from 'lib/filter';
import { Component, EventEmitter, OnInit, Input, Output } from '@angular/core';
@Component({
selector: 'iw-filters',
templateUrl: './filters.component.html',
styleUrls: ['./filters.component.css'],
providers: [FilterService]
})
export class FiltersComponent implements OnInit {
@Input() rows: any[];
// @Input() keys: string[];
@Input() filters: Filter[] = [];
@Input() overrideFilters: FilterIndex = {};
@Input() advancedFiltering = false; // Disabled by default.
@Input() operator: 'and' | 'or' = 'and';
@Output() filter = new EventEmitter<any[]>();
constructor(private filterService: FilterService) { }
ngOnInit() {
this.filters = this.filterService.detectFilters(this.rows, this.overrideFilters);
this.createNestedFilters();
}
getLabel(filter: Filter) {
return filter.label ? filter.label : filter.key;
}
filterAnyFields(value: any) {
const filterTree: FilterTree = {
operator: 'or',
filters: this.filters.map((f) => {
f.value = value;
return f;
})
};
const filtered = this.filterService.filterByTree(this.rows, filterTree);
this.filter.emit(filtered);
}
toggleAdvancedFiltering() {
this.advancedFiltering = !this.advancedFiltering;
}
changeOperator(operator: 'and' | 'or') {
this.operator = operator;
this.executeFiltering();
}
onFilterChange() {
this.executeFiltering();
}
isSimpleFilter(filter: Filter) {
return [FilterType.Array, FilterType.Object].indexOf(filter.type) < 0;
}
executeFiltering() {
const filterTree = {
operator: this.operator,
filters: this.filters
};
const filteredRows = this.filterService.filterByTree(this.rows, filterTree);
this.filter.emit(filteredRows);
}
onNestedFilterChange(filter: Filter, nestedFilter: Filter) {
filter.value = (<Filter[]>filter.filters).some((nf: any) => nf.value) ? 'any' : undefined;
this.executeFiltering();
}
private createNestedFilters() {
this.filters.forEach((filter) => {
const parentFilter = this.filters.find(f => f.key === filter.key);
if (parentFilter) {
if (filter.type === FilterType.Array) {
parentFilter.filters = this.filterService
.detectFilters(this.getSubRows(filter.key));
} else if (filter.type === FilterType.Object) {
parentFilter.filters = this.filterService
.detectFilters(this.getNestedObjects(filter.key));
}
}
});
}
private getNestedObjects(key: string) {
return this.rows.reduce((result, row) => {
result.push(row[key]);
return result;
}, []);
}
private getSubRows(key: string) |
}
| {
return this.rows.reduce((result, row) => result.concat(row[key]), []);
} | identifier_body |
filters.component.ts | import { FilterService, Filter, FilterTree, FilterType, FilterIndex } from 'lib/filter';
import { Component, EventEmitter, OnInit, Input, Output } from '@angular/core';
@Component({
selector: 'iw-filters',
templateUrl: './filters.component.html',
styleUrls: ['./filters.component.css'],
providers: [FilterService]
})
export class FiltersComponent implements OnInit {
@Input() rows: any[];
// @Input() keys: string[];
@Input() filters: Filter[] = [];
@Input() overrideFilters: FilterIndex = {};
@Input() advancedFiltering = false; // Disabled by default.
@Input() operator: 'and' | 'or' = 'and';
@Output() filter = new EventEmitter<any[]>();
constructor(private filterService: FilterService) { }
ngOnInit() {
this.filters = this.filterService.detectFilters(this.rows, this.overrideFilters);
this.createNestedFilters();
} | filterAnyFields(value: any) {
const filterTree: FilterTree = {
operator: 'or',
filters: this.filters.map((f) => {
f.value = value;
return f;
})
};
const filtered = this.filterService.filterByTree(this.rows, filterTree);
this.filter.emit(filtered);
}
toggleAdvancedFiltering() {
this.advancedFiltering = !this.advancedFiltering;
}
changeOperator(operator: 'and' | 'or') {
this.operator = operator;
this.executeFiltering();
}
onFilterChange() {
this.executeFiltering();
}
isSimpleFilter(filter: Filter) {
return [FilterType.Array, FilterType.Object].indexOf(filter.type) < 0;
}
executeFiltering() {
const filterTree = {
operator: this.operator,
filters: this.filters
};
const filteredRows = this.filterService.filterByTree(this.rows, filterTree);
this.filter.emit(filteredRows);
}
onNestedFilterChange(filter: Filter, nestedFilter: Filter) {
filter.value = (<Filter[]>filter.filters).some((nf: any) => nf.value) ? 'any' : undefined;
this.executeFiltering();
}
private createNestedFilters() {
this.filters.forEach((filter) => {
const parentFilter = this.filters.find(f => f.key === filter.key);
if (parentFilter) {
if (filter.type === FilterType.Array) {
parentFilter.filters = this.filterService
.detectFilters(this.getSubRows(filter.key));
} else if (filter.type === FilterType.Object) {
parentFilter.filters = this.filterService
.detectFilters(this.getNestedObjects(filter.key));
}
}
});
}
private getNestedObjects(key: string) {
return this.rows.reduce((result, row) => {
result.push(row[key]);
return result;
}, []);
}
private getSubRows(key: string) {
return this.rows.reduce((result, row) => result.concat(row[key]), []);
}
} |
getLabel(filter: Filter) {
return filter.label ? filter.label : filter.key;
}
| random_line_split |
lib.rs | #![crate_type="dylib"]
#![feature(plugin_registrar)]
#![deny(warnings)]
#![allow(unstable)]
extern crate syntax;
extern crate sodiumoxide;
#[macro_use] extern crate rustc;
use std::borrow::ToOwned;
use std::io::File;
use syntax::ast;
use syntax::visit;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::Span;
use rustc::lint::{Context, LintPass, LintPassObject, LintArray};
use rustc::plugin::Registry;
use rustc::session::Session;
use sodiumoxide::crypto::sign;
use sodiumoxide::crypto::sign::{PublicKey, SecretKey};
use validator::Validator;
mod validator;
fn read_key(sess: &Session, buf: &mut [u8], filename: &str) {
let mut file = match File::open(&Path::new(filename)) {
Err(e) => {
sess.err(format!("could not open key file {}: {:?}", filename, e).as_slice());
return;
}
Ok(f) => f,
};
match file.read(buf) {
Ok(n) if n == buf.len() => (),
r => sess.err(format!("could not read full key from key file {}: got {:?}",
filename, r).as_slice()),
}
}
fn write_key(buf: &[u8], path: &Path) {
let mut file = File::create(path).unwrap();
file.write(buf).unwrap();
}
/// Generate a key pair and write it out as two files.
pub fn gen_keypair(pubkey: &Path, seckey: &Path) {
let (pk, sk) = sign::gen_keypair();
write_key(pk.0.as_slice(), pubkey);
write_key(sk.0.as_slice(), seckey);
}
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
sodiumoxide::init();
let mut pubkey = None;
let mut seckey = None;
{
let args = match reg.args().meta_item_list() {
Some(args) => args,
None => {
reg.sess.span_err(reg.args().span,
r#"usage: #[plugin(public_key="filename", ...)]"#);
return;
}
};
macro_rules! read_key {
($attr:expr, $size:expr) => ({
let mut k = [0u8; $size];
if let Some(filename) = $attr.value_str() {
read_key(reg.sess, k.as_mut_slice(), filename.get());
Some(k)
} else {
None
}
});
}
for attr in args.iter() {
if attr.check_name("public_key") {
pubkey = read_key!(attr, sign::PUBLICKEYBYTES);
} else if attr.check_name("secret_key") {
seckey = read_key!(attr, sign::SECRETKEYBYTES);
} else {
reg.sess.span_err(attr.span, "unknown argument");
}
}
}
let pubkey = match pubkey {
None => {
reg.sess.span_err(reg.args().span, "public key must be specified");
return;
}
Some(k) => k,
};
let pass = Pass {
authenticated_parent: None,
pubkey: PublicKey(pubkey),
seckey: seckey.map(|k| SecretKey(k)),
};
reg.register_lint_pass(Box::new(pass) as LintPassObject);
}
// Is `child` a child of `parent` in the AST?
fn child_of(cx: &Context, child: ast::NodeId, parent: ast::NodeId) -> bool {
let mut id = child;
loop {
if id == parent { return true; }
match cx.tcx.map.get_parent(id) {
i if i == id => return false, // no parent
i => id = i,
}
}
}
// Grab a span of bytes from the original source file.
fn snip(cx: &Context, span: Span) -> Vec<u8> {
match cx.sess().codemap().span_to_snippet(span) {
None => {
cx.sess().span_err(span, "can't get snippet");
vec![]
}
Some(s) => s.into_bytes(),
}
}
declare_lint!(UNAUTHORIZED_UNSAFE, Warn, "unauthorized unsafe blocks");
declare_lint!(WRONG_LAUNCH_CODE, Warn, "incorrect #[launch_code] attributes");
struct Pass {
authenticated_parent: Option<ast::NodeId>,
pubkey: PublicKey,
seckey: Option<SecretKey>,
}
impl Pass {
// Warn if this AST node does not have an authenticated ancestor.
fn | (&self, cx: &Context, span: Span, id: ast::NodeId) {
if match self.authenticated_parent {
None => true,
Some(p) => !child_of(cx, id, p),
} {
cx.span_lint(UNAUTHORIZED_UNSAFE, span, "unauthorized unsafe block");
}
}
// Check a function's #[launch_code] attribute, if any.
fn authenticate(&mut self,
cx: &Context,
attrs: &[ast::Attribute],
span: Span,
id: ast::NodeId) {
let mut launch_code = None;
let mut val = Validator::new();
for attr in attrs.iter() {
if attr.check_name("launch_code") {
let value = attr.value_str()
.map(|s| s.get().to_owned())
.unwrap_or_else(|| "".to_owned());
launch_code = Some((attr.span, value));
} else {
// Authenticate all attributes other than #[launch_code] itself.
// This includes doc comments and attribute order.
val.write(snip(cx, attr.span).as_slice());
}
}
let launch_code = match launch_code {
Some(c) => c,
None => return,
};
// Authenticate the function arguments and body.
val.write(snip(cx, span).as_slice());
if val.verify(launch_code.1.as_slice(), &self.pubkey) {
self.authenticated_parent = Some(id);
} else {
let msg = match self.seckey.as_ref() {
None => "incorrect launch code".to_owned(),
Some(sk) => format!("correct launch code is {}", val.compute(sk)),
};
cx.span_lint(WRONG_LAUNCH_CODE, launch_code.0, msg.as_slice());
}
}
}
impl LintPass for Pass {
fn get_lints(&self) -> LintArray {
lint_array!(UNAUTHORIZED_UNSAFE, WRONG_LAUNCH_CODE)
}
fn check_block(&mut self,
cx: &Context,
block: &ast::Block) {
match block.rules {
ast::DefaultBlock => (),
ast::UnsafeBlock(..) => self.authorize(cx, block.span, block.id),
}
}
fn check_fn(&mut self,
cx: &Context,
fk: visit::FnKind,
_: &ast::FnDecl,
_: &ast::Block,
span: Span,
id: ast::NodeId) {
if match fk {
visit::FkItemFn(_, _, ast::Unsafety::Unsafe, _) => true,
visit::FkItemFn(..) => false,
visit::FkMethod(_, _, m) => match m.node {
ast::MethDecl(_, _, _, _, ast::Unsafety::Unsafe, _, _, _) => true,
ast::MethDecl(..) => false,
ast::MethMac(..) => cx.sess().bug("method macro remains during lint pass"),
},
// closures inherit unsafety from the context
visit::FkFnBlock => false,
} {
self.authorize(cx, span, id);
}
}
fn check_ty_method(&mut self, cx: &Context, m: &ast::TypeMethod) {
self.authenticate(cx, &m.attrs[], m.span, m.id);
}
fn check_trait_method(&mut self, cx: &Context, it: &ast::TraitItem) {
match *it {
ast::RequiredMethod(ref m) => self.authenticate(cx, &m.attrs[], m.span, m.id),
ast::ProvidedMethod(ref m) => self.authenticate(cx, &m.attrs[], m.span, m.id),
ast::TypeTraitItem(..) => (),
}
}
fn check_item(&mut self, cx: &Context, it: &ast::Item) {
self.authenticate(cx, &it.attrs[], it.span, it.id);
}
}
| authorize | identifier_name |
lib.rs | #![crate_type="dylib"]
#![feature(plugin_registrar)]
#![deny(warnings)]
#![allow(unstable)]
extern crate syntax;
extern crate sodiumoxide;
#[macro_use] extern crate rustc;
use std::borrow::ToOwned;
use std::io::File;
use syntax::ast;
use syntax::visit;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::Span;
use rustc::lint::{Context, LintPass, LintPassObject, LintArray};
use rustc::plugin::Registry;
use rustc::session::Session;
use sodiumoxide::crypto::sign;
use sodiumoxide::crypto::sign::{PublicKey, SecretKey};
use validator::Validator;
mod validator;
fn read_key(sess: &Session, buf: &mut [u8], filename: &str) {
let mut file = match File::open(&Path::new(filename)) {
Err(e) => {
sess.err(format!("could not open key file {}: {:?}", filename, e).as_slice());
return;
}
Ok(f) => f,
};
match file.read(buf) {
Ok(n) if n == buf.len() => (),
r => sess.err(format!("could not read full key from key file {}: got {:?}",
filename, r).as_slice()),
}
}
fn write_key(buf: &[u8], path: &Path) {
let mut file = File::create(path).unwrap();
file.write(buf).unwrap();
}
/// Generate a key pair and write it out as two files.
pub fn gen_keypair(pubkey: &Path, seckey: &Path) {
let (pk, sk) = sign::gen_keypair();
write_key(pk.0.as_slice(), pubkey);
write_key(sk.0.as_slice(), seckey);
}
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
sodiumoxide::init();
let mut pubkey = None;
let mut seckey = None;
{
let args = match reg.args().meta_item_list() {
Some(args) => args,
None => {
reg.sess.span_err(reg.args().span,
r#"usage: #[plugin(public_key="filename", ...)]"#);
return;
}
};
macro_rules! read_key {
($attr:expr, $size:expr) => ({
let mut k = [0u8; $size];
if let Some(filename) = $attr.value_str() {
read_key(reg.sess, k.as_mut_slice(), filename.get());
Some(k)
} else {
None
}
});
}
for attr in args.iter() {
if attr.check_name("public_key") {
pubkey = read_key!(attr, sign::PUBLICKEYBYTES);
} else if attr.check_name("secret_key") {
seckey = read_key!(attr, sign::SECRETKEYBYTES);
} else {
reg.sess.span_err(attr.span, "unknown argument");
}
}
}
let pubkey = match pubkey {
None => {
reg.sess.span_err(reg.args().span, "public key must be specified");
return;
}
Some(k) => k,
};
let pass = Pass {
authenticated_parent: None,
pubkey: PublicKey(pubkey),
seckey: seckey.map(|k| SecretKey(k)),
};
reg.register_lint_pass(Box::new(pass) as LintPassObject);
}
// Is `child` a child of `parent` in the AST?
fn child_of(cx: &Context, child: ast::NodeId, parent: ast::NodeId) -> bool {
let mut id = child;
loop {
if id == parent { return true; }
match cx.tcx.map.get_parent(id) {
i if i == id => return false, // no parent
i => id = i,
}
}
}
// Grab a span of bytes from the original source file.
fn snip(cx: &Context, span: Span) -> Vec<u8> {
match cx.sess().codemap().span_to_snippet(span) {
None => {
cx.sess().span_err(span, "can't get snippet");
vec![]
}
Some(s) => s.into_bytes(),
}
}
declare_lint!(UNAUTHORIZED_UNSAFE, Warn, "unauthorized unsafe blocks");
declare_lint!(WRONG_LAUNCH_CODE, Warn, "incorrect #[launch_code] attributes");
struct Pass {
authenticated_parent: Option<ast::NodeId>,
pubkey: PublicKey,
seckey: Option<SecretKey>,
}
impl Pass {
// Warn if this AST node does not have an authenticated ancestor.
fn authorize(&self, cx: &Context, span: Span, id: ast::NodeId) {
if match self.authenticated_parent {
None => true,
Some(p) => !child_of(cx, id, p),
} {
cx.span_lint(UNAUTHORIZED_UNSAFE, span, "unauthorized unsafe block");
}
}
// Check a function's #[launch_code] attribute, if any.
fn authenticate(&mut self,
cx: &Context,
attrs: &[ast::Attribute],
span: Span,
id: ast::NodeId) {
let mut launch_code = None;
let mut val = Validator::new();
for attr in attrs.iter() {
if attr.check_name("launch_code") {
let value = attr.value_str()
.map(|s| s.get().to_owned())
.unwrap_or_else(|| "".to_owned());
launch_code = Some((attr.span, value));
} else {
// Authenticate all attributes other than #[launch_code] itself.
// This includes doc comments and attribute order.
val.write(snip(cx, attr.span).as_slice()); |
let launch_code = match launch_code {
Some(c) => c,
None => return,
};
// Authenticate the function arguments and body.
val.write(snip(cx, span).as_slice());
if val.verify(launch_code.1.as_slice(), &self.pubkey) {
self.authenticated_parent = Some(id);
} else {
let msg = match self.seckey.as_ref() {
None => "incorrect launch code".to_owned(),
Some(sk) => format!("correct launch code is {}", val.compute(sk)),
};
cx.span_lint(WRONG_LAUNCH_CODE, launch_code.0, msg.as_slice());
}
}
}
impl LintPass for Pass {
fn get_lints(&self) -> LintArray {
lint_array!(UNAUTHORIZED_UNSAFE, WRONG_LAUNCH_CODE)
}
fn check_block(&mut self,
cx: &Context,
block: &ast::Block) {
match block.rules {
ast::DefaultBlock => (),
ast::UnsafeBlock(..) => self.authorize(cx, block.span, block.id),
}
}
fn check_fn(&mut self,
cx: &Context,
fk: visit::FnKind,
_: &ast::FnDecl,
_: &ast::Block,
span: Span,
id: ast::NodeId) {
if match fk {
visit::FkItemFn(_, _, ast::Unsafety::Unsafe, _) => true,
visit::FkItemFn(..) => false,
visit::FkMethod(_, _, m) => match m.node {
ast::MethDecl(_, _, _, _, ast::Unsafety::Unsafe, _, _, _) => true,
ast::MethDecl(..) => false,
ast::MethMac(..) => cx.sess().bug("method macro remains during lint pass"),
},
// closures inherit unsafety from the context
visit::FkFnBlock => false,
} {
self.authorize(cx, span, id);
}
}
fn check_ty_method(&mut self, cx: &Context, m: &ast::TypeMethod) {
self.authenticate(cx, &m.attrs[], m.span, m.id);
}
fn check_trait_method(&mut self, cx: &Context, it: &ast::TraitItem) {
match *it {
ast::RequiredMethod(ref m) => self.authenticate(cx, &m.attrs[], m.span, m.id),
ast::ProvidedMethod(ref m) => self.authenticate(cx, &m.attrs[], m.span, m.id),
ast::TypeTraitItem(..) => (),
}
}
fn check_item(&mut self, cx: &Context, it: &ast::Item) {
self.authenticate(cx, &it.attrs[], it.span, it.id);
}
} | }
} | random_line_split |
emotion.js | window.onload = function () {
editor.setOpt({
emotionLocalization:false
});
emotion.SmileyPath = editor.options.emotionLocalization === true ? "images/" : "http://img.baidu.com/hi/";
emotion.SmileyBox = createTabList( emotion.tabNum );
emotion.tabExist = createArr( emotion.tabNum );
initImgName();
initEvtHandler( "tabHeads" );
};
function initImgName() {
for ( var pro in emotion.SmilmgName ) {
var tempName = emotion.SmilmgName[pro],
tempBox = emotion.SmileyBox[pro],
tempStr = "";
if ( tempBox.length ) return;
for ( var i = 1; i <= tempName[1]; i++ ) {
tempStr = tempName[0];
if ( i < 10 ) tempStr = tempStr + "0";
tempStr = tempStr + i + ".gif";
tempBox.push( tempStr );
}
}
}
function initEvtHandler( conId ) {
var tabHeads = $G( conId );
for ( var i = 0, j = 0; i < tabHeads.childNodes.length; i++ ) {
var tabObj = tabHeads.childNodes[i];
if ( tabObj.nodeType == 1 ) {
domUtils.on( tabObj, "click", (function ( index ) {
return function () {
switchTab( index );
};
})( j ) );
j++;
}
}
switchTab( 0 );
$G( "tabIconReview" ).style.display = "none";
}
function InsertSmiley( url, evt ) {
var obj = {
src:editor.options.emotionLocalization ? editor.options.UEDITOR_HOME_URL + "dialogs/emotion/" + url : url
};
obj._src = obj.src;
editor.execCommand( "insertimage", obj );
if ( !evt.ctrlKey ) {
dialog.popup.hide();
}
}
function switchTab( index ) {
autoHeight( index );
if ( emotion.tabExist[index] == 0 ) {
emotion.tabExist[index] = 1;
createTab( "tab" + index );
}
//获取呈现元素句柄数组
var tabHeads = $G( "tabHeads" ).getElementsByTagName( "span" ),
tabBodys = $G( "tabBodys" ).getElementsByTagName( "div" ),
i = 0, L = tabHeads.length;
//隐藏所有呈现元素
for ( ; i < L; i++ ) {
tabHeads[i].className = "";
tabBodys[i].style.display = "none";
}
//显示对应呈现元素
tabHeads[index].className = "focus";
tabBodys[index].style.display = "block";
}
function autoHeight( index ) {
var iframe = dialog.getDom | ),
parent = iframe.parentNode.parentNode;
switch ( index ) {
case 0:
iframe.style.height = "380px";
parent.style.height = "392px";
break;
case 1:
iframe.style.height = "220px";
parent.style.height = "232px";
break;
case 2:
iframe.style.height = "260px";
parent.style.height = "272px";
break;
case 3:
iframe.style.height = "300px";
parent.style.height = "312px";
break;
case 4:
iframe.style.height = "140px";
parent.style.height = "152px";
break;
case 5:
iframe.style.height = "260px";
parent.style.height = "272px";
break;
case 6:
iframe.style.height = "230px";
parent.style.height = "242px";
break;
default:
}
}
function createTab( tabName ) {
var faceVersion = "?v=1.1", //版本号
tab = $G( tabName ), //获取将要生成的Div句柄
imagePath = emotion.SmileyPath + emotion.imageFolders[tabName], //获取显示表情和预览表情的路径
positionLine = 11 / 2, //中间数
iWidth = iHeight = 35, //图片长宽
iColWidth = 3, //表格剩余空间的显示比例
tableCss = emotion.imageCss[tabName],
cssOffset = emotion.imageCssOffset[tabName],
textHTML = ['<table class="smileytable">'],
i = 0, imgNum = emotion.SmileyBox[tabName].length, imgColNum = 11, faceImage,
sUrl, realUrl, posflag, offset, infor;
for ( ; i < imgNum; ) {
textHTML.push( "<tr>" );
for ( var j = 0; j < imgColNum; j++, i++ ) {
faceImage = emotion.SmileyBox[tabName][i];
if ( faceImage ) {
sUrl = imagePath + faceImage + faceVersion;
realUrl = imagePath + faceImage;
posflag = j < positionLine ? 0 : 1;
offset = cssOffset * i * (-1) - 1;
infor = emotion.SmileyInfor[tabName][i];
textHTML.push( '<td class="' + tableCss + '" border="1" width="' + iColWidth + '%" style="border-collapse:collapse;" align="center" bgcolor="transparent" onclick="InsertSmiley(\'' + realUrl.replace( /'/g, "\\'" ) + '\',event)" onmouseover="over(this,\'' + sUrl + "','" + posflag + '\')" onmouseout="out(this)">' );
textHTML.push( "<span>" );
textHTML.push( '<img style="background-position:left ' + offset + 'px;" title="' + infor + '" src="' + emotion.SmileyPath + (editor.options.emotionLocalization ? '0.gif" width="' : 'default/0.gif" width="') + iWidth + '" height="' + iHeight + '"></img>' );
textHTML.push( "</span>" );
} else {
textHTML.push( '<td width="' + iColWidth + '%" bgcolor="#FFFFFF">' );
}
textHTML.push( "</td>" );
}
textHTML.push( "</tr>" );
}
textHTML.push( "</table>" );
textHTML = textHTML.join( "" );
tab.innerHTML = textHTML;
}
function over( td, srcPath, posFlag ) {
td.style.backgroundColor = "#ACCD3C";
$G( "faceReview" ).style.backgroundImage = "url(" + srcPath + ")";
if ( posFlag == 1 ) $G( "tabIconReview" ).className = "show";
$G( "tabIconReview" ).style.display = "block";
}
function out( td ) {
td.style.backgroundColor = "transparent";
var tabIconRevew = $G( "tabIconReview" );
tabIconRevew.className = "";
tabIconRevew.style.display = "none";
}
function createTabList( tabNum ) {
var obj = {};
for ( var i = 0; i < tabNum; i++ ) {
obj["tab" + i] = [];
}
return obj;
}
function createArr( tabNum ) {
var arr = [];
for ( var i = 0; i < tabNum; i++ ) {
arr[i] = 0;
}
return arr;
}
| ( "iframe" | identifier_name |
emotion.js | window.onload = function () {
editor.setOpt({
emotionLocalization:false
});
emotion.SmileyPath = editor.options.emotionLocalization === true ? "images/" : "http://img.baidu.com/hi/";
emotion.SmileyBox = createTabList( emotion.tabNum );
emotion.tabExist = createArr( emotion.tabNum );
initImgName();
initEvtHandler( "tabHeads" );
};
function initImgName() |
function initEvtHandler( conId ) {
var tabHeads = $G( conId );
for ( var i = 0, j = 0; i < tabHeads.childNodes.length; i++ ) {
var tabObj = tabHeads.childNodes[i];
if ( tabObj.nodeType == 1 ) {
domUtils.on( tabObj, "click", (function ( index ) {
return function () {
switchTab( index );
};
})( j ) );
j++;
}
}
switchTab( 0 );
$G( "tabIconReview" ).style.display = "none";
}
function InsertSmiley( url, evt ) {
var obj = {
src:editor.options.emotionLocalization ? editor.options.UEDITOR_HOME_URL + "dialogs/emotion/" + url : url
};
obj._src = obj.src;
editor.execCommand( "insertimage", obj );
if ( !evt.ctrlKey ) {
dialog.popup.hide();
}
}
function switchTab( index ) {
autoHeight( index );
if ( emotion.tabExist[index] == 0 ) {
emotion.tabExist[index] = 1;
createTab( "tab" + index );
}
//获取呈现元素句柄数组
var tabHeads = $G( "tabHeads" ).getElementsByTagName( "span" ),
tabBodys = $G( "tabBodys" ).getElementsByTagName( "div" ),
i = 0, L = tabHeads.length;
//隐藏所有呈现元素
for ( ; i < L; i++ ) {
tabHeads[i].className = "";
tabBodys[i].style.display = "none";
}
//显示对应呈现元素
tabHeads[index].className = "focus";
tabBodys[index].style.display = "block";
}
function autoHeight( index ) {
var iframe = dialog.getDom( "iframe" ),
parent = iframe.parentNode.parentNode;
switch ( index ) {
case 0:
iframe.style.height = "380px";
parent.style.height = "392px";
break;
case 1:
iframe.style.height = "220px";
parent.style.height = "232px";
break;
case 2:
iframe.style.height = "260px";
parent.style.height = "272px";
break;
case 3:
iframe.style.height = "300px";
parent.style.height = "312px";
break;
case 4:
iframe.style.height = "140px";
parent.style.height = "152px";
break;
case 5:
iframe.style.height = "260px";
parent.style.height = "272px";
break;
case 6:
iframe.style.height = "230px";
parent.style.height = "242px";
break;
default:
}
}
function createTab( tabName ) {
var faceVersion = "?v=1.1", //版本号
tab = $G( tabName ), //获取将要生成的Div句柄
imagePath = emotion.SmileyPath + emotion.imageFolders[tabName], //获取显示表情和预览表情的路径
positionLine = 11 / 2, //中间数
iWidth = iHeight = 35, //图片长宽
iColWidth = 3, //表格剩余空间的显示比例
tableCss = emotion.imageCss[tabName],
cssOffset = emotion.imageCssOffset[tabName],
textHTML = ['<table class="smileytable">'],
i = 0, imgNum = emotion.SmileyBox[tabName].length, imgColNum = 11, faceImage,
sUrl, realUrl, posflag, offset, infor;
for ( ; i < imgNum; ) {
textHTML.push( "<tr>" );
for ( var j = 0; j < imgColNum; j++, i++ ) {
faceImage = emotion.SmileyBox[tabName][i];
if ( faceImage ) {
sUrl = imagePath + faceImage + faceVersion;
realUrl = imagePath + faceImage;
posflag = j < positionLine ? 0 : 1;
offset = cssOffset * i * (-1) - 1;
infor = emotion.SmileyInfor[tabName][i];
textHTML.push( '<td class="' + tableCss + '" border="1" width="' + iColWidth + '%" style="border-collapse:collapse;" align="center" bgcolor="transparent" onclick="InsertSmiley(\'' + realUrl.replace( /'/g, "\\'" ) + '\',event)" onmouseover="over(this,\'' + sUrl + "','" + posflag + '\')" onmouseout="out(this)">' );
textHTML.push( "<span>" );
textHTML.push( '<img style="background-position:left ' + offset + 'px;" title="' + infor + '" src="' + emotion.SmileyPath + (editor.options.emotionLocalization ? '0.gif" width="' : 'default/0.gif" width="') + iWidth + '" height="' + iHeight + '"></img>' );
textHTML.push( "</span>" );
} else {
textHTML.push( '<td width="' + iColWidth + '%" bgcolor="#FFFFFF">' );
}
textHTML.push( "</td>" );
}
textHTML.push( "</tr>" );
}
textHTML.push( "</table>" );
textHTML = textHTML.join( "" );
tab.innerHTML = textHTML;
}
function over( td, srcPath, posFlag ) {
td.style.backgroundColor = "#ACCD3C";
$G( "faceReview" ).style.backgroundImage = "url(" + srcPath + ")";
if ( posFlag == 1 ) $G( "tabIconReview" ).className = "show";
$G( "tabIconReview" ).style.display = "block";
}
function out( td ) {
td.style.backgroundColor = "transparent";
var tabIconRevew = $G( "tabIconReview" );
tabIconRevew.className = "";
tabIconRevew.style.display = "none";
}
function createTabList( tabNum ) {
var obj = {};
for ( var i = 0; i < tabNum; i++ ) {
obj["tab" + i] = [];
}
return obj;
}
function createArr( tabNum ) {
var arr = [];
for ( var i = 0; i < tabNum; i++ ) {
arr[i] = 0;
}
return arr;
}
| {
for ( var pro in emotion.SmilmgName ) {
var tempName = emotion.SmilmgName[pro],
tempBox = emotion.SmileyBox[pro],
tempStr = "";
if ( tempBox.length ) return;
for ( var i = 1; i <= tempName[1]; i++ ) {
tempStr = tempName[0];
if ( i < 10 ) tempStr = tempStr + "0";
tempStr = tempStr + i + ".gif";
tempBox.push( tempStr );
}
}
} | identifier_body |
emotion.js | window.onload = function () {
editor.setOpt({
emotionLocalization:false
});
emotion.SmileyPath = editor.options.emotionLocalization === true ? "images/" : "http://img.baidu.com/hi/";
emotion.SmileyBox = createTabList( emotion.tabNum );
emotion.tabExist = createArr( emotion.tabNum );
initImgName();
initEvtHandler( "tabHeads" );
};
function initImgName() {
for ( var pro in emotion.SmilmgName ) {
var tempName = emotion.SmilmgName[pro],
tempBox = emotion.SmileyBox[pro],
tempStr = "";
if ( tempBox.length ) return;
for ( var i = 1; i <= tempName[1]; i++ ) {
tempStr = tempName[0];
if ( i < 10 ) tempStr = tempStr + "0";
tempStr = tempStr + i + ".gif";
tempBox.push( tempStr );
}
}
}
function initEvtHandler( conId ) {
var tabHeads = $G( conId );
for ( var i = 0, j = 0; i < tabHeads.childNodes.length; i++ ) {
var tabObj = tabHeads.childNodes[i];
if ( tabObj.nodeType == 1 ) {
domUtils.on( tabObj, "click", (function ( index ) {
return function () {
switchTab( index );
};
})( j ) );
j++;
}
}
switchTab( 0 );
$G( "tabIconReview" ).style.display = "none";
}
function InsertSmiley( url, evt ) {
var obj = {
src:editor.options.emotionLocalization ? editor.options.UEDITOR_HOME_URL + "dialogs/emotion/" + url : url
};
obj._src = obj.src;
editor.execCommand( "insertimage", obj );
if ( !evt.ctrlKey ) {
dialog.popup.hide();
}
}
function switchTab( index ) {
autoHeight( index );
if ( emotion.tabExist[index] == 0 ) {
emotion.tabExist[index] = 1;
createTab( "tab" + index );
}
//获取呈现元素句柄数组
var tabHeads = $G( "tabHeads" ).getElementsByTagName( "span" ),
tabBodys = $G( "tabBodys" ).getElementsByTagName( "div" ),
i = 0, L = tabHeads.length;
//隐藏所有呈现元素
for ( ; i < L; i++ ) {
tabHeads[i].className = "";
tabBodys[i].style.display = "none";
}
//显示对应呈现元素
tabHeads[index].className = "focus";
tabBodys[index].style.display = "block";
}
function autoHeight( index ) {
var iframe = dialog.getDom( "iframe" ),
parent = iframe.parentNode.parentNode; | switch ( index ) {
case 0:
iframe.style.height = "380px";
parent.style.height = "392px";
break;
case 1:
iframe.style.height = "220px";
parent.style.height = "232px";
break;
case 2:
iframe.style.height = "260px";
parent.style.height = "272px";
break;
case 3:
iframe.style.height = "300px";
parent.style.height = "312px";
break;
case 4:
iframe.style.height = "140px";
parent.style.height = "152px";
break;
case 5:
iframe.style.height = "260px";
parent.style.height = "272px";
break;
case 6:
iframe.style.height = "230px";
parent.style.height = "242px";
break;
default:
}
}
function createTab( tabName ) {
var faceVersion = "?v=1.1", //版本号
tab = $G( tabName ), //获取将要生成的Div句柄
imagePath = emotion.SmileyPath + emotion.imageFolders[tabName], //获取显示表情和预览表情的路径
positionLine = 11 / 2, //中间数
iWidth = iHeight = 35, //图片长宽
iColWidth = 3, //表格剩余空间的显示比例
tableCss = emotion.imageCss[tabName],
cssOffset = emotion.imageCssOffset[tabName],
textHTML = ['<table class="smileytable">'],
i = 0, imgNum = emotion.SmileyBox[tabName].length, imgColNum = 11, faceImage,
sUrl, realUrl, posflag, offset, infor;
for ( ; i < imgNum; ) {
textHTML.push( "<tr>" );
for ( var j = 0; j < imgColNum; j++, i++ ) {
faceImage = emotion.SmileyBox[tabName][i];
if ( faceImage ) {
sUrl = imagePath + faceImage + faceVersion;
realUrl = imagePath + faceImage;
posflag = j < positionLine ? 0 : 1;
offset = cssOffset * i * (-1) - 1;
infor = emotion.SmileyInfor[tabName][i];
textHTML.push( '<td class="' + tableCss + '" border="1" width="' + iColWidth + '%" style="border-collapse:collapse;" align="center" bgcolor="transparent" onclick="InsertSmiley(\'' + realUrl.replace( /'/g, "\\'" ) + '\',event)" onmouseover="over(this,\'' + sUrl + "','" + posflag + '\')" onmouseout="out(this)">' );
textHTML.push( "<span>" );
textHTML.push( '<img style="background-position:left ' + offset + 'px;" title="' + infor + '" src="' + emotion.SmileyPath + (editor.options.emotionLocalization ? '0.gif" width="' : 'default/0.gif" width="') + iWidth + '" height="' + iHeight + '"></img>' );
textHTML.push( "</span>" );
} else {
textHTML.push( '<td width="' + iColWidth + '%" bgcolor="#FFFFFF">' );
}
textHTML.push( "</td>" );
}
textHTML.push( "</tr>" );
}
textHTML.push( "</table>" );
textHTML = textHTML.join( "" );
tab.innerHTML = textHTML;
}
function over( td, srcPath, posFlag ) {
td.style.backgroundColor = "#ACCD3C";
$G( "faceReview" ).style.backgroundImage = "url(" + srcPath + ")";
if ( posFlag == 1 ) $G( "tabIconReview" ).className = "show";
$G( "tabIconReview" ).style.display = "block";
}
function out( td ) {
td.style.backgroundColor = "transparent";
var tabIconRevew = $G( "tabIconReview" );
tabIconRevew.className = "";
tabIconRevew.style.display = "none";
}
function createTabList( tabNum ) {
var obj = {};
for ( var i = 0; i < tabNum; i++ ) {
obj["tab" + i] = [];
}
return obj;
}
function createArr( tabNum ) {
var arr = [];
for ( var i = 0; i < tabNum; i++ ) {
arr[i] = 0;
}
return arr;
} | random_line_split | |
emotion.js | window.onload = function () {
editor.setOpt({
emotionLocalization:false
});
emotion.SmileyPath = editor.options.emotionLocalization === true ? "images/" : "http://img.baidu.com/hi/";
emotion.SmileyBox = createTabList( emotion.tabNum );
emotion.tabExist = createArr( emotion.tabNum );
initImgName();
initEvtHandler( "tabHeads" );
};
function initImgName() {
for ( var pro in emotion.SmilmgName ) {
var tempName = emotion.SmilmgName[pro],
tempBox = emotion.SmileyBox[pro],
tempStr = "";
if ( tempBox.length ) return;
for ( var i = 1; i <= tempName[1]; i++ ) {
tempStr = tempName[0];
if ( i < 10 ) tempStr = tempStr + "0";
tempStr = tempStr + i + ".gif";
tempBox.push( tempStr );
}
}
}
function initEvtHandler( conId ) {
var tabHeads = $G( conId );
for ( var i = 0, j = 0; i < tabHeads.childNodes.length; i++ ) {
var tabObj = tabHeads.childNodes[i];
if ( tabObj.nodeType == 1 ) {
domUtils.on( tabObj, "click", (function ( index ) {
return function () {
switchTab( index );
};
})( j ) );
j++;
}
}
switchTab( 0 );
$G( "tabIconReview" ).style.display = "none";
}
function InsertSmiley( url, evt ) {
var obj = {
src:editor.options.emotionLocalization ? editor.options.UEDITOR_HOME_URL + "dialogs/emotion/" + url : url
};
obj._src = obj.src;
editor.execCommand( "insertimage", obj );
if ( !evt.ctrlKey ) {
dialog.popup.hide();
}
}
function switchTab( index ) {
autoHeight( index );
if ( emotion.tabExist[index] == 0 ) {
emotion.tabExist[index] = 1;
createTab( "tab" + index );
}
//获取呈现元素句柄数组
var tabHeads = $G( "tabHeads" ).getElementsByTagName( "span" ),
tabBodys = $G( "tabBodys" ).getElementsByTagName( "div" ),
i = 0, L = tabHeads.length;
//隐藏所有呈现元素
for ( ; i < L; i++ ) {
tabHeads[i].className = "";
tabBodys[i].style.display = "none";
}
//显示对应呈现元素
tabHeads[index].className = "focus";
tabBodys[index].style.display = "block";
}
function autoHeight( index ) {
var iframe = dialog.getDom( "iframe" ),
parent = iframe.parentNode.parentNode;
switch ( index ) {
case 0:
iframe.style.height = "380px";
parent.style.height = "392px";
break;
case 1:
iframe.style.height = "220px";
parent.style.height = "232px";
break;
case 2:
iframe.style.height = "260px";
parent.style.height = "272px";
break;
case 3:
iframe.style.height = "300px";
parent.style.height = "312px";
break;
case 4:
iframe.style.height = "140px";
parent.style.height = "152px";
break;
case 5:
iframe.style.height = "260px";
parent.style.height = "272px";
break;
case 6:
iframe.style.height = "230px";
parent.style.height = "242px";
break;
default:
}
}
function createTab( tabName ) {
var faceVersion = "?v=1.1", //版本号
tab = $G( tabName ), //获取将要生成的Div句柄
imagePath = emotion.SmileyPath + emotion.imageFolders[tabName], //获取显示表情和预览表情的路径
positionLine = 11 / 2, //中间数
iWidth = iHeight = 35, //图片长宽
iColWidth = 3, //表格剩余空间的显示比例
tableCss = emotion.imageCss[tabName],
cssOffset = emotion.imageCssOffset[tabName],
textHTML = ['<table class="smileytable">'],
i = 0, imgNum = emotion.SmileyBox[tabName].length, imgColNum = 11, faceImage,
sUrl, realUrl, posflag, offset, infor;
for ( ; i < imgNum; ) {
textHTML.push( "<tr>" );
for ( var j = 0; j < imgColNum; j++, i++ ) {
faceImage = emotion.SmileyBox[tabName][i];
if ( faceImage ) {
sUrl = imagePath + faceImage + faceVersion;
realUrl = imagePath + faceImage;
posflag = j < | td>" );
}
textHTML.push( "</tr>" );
}
textHTML.push( "</table>" );
textHTML = textHTML.join( "" );
tab.innerHTML = textHTML;
}
function over( td, srcPath, posFlag ) {
td.style.backgroundColor = "#ACCD3C";
$G( "faceReview" ).style.backgroundImage = "url(" + srcPath + ")";
if ( posFlag == 1 ) $G( "tabIconReview" ).className = "show";
$G( "tabIconReview" ).style.display = "block";
}
function out( td ) {
td.style.backgroundColor = "transparent";
var tabIconRevew = $G( "tabIconReview" );
tabIconRevew.className = "";
tabIconRevew.style.display = "none";
}
function createTabList( tabNum ) {
var obj = {};
for ( var i = 0; i < tabNum; i++ ) {
obj["tab" + i] = [];
}
return obj;
}
function createArr( tabNum ) {
var arr = [];
for ( var i = 0; i < tabNum; i++ ) {
arr[i] = 0;
}
return arr;
}
| positionLine ? 0 : 1;
offset = cssOffset * i * (-1) - 1;
infor = emotion.SmileyInfor[tabName][i];
textHTML.push( '<td class="' + tableCss + '" border="1" width="' + iColWidth + '%" style="border-collapse:collapse;" align="center" bgcolor="transparent" onclick="InsertSmiley(\'' + realUrl.replace( /'/g, "\\'" ) + '\',event)" onmouseover="over(this,\'' + sUrl + "','" + posflag + '\')" onmouseout="out(this)">' );
textHTML.push( "<span>" );
textHTML.push( '<img style="background-position:left ' + offset + 'px;" title="' + infor + '" src="' + emotion.SmileyPath + (editor.options.emotionLocalization ? '0.gif" width="' : 'default/0.gif" width="') + iWidth + '" height="' + iHeight + '"></img>' );
textHTML.push( "</span>" );
} else {
textHTML.push( '<td width="' + iColWidth + '%" bgcolor="#FFFFFF">' );
}
textHTML.push( "</ | conditional_block |
server.js | 'use strict';
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
function | (baseDir, browser) {
// var routes = null;
// if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
// routes = {
// '/bower_components': 'bower_components'
// };
// }
/*
* You can add a proxy to your backend by uncommenting the line below.
* You just have to configure a context which will we redirected and the target url.
* Example: $http.get('/users') requests will be automatically proxified.
*
* For more details and option, https://github.com/chimurai/http-proxy-middleware/blob/v0.0.5/README.md
*/
// server.middleware = proxyMiddleware('/users', {target: 'http://jsonplaceholder.typicode.com', proxyHost: 'jsonplaceholder.typicode.com'});
browserSync.instance = browserSync.init({
startPath: '/',
server: {
baseDir: baseDir,
routes: null
},
browser: browser || 'default'
});
}
browserSync.use(browserSyncSpa({
selector: '[ng-app]'// Only needed for angular apps
}));
gulp.task('serve', ['watch'], function() {
browserSyncInit(conf.dist);
});
gulp.task('serve:dist', ['inject'], function() {
browserSyncInit(conf.dist);
}); | browserSyncInit | identifier_name |
server.js | 'use strict';
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
function browserSyncInit(baseDir, browser) |
browserSync.use(browserSyncSpa({
selector: '[ng-app]'// Only needed for angular apps
}));
gulp.task('serve', ['watch'], function() {
browserSyncInit(conf.dist);
});
gulp.task('serve:dist', ['inject'], function() {
browserSyncInit(conf.dist);
}); | {
// var routes = null;
// if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
// routes = {
// '/bower_components': 'bower_components'
// };
// }
/*
* You can add a proxy to your backend by uncommenting the line below.
* You just have to configure a context which will we redirected and the target url.
* Example: $http.get('/users') requests will be automatically proxified.
*
* For more details and option, https://github.com/chimurai/http-proxy-middleware/blob/v0.0.5/README.md
*/
// server.middleware = proxyMiddleware('/users', {target: 'http://jsonplaceholder.typicode.com', proxyHost: 'jsonplaceholder.typicode.com'});
browserSync.instance = browserSync.init({
startPath: '/',
server: {
baseDir: baseDir,
routes: null
},
browser: browser || 'default'
});
} | identifier_body |
server.js | 'use strict';
var gulp = require('gulp');
var conf = require('./conf');
var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
function browserSyncInit(baseDir, browser) {
// var routes = null;
// if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
// routes = {
// '/bower_components': 'bower_components'
// };
// }
/*
* You can add a proxy to your backend by uncommenting the line below. | * Example: $http.get('/users') requests will be automatically proxified.
*
* For more details and option, https://github.com/chimurai/http-proxy-middleware/blob/v0.0.5/README.md
*/
// server.middleware = proxyMiddleware('/users', {target: 'http://jsonplaceholder.typicode.com', proxyHost: 'jsonplaceholder.typicode.com'});
browserSync.instance = browserSync.init({
startPath: '/',
server: {
baseDir: baseDir,
routes: null
},
browser: browser || 'default'
});
}
browserSync.use(browserSyncSpa({
selector: '[ng-app]'// Only needed for angular apps
}));
gulp.task('serve', ['watch'], function() {
browserSyncInit(conf.dist);
});
gulp.task('serve:dist', ['inject'], function() {
browserSyncInit(conf.dist);
}); | * You just have to configure a context which will we redirected and the target url. | random_line_split |
passenger_wsgi.py | import os
import tempfile
import re
import bottle
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont
formats = {
'png': {
'format': 'PNG',
'mimetype': 'image/png'
},
'jpg': {
'format': 'JPEG',
'mimetype': 'image/jpeg'
},
'gif': {
'format': 'GIF',
'mimetype': 'image/gif'
},
}
guides = {
'qqvga': [160, 120],
'hqvga': [240, 160],
'qvga': [320, 240],
'wqvga': [400, 240],
'hvga': [480, 320],
'vga': [640, 480],
'wvga': [768, 480],
'fwvga': [854, 480],
'svga': [800, 600],
'dvga': [960, 640],
'wsvga': [1024, 600],
'xga': [1024, 768],
'wxga': [1366, 768],
'fwxga': [1366, 768],
'xga+': [1152, 864],
'wxga+': [1440, 900],
'sxga': [1280, 1024],
'sxga+': [1400, 1050],
'wsxga+': [1680, 1050],
'uxga': [1600, 1200],
'wuxga': [1920, 1200],
'1080': [1920, 1080],
'720': [1280, 720],
}
@bottle.route('/')
def | ():
return "it works!"
@bottle.route('/<width>/<height>')
@bottle.route('/<width>/<height>/')
def image(width=320, height=240):
width=int(width)
height=int(height)
format = bottle.request.query.get('f', 'png').lower()
bg_color = bottle.request.query.get('bgcolor', 'aaaaaa').lower()
fg_color = bottle.request.query.get('fgcolor', 'ffffff').lower()
text = bottle.request.query.get('t', str(width) + 'x' + str(height)).lower()
text_size = int(bottle.request.query.get('ts', 60))
guide_list = [[int(y) for y in x.lower().split(',')] if ',' in x else x.lower() for x in bottle.request.query.getall('g')]
guide_color = bottle.request.query.get('gcolor', fg_color).lower()
try:
if int(bg_color, 16):
bg_color = '#' + bg_color
except:
pass
try:
if int(fg_color, 16):
fg_color = '#' + fg_color
except:
pass
try:
if int(guide_color, 16):
guide_color = '#' + guide_color
except:
pass
if not format in formats:
return bottle.HTTPError(code=404, output="That format is not supported")
image_file = tempfile.NamedTemporaryFile(suffix='.' + format, dir='/home/spencersr/holder.graphics/tmp/images/', delete=True)
image = PIL.Image.new('RGB', size=(width, height), color=bg_color)
draw = PIL.ImageDraw.Draw(image)
print(text_size)
font = PIL.ImageFont.truetype("/usr/share/fonts/truetype/ttf-bitstream-vera/VeraBd.ttf", text_size)
guide_font = PIL.ImageFont.truetype("/usr/share/fonts/truetype/ttf-bitstream-vera/VeraBd.ttf", int(text_size/4.0))
for guide in guide_list:
guide_width, guide_height = guides.get(str(guide), guide)
guide_offset_width = (width - guide_width) / 2.0
guide_offset_height = (height - guide_height) / 2.0
draw.rectangle(((guide_offset_width, guide_offset_height), (guide_offset_width + guide_width, guide_offset_height + guide_height)), fill=None, outline=guide_color)
draw.text((guide_offset_width + 4, guide_offset_height + 4), str(guide_width) + 'x' + str(guide_height), fill=guide_color, font=guide_font)
# Draw Center Text
text_width, text_height = font.getsize(text)
draw.text(((width - text_width) / 2.0, (height - text_height) / 2.0), text, fill=fg_color, font=font)
image.save(image_file.file, formats[format]['format'])
bottle.response.image_file = image_file
return bottle.static_file(os.path.basename(image_file.name), root='/home/spencersr/holder.graphics/tmp/images/', mimetype=formats[format]['mimetype'])
def application(environ, start_response):
app = bottle.default_app()
return app.wsgi(environ, start_response)
if __name__ == "__main__":
bottle.debug(True)
app = bottle.default_app()
bottle.run(app, host='0.0.0.0', port='8685', reloader=True)
| index | identifier_name |
passenger_wsgi.py | import os
import tempfile
import re
import bottle
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont
formats = {
'png': {
'format': 'PNG',
'mimetype': 'image/png'
},
'jpg': {
'format': 'JPEG',
'mimetype': 'image/jpeg'
},
'gif': {
'format': 'GIF',
'mimetype': 'image/gif'
},
}
guides = {
'qqvga': [160, 120],
'hqvga': [240, 160],
'qvga': [320, 240],
'wqvga': [400, 240],
'hvga': [480, 320],
'vga': [640, 480],
'wvga': [768, 480],
'fwvga': [854, 480],
'svga': [800, 600],
'dvga': [960, 640], | 'wxga+': [1440, 900],
'sxga': [1280, 1024],
'sxga+': [1400, 1050],
'wsxga+': [1680, 1050],
'uxga': [1600, 1200],
'wuxga': [1920, 1200],
'1080': [1920, 1080],
'720': [1280, 720],
}
@bottle.route('/')
def index():
return "it works!"
@bottle.route('/<width>/<height>')
@bottle.route('/<width>/<height>/')
def image(width=320, height=240):
width=int(width)
height=int(height)
format = bottle.request.query.get('f', 'png').lower()
bg_color = bottle.request.query.get('bgcolor', 'aaaaaa').lower()
fg_color = bottle.request.query.get('fgcolor', 'ffffff').lower()
text = bottle.request.query.get('t', str(width) + 'x' + str(height)).lower()
text_size = int(bottle.request.query.get('ts', 60))
guide_list = [[int(y) for y in x.lower().split(',')] if ',' in x else x.lower() for x in bottle.request.query.getall('g')]
guide_color = bottle.request.query.get('gcolor', fg_color).lower()
try:
if int(bg_color, 16):
bg_color = '#' + bg_color
except:
pass
try:
if int(fg_color, 16):
fg_color = '#' + fg_color
except:
pass
try:
if int(guide_color, 16):
guide_color = '#' + guide_color
except:
pass
if not format in formats:
return bottle.HTTPError(code=404, output="That format is not supported")
image_file = tempfile.NamedTemporaryFile(suffix='.' + format, dir='/home/spencersr/holder.graphics/tmp/images/', delete=True)
image = PIL.Image.new('RGB', size=(width, height), color=bg_color)
draw = PIL.ImageDraw.Draw(image)
print(text_size)
font = PIL.ImageFont.truetype("/usr/share/fonts/truetype/ttf-bitstream-vera/VeraBd.ttf", text_size)
guide_font = PIL.ImageFont.truetype("/usr/share/fonts/truetype/ttf-bitstream-vera/VeraBd.ttf", int(text_size/4.0))
for guide in guide_list:
guide_width, guide_height = guides.get(str(guide), guide)
guide_offset_width = (width - guide_width) / 2.0
guide_offset_height = (height - guide_height) / 2.0
draw.rectangle(((guide_offset_width, guide_offset_height), (guide_offset_width + guide_width, guide_offset_height + guide_height)), fill=None, outline=guide_color)
draw.text((guide_offset_width + 4, guide_offset_height + 4), str(guide_width) + 'x' + str(guide_height), fill=guide_color, font=guide_font)
# Draw Center Text
text_width, text_height = font.getsize(text)
draw.text(((width - text_width) / 2.0, (height - text_height) / 2.0), text, fill=fg_color, font=font)
image.save(image_file.file, formats[format]['format'])
bottle.response.image_file = image_file
return bottle.static_file(os.path.basename(image_file.name), root='/home/spencersr/holder.graphics/tmp/images/', mimetype=formats[format]['mimetype'])
def application(environ, start_response):
app = bottle.default_app()
return app.wsgi(environ, start_response)
if __name__ == "__main__":
bottle.debug(True)
app = bottle.default_app()
bottle.run(app, host='0.0.0.0', port='8685', reloader=True) | 'wsvga': [1024, 600],
'xga': [1024, 768],
'wxga': [1366, 768],
'fwxga': [1366, 768],
'xga+': [1152, 864], | random_line_split |
passenger_wsgi.py | import os
import tempfile
import re
import bottle
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont
formats = {
'png': {
'format': 'PNG',
'mimetype': 'image/png'
},
'jpg': {
'format': 'JPEG',
'mimetype': 'image/jpeg'
},
'gif': {
'format': 'GIF',
'mimetype': 'image/gif'
},
}
guides = {
'qqvga': [160, 120],
'hqvga': [240, 160],
'qvga': [320, 240],
'wqvga': [400, 240],
'hvga': [480, 320],
'vga': [640, 480],
'wvga': [768, 480],
'fwvga': [854, 480],
'svga': [800, 600],
'dvga': [960, 640],
'wsvga': [1024, 600],
'xga': [1024, 768],
'wxga': [1366, 768],
'fwxga': [1366, 768],
'xga+': [1152, 864],
'wxga+': [1440, 900],
'sxga': [1280, 1024],
'sxga+': [1400, 1050],
'wsxga+': [1680, 1050],
'uxga': [1600, 1200],
'wuxga': [1920, 1200],
'1080': [1920, 1080],
'720': [1280, 720],
}
@bottle.route('/')
def index():
return "it works!"
@bottle.route('/<width>/<height>')
@bottle.route('/<width>/<height>/')
def image(width=320, height=240):
|
def application(environ, start_response):
app = bottle.default_app()
return app.wsgi(environ, start_response)
if __name__ == "__main__":
bottle.debug(True)
app = bottle.default_app()
bottle.run(app, host='0.0.0.0', port='8685', reloader=True)
| width=int(width)
height=int(height)
format = bottle.request.query.get('f', 'png').lower()
bg_color = bottle.request.query.get('bgcolor', 'aaaaaa').lower()
fg_color = bottle.request.query.get('fgcolor', 'ffffff').lower()
text = bottle.request.query.get('t', str(width) + 'x' + str(height)).lower()
text_size = int(bottle.request.query.get('ts', 60))
guide_list = [[int(y) for y in x.lower().split(',')] if ',' in x else x.lower() for x in bottle.request.query.getall('g')]
guide_color = bottle.request.query.get('gcolor', fg_color).lower()
try:
if int(bg_color, 16):
bg_color = '#' + bg_color
except:
pass
try:
if int(fg_color, 16):
fg_color = '#' + fg_color
except:
pass
try:
if int(guide_color, 16):
guide_color = '#' + guide_color
except:
pass
if not format in formats:
return bottle.HTTPError(code=404, output="That format is not supported")
image_file = tempfile.NamedTemporaryFile(suffix='.' + format, dir='/home/spencersr/holder.graphics/tmp/images/', delete=True)
image = PIL.Image.new('RGB', size=(width, height), color=bg_color)
draw = PIL.ImageDraw.Draw(image)
print(text_size)
font = PIL.ImageFont.truetype("/usr/share/fonts/truetype/ttf-bitstream-vera/VeraBd.ttf", text_size)
guide_font = PIL.ImageFont.truetype("/usr/share/fonts/truetype/ttf-bitstream-vera/VeraBd.ttf", int(text_size/4.0))
for guide in guide_list:
guide_width, guide_height = guides.get(str(guide), guide)
guide_offset_width = (width - guide_width) / 2.0
guide_offset_height = (height - guide_height) / 2.0
draw.rectangle(((guide_offset_width, guide_offset_height), (guide_offset_width + guide_width, guide_offset_height + guide_height)), fill=None, outline=guide_color)
draw.text((guide_offset_width + 4, guide_offset_height + 4), str(guide_width) + 'x' + str(guide_height), fill=guide_color, font=guide_font)
# Draw Center Text
text_width, text_height = font.getsize(text)
draw.text(((width - text_width) / 2.0, (height - text_height) / 2.0), text, fill=fg_color, font=font)
image.save(image_file.file, formats[format]['format'])
bottle.response.image_file = image_file
return bottle.static_file(os.path.basename(image_file.name), root='/home/spencersr/holder.graphics/tmp/images/', mimetype=formats[format]['mimetype']) | identifier_body |
passenger_wsgi.py | import os
import tempfile
import re
import bottle
import PIL.Image
import PIL.ImageDraw
import PIL.ImageFont
formats = {
'png': {
'format': 'PNG',
'mimetype': 'image/png'
},
'jpg': {
'format': 'JPEG',
'mimetype': 'image/jpeg'
},
'gif': {
'format': 'GIF',
'mimetype': 'image/gif'
},
}
guides = {
'qqvga': [160, 120],
'hqvga': [240, 160],
'qvga': [320, 240],
'wqvga': [400, 240],
'hvga': [480, 320],
'vga': [640, 480],
'wvga': [768, 480],
'fwvga': [854, 480],
'svga': [800, 600],
'dvga': [960, 640],
'wsvga': [1024, 600],
'xga': [1024, 768],
'wxga': [1366, 768],
'fwxga': [1366, 768],
'xga+': [1152, 864],
'wxga+': [1440, 900],
'sxga': [1280, 1024],
'sxga+': [1400, 1050],
'wsxga+': [1680, 1050],
'uxga': [1600, 1200],
'wuxga': [1920, 1200],
'1080': [1920, 1080],
'720': [1280, 720],
}
@bottle.route('/')
def index():
return "it works!"
@bottle.route('/<width>/<height>')
@bottle.route('/<width>/<height>/')
def image(width=320, height=240):
width=int(width)
height=int(height)
format = bottle.request.query.get('f', 'png').lower()
bg_color = bottle.request.query.get('bgcolor', 'aaaaaa').lower()
fg_color = bottle.request.query.get('fgcolor', 'ffffff').lower()
text = bottle.request.query.get('t', str(width) + 'x' + str(height)).lower()
text_size = int(bottle.request.query.get('ts', 60))
guide_list = [[int(y) for y in x.lower().split(',')] if ',' in x else x.lower() for x in bottle.request.query.getall('g')]
guide_color = bottle.request.query.get('gcolor', fg_color).lower()
try:
if int(bg_color, 16):
bg_color = '#' + bg_color
except:
pass
try:
if int(fg_color, 16):
fg_color = '#' + fg_color
except:
pass
try:
if int(guide_color, 16):
guide_color = '#' + guide_color
except:
pass
if not format in formats:
return bottle.HTTPError(code=404, output="That format is not supported")
image_file = tempfile.NamedTemporaryFile(suffix='.' + format, dir='/home/spencersr/holder.graphics/tmp/images/', delete=True)
image = PIL.Image.new('RGB', size=(width, height), color=bg_color)
draw = PIL.ImageDraw.Draw(image)
print(text_size)
font = PIL.ImageFont.truetype("/usr/share/fonts/truetype/ttf-bitstream-vera/VeraBd.ttf", text_size)
guide_font = PIL.ImageFont.truetype("/usr/share/fonts/truetype/ttf-bitstream-vera/VeraBd.ttf", int(text_size/4.0))
for guide in guide_list:
guide_width, guide_height = guides.get(str(guide), guide)
guide_offset_width = (width - guide_width) / 2.0
guide_offset_height = (height - guide_height) / 2.0
draw.rectangle(((guide_offset_width, guide_offset_height), (guide_offset_width + guide_width, guide_offset_height + guide_height)), fill=None, outline=guide_color)
draw.text((guide_offset_width + 4, guide_offset_height + 4), str(guide_width) + 'x' + str(guide_height), fill=guide_color, font=guide_font)
# Draw Center Text
text_width, text_height = font.getsize(text)
draw.text(((width - text_width) / 2.0, (height - text_height) / 2.0), text, fill=fg_color, font=font)
image.save(image_file.file, formats[format]['format'])
bottle.response.image_file = image_file
return bottle.static_file(os.path.basename(image_file.name), root='/home/spencersr/holder.graphics/tmp/images/', mimetype=formats[format]['mimetype'])
def application(environ, start_response):
app = bottle.default_app()
return app.wsgi(environ, start_response)
if __name__ == "__main__":
| bottle.debug(True)
app = bottle.default_app()
bottle.run(app, host='0.0.0.0', port='8685', reloader=True) | conditional_block | |
picget.py | # This is a program for IP limit using picture recognition.
# URL: http://bbs.csdn.net/human_validations/new
# Input: human validations page
# Get the jpeg from the url.
# use picture recognition to get the string from the picture.
# Authentication pass!
#
# this is try to use selenuim to login
import re,os,sys
import time
import urllib2
import cookielib
import urllib
from cookielib import CookieJar
import pytesseract
from selenium import webdriver
from PIL import Image,ImageFilter,ImageEnhance
from selenium.webdriver.common import action_chains
from selenium.webdriver.common.keys import Keys
class PicGet:
def image_to_text(self, img):
text = pytesseract.image_to_string(img)
text = re.sub('[\W]', '', text)
return text
def imageToString(self,picname):
image = Image.open(picname)
ValidCode = self.image_to_text(image)
image.save('captcha.png')
return ValidCode
def validlogin(self,driver,cookie,validcode):
# use the validcode to authentication
PostUrl = "http://bbs.csdn.net/human_validations"
elem = driver.find_element_by_id("captcha")
elem.send_keys(validcode)
elem.send_keys(Keys.TAB)
time.sleep(3)
driver.find_element_by_xpath('//button[@type="submit"]').send_keys(Keys.ENTER)
#submit_button.send_keys(Keys.ENTER)
print "test"
cur_url = driver.current_url
# print (cur_url)
if cur_url == PostUrl:
return True
else:
return False
def validImageGet(self):
AuthUrl = "http://bbs.csdn.net/human_validations/new"
picname = 'captcha.png'
sel = webdriver.Chrome()
sel.get(AuthUrl)
cookie = sel.get_cookies()
auth_token = sel.find_element_by_xpath('//input[@name="authenticity_token"]')
captcha_key = sel.find_element_by_xpath('//input[@id="captcha_key"]')
# submit_button = sel.find_element_by_xpath('//button[@type="submit"]')
# submit_button.submit()
time.sleep(0.3)
picItem = sel.find_element_by_xpath('//img[@alt="captcha"]')
# submit_button = sel.find_element_by_xpath('//button[@type="submit"]')
sel.save_screenshot(picname)
left = int(picItem.location['x'])
top = int(picItem.location['y'])
right = int(picItem.location['x'] + picItem.size['width'])
bottom = int(picItem.location['y'] + picItem.size['height'])
im = Image.open(picname)
# print (left,top,right,bottom)
im = im.crop((left, top, right, bottom))
im.save(picname)
# validcode picture recognize
time.sleep(0.5)
validcode = self.imageToString(picname)
print (validcode)
validcode = "RCNCUB"
#validcode = input("please input:")
if re.match('[A-Z]{6}',validcode):
if self.validlogin(sel,cookie,validcode):
print ('Auth Success!')
else:
print ('Auth Fail!')
#picItem.send_keys(Keys.TAB)
#submit_button.send_keys(Keys.ENTER)
#submit_button.click()
# try:
# submit_button.click()
# except Exception,e:
# print (Exception,":",e)
# validcode = input("please input:")
# if True: # if (len(validcode) == 6) & validcode.isalnum():
# if self.validpost(cookie,auth_token,validcode,captcha_key):# if self.validlogin(sel,cookie,validcode):
# print ('Authentication Pass!')
# break
# else:
# submit_button.click()
time.sleep(5)
sel.quit()
if __name__ == '__main__':
| ValidTest = PicGet()
ValidTest.validImageGet() | conditional_block | |
picget.py | # This is a program for IP limit using picture recognition.
# URL: http://bbs.csdn.net/human_validations/new
# Input: human validations page
# Get the jpeg from the url.
# use picture recognition to get the string from the picture.
# Authentication pass!
#
# this is try to use selenuim to login
import re,os,sys
import time
import urllib2
import cookielib
import urllib
from cookielib import CookieJar
import pytesseract
from selenium import webdriver
from PIL import Image,ImageFilter,ImageEnhance
from selenium.webdriver.common import action_chains
from selenium.webdriver.common.keys import Keys
class PicGet:
def image_to_text(self, img):
text = pytesseract.image_to_string(img)
text = re.sub('[\W]', '', text)
return text
def imageToString(self,picname):
image = Image.open(picname)
ValidCode = self.image_to_text(image)
image.save('captcha.png')
return ValidCode
def | (self,driver,cookie,validcode):
# use the validcode to authentication
PostUrl = "http://bbs.csdn.net/human_validations"
elem = driver.find_element_by_id("captcha")
elem.send_keys(validcode)
elem.send_keys(Keys.TAB)
time.sleep(3)
driver.find_element_by_xpath('//button[@type="submit"]').send_keys(Keys.ENTER)
#submit_button.send_keys(Keys.ENTER)
print "test"
cur_url = driver.current_url
# print (cur_url)
if cur_url == PostUrl:
return True
else:
return False
def validImageGet(self):
AuthUrl = "http://bbs.csdn.net/human_validations/new"
picname = 'captcha.png'
sel = webdriver.Chrome()
sel.get(AuthUrl)
cookie = sel.get_cookies()
auth_token = sel.find_element_by_xpath('//input[@name="authenticity_token"]')
captcha_key = sel.find_element_by_xpath('//input[@id="captcha_key"]')
# submit_button = sel.find_element_by_xpath('//button[@type="submit"]')
# submit_button.submit()
time.sleep(0.3)
picItem = sel.find_element_by_xpath('//img[@alt="captcha"]')
# submit_button = sel.find_element_by_xpath('//button[@type="submit"]')
sel.save_screenshot(picname)
left = int(picItem.location['x'])
top = int(picItem.location['y'])
right = int(picItem.location['x'] + picItem.size['width'])
bottom = int(picItem.location['y'] + picItem.size['height'])
im = Image.open(picname)
# print (left,top,right,bottom)
im = im.crop((left, top, right, bottom))
im.save(picname)
# validcode picture recognize
time.sleep(0.5)
validcode = self.imageToString(picname)
print (validcode)
validcode = "RCNCUB"
#validcode = input("please input:")
if re.match('[A-Z]{6}',validcode):
if self.validlogin(sel,cookie,validcode):
print ('Auth Success!')
else:
print ('Auth Fail!')
#picItem.send_keys(Keys.TAB)
#submit_button.send_keys(Keys.ENTER)
#submit_button.click()
# try:
# submit_button.click()
# except Exception,e:
# print (Exception,":",e)
# validcode = input("please input:")
# if True: # if (len(validcode) == 6) & validcode.isalnum():
# if self.validpost(cookie,auth_token,validcode,captcha_key):# if self.validlogin(sel,cookie,validcode):
# print ('Authentication Pass!')
# break
# else:
# submit_button.click()
time.sleep(5)
sel.quit()
if __name__ == '__main__':
ValidTest = PicGet()
ValidTest.validImageGet() | validlogin | identifier_name |
picget.py | # This is a program for IP limit using picture recognition.
# URL: http://bbs.csdn.net/human_validations/new
# Input: human validations page
# Get the jpeg from the url.
# use picture recognition to get the string from the picture.
# Authentication pass!
#
# this is try to use selenuim to login
import re,os,sys
import time
import urllib2
import cookielib
import urllib
from cookielib import CookieJar
import pytesseract
from selenium import webdriver
from PIL import Image,ImageFilter,ImageEnhance
from selenium.webdriver.common import action_chains
from selenium.webdriver.common.keys import Keys
class PicGet:
def image_to_text(self, img):
text = pytesseract.image_to_string(img)
text = re.sub('[\W]', '', text)
return text
def imageToString(self,picname):
image = Image.open(picname) | ValidCode = self.image_to_text(image)
image.save('captcha.png')
return ValidCode
def validlogin(self,driver,cookie,validcode):
# use the validcode to authentication
PostUrl = "http://bbs.csdn.net/human_validations"
elem = driver.find_element_by_id("captcha")
elem.send_keys(validcode)
elem.send_keys(Keys.TAB)
time.sleep(3)
driver.find_element_by_xpath('//button[@type="submit"]').send_keys(Keys.ENTER)
#submit_button.send_keys(Keys.ENTER)
print "test"
cur_url = driver.current_url
# print (cur_url)
if cur_url == PostUrl:
return True
else:
return False
def validImageGet(self):
AuthUrl = "http://bbs.csdn.net/human_validations/new"
picname = 'captcha.png'
sel = webdriver.Chrome()
sel.get(AuthUrl)
cookie = sel.get_cookies()
auth_token = sel.find_element_by_xpath('//input[@name="authenticity_token"]')
captcha_key = sel.find_element_by_xpath('//input[@id="captcha_key"]')
# submit_button = sel.find_element_by_xpath('//button[@type="submit"]')
# submit_button.submit()
time.sleep(0.3)
picItem = sel.find_element_by_xpath('//img[@alt="captcha"]')
# submit_button = sel.find_element_by_xpath('//button[@type="submit"]')
sel.save_screenshot(picname)
left = int(picItem.location['x'])
top = int(picItem.location['y'])
right = int(picItem.location['x'] + picItem.size['width'])
bottom = int(picItem.location['y'] + picItem.size['height'])
im = Image.open(picname)
# print (left,top,right,bottom)
im = im.crop((left, top, right, bottom))
im.save(picname)
# validcode picture recognize
time.sleep(0.5)
validcode = self.imageToString(picname)
print (validcode)
validcode = "RCNCUB"
#validcode = input("please input:")
if re.match('[A-Z]{6}',validcode):
if self.validlogin(sel,cookie,validcode):
print ('Auth Success!')
else:
print ('Auth Fail!')
#picItem.send_keys(Keys.TAB)
#submit_button.send_keys(Keys.ENTER)
#submit_button.click()
# try:
# submit_button.click()
# except Exception,e:
# print (Exception,":",e)
# validcode = input("please input:")
# if True: # if (len(validcode) == 6) & validcode.isalnum():
# if self.validpost(cookie,auth_token,validcode,captcha_key):# if self.validlogin(sel,cookie,validcode):
# print ('Authentication Pass!')
# break
# else:
# submit_button.click()
time.sleep(5)
sel.quit()
if __name__ == '__main__':
ValidTest = PicGet()
ValidTest.validImageGet() | random_line_split | |
picget.py | # This is a program for IP limit using picture recognition.
# URL: http://bbs.csdn.net/human_validations/new
# Input: human validations page
# Get the jpeg from the url.
# use picture recognition to get the string from the picture.
# Authentication pass!
#
# this is try to use selenuim to login
import re,os,sys
import time
import urllib2
import cookielib
import urllib
from cookielib import CookieJar
import pytesseract
from selenium import webdriver
from PIL import Image,ImageFilter,ImageEnhance
from selenium.webdriver.common import action_chains
from selenium.webdriver.common.keys import Keys
class PicGet:
def image_to_text(self, img):
text = pytesseract.image_to_string(img)
text = re.sub('[\W]', '', text)
return text
def imageToString(self,picname):
image = Image.open(picname)
ValidCode = self.image_to_text(image)
image.save('captcha.png')
return ValidCode
def validlogin(self,driver,cookie,validcode):
# use the validcode to authentication
PostUrl = "http://bbs.csdn.net/human_validations"
elem = driver.find_element_by_id("captcha")
elem.send_keys(validcode)
elem.send_keys(Keys.TAB)
time.sleep(3)
driver.find_element_by_xpath('//button[@type="submit"]').send_keys(Keys.ENTER)
#submit_button.send_keys(Keys.ENTER)
print "test"
cur_url = driver.current_url
# print (cur_url)
if cur_url == PostUrl:
return True
else:
return False
def validImageGet(self):
|
if __name__ == '__main__':
ValidTest = PicGet()
ValidTest.validImageGet() | AuthUrl = "http://bbs.csdn.net/human_validations/new"
picname = 'captcha.png'
sel = webdriver.Chrome()
sel.get(AuthUrl)
cookie = sel.get_cookies()
auth_token = sel.find_element_by_xpath('//input[@name="authenticity_token"]')
captcha_key = sel.find_element_by_xpath('//input[@id="captcha_key"]')
# submit_button = sel.find_element_by_xpath('//button[@type="submit"]')
# submit_button.submit()
time.sleep(0.3)
picItem = sel.find_element_by_xpath('//img[@alt="captcha"]')
# submit_button = sel.find_element_by_xpath('//button[@type="submit"]')
sel.save_screenshot(picname)
left = int(picItem.location['x'])
top = int(picItem.location['y'])
right = int(picItem.location['x'] + picItem.size['width'])
bottom = int(picItem.location['y'] + picItem.size['height'])
im = Image.open(picname)
# print (left,top,right,bottom)
im = im.crop((left, top, right, bottom))
im.save(picname)
# validcode picture recognize
time.sleep(0.5)
validcode = self.imageToString(picname)
print (validcode)
validcode = "RCNCUB"
#validcode = input("please input:")
if re.match('[A-Z]{6}',validcode):
if self.validlogin(sel,cookie,validcode):
print ('Auth Success!')
else:
print ('Auth Fail!')
#picItem.send_keys(Keys.TAB)
#submit_button.send_keys(Keys.ENTER)
#submit_button.click()
# try:
# submit_button.click()
# except Exception,e:
# print (Exception,":",e)
# validcode = input("please input:")
# if True: # if (len(validcode) == 6) & validcode.isalnum():
# if self.validpost(cookie,auth_token,validcode,captcha_key):# if self.validlogin(sel,cookie,validcode):
# print ('Authentication Pass!')
# break
# else:
# submit_button.click()
time.sleep(5)
sel.quit() | identifier_body |
prettier.ts | import type { PackageJson } from 'type-fest';
import Generator from '../generator.js';
export default class PrettierGenerator extends Generator {
public async configuring(): Promise<void> {
if (!this.isNpmPackage()) {
return;
}
this.packageJson.merge({
scripts: {
format: 'prettier --write .',
'format:check': 'prettier --check .',
},
});
const devDependencies = ['prettier', 'prettier-plugin-pkg', 'prettier-plugin-sh'];
if (this.hasAnyDependency('typescript')) {
devDependencies.push('prettier-plugin-organize-imports');
}
await this.addDevDependencies(devDependencies);
}
public | (): void {
const packageFiles = (this.packageJson.get('files') as PackageJson['files']) ?? [];
const options = {
files: packageFiles.map((packageFile) => `${packageFile}\n`).join(''),
flow: this.hasDevDependency('flow-bin'),
husky: this.hasFiles('.husky'),
jekyll: this.hasFiles('docs/_config.yml') || this.hasFiles('_config.yml'),
test: this.hasDevDependency('jest'),
yarn: this.hasFiles('.yarn'),
};
this.copyTemplate('prettierrc.json', '.prettierrc.json');
this.renderTemplate('prettierignore', '.prettierignore', options);
}
}
| writing | identifier_name |
prettier.ts | import type { PackageJson } from 'type-fest';
import Generator from '../generator.js';
export default class PrettierGenerator extends Generator {
public async configuring(): Promise<void> {
if (!this.isNpmPackage()) {
return;
}
this.packageJson.merge({
scripts: {
format: 'prettier --write .',
'format:check': 'prettier --check .',
},
});
const devDependencies = ['prettier', 'prettier-plugin-pkg', 'prettier-plugin-sh'];
if (this.hasAnyDependency('typescript')) {
devDependencies.push('prettier-plugin-organize-imports');
}
await this.addDevDependencies(devDependencies);
}
public writing(): void |
}
| {
const packageFiles = (this.packageJson.get('files') as PackageJson['files']) ?? [];
const options = {
files: packageFiles.map((packageFile) => `${packageFile}\n`).join(''),
flow: this.hasDevDependency('flow-bin'),
husky: this.hasFiles('.husky'),
jekyll: this.hasFiles('docs/_config.yml') || this.hasFiles('_config.yml'),
test: this.hasDevDependency('jest'),
yarn: this.hasFiles('.yarn'),
};
this.copyTemplate('prettierrc.json', '.prettierrc.json');
this.renderTemplate('prettierignore', '.prettierignore', options);
} | identifier_body |
prettier.ts | import type { PackageJson } from 'type-fest';
import Generator from '../generator.js';
export default class PrettierGenerator extends Generator {
public async configuring(): Promise<void> {
if (!this.isNpmPackage()) {
return;
}
this.packageJson.merge({
scripts: {
format: 'prettier --write .',
'format:check': 'prettier --check .',
},
});
const devDependencies = ['prettier', 'prettier-plugin-pkg', 'prettier-plugin-sh'];
| if (this.hasAnyDependency('typescript')) {
devDependencies.push('prettier-plugin-organize-imports');
}
await this.addDevDependencies(devDependencies);
}
public writing(): void {
const packageFiles = (this.packageJson.get('files') as PackageJson['files']) ?? [];
const options = {
files: packageFiles.map((packageFile) => `${packageFile}\n`).join(''),
flow: this.hasDevDependency('flow-bin'),
husky: this.hasFiles('.husky'),
jekyll: this.hasFiles('docs/_config.yml') || this.hasFiles('_config.yml'),
test: this.hasDevDependency('jest'),
yarn: this.hasFiles('.yarn'),
};
this.copyTemplate('prettierrc.json', '.prettierrc.json');
this.renderTemplate('prettierignore', '.prettierignore', options);
}
} | random_line_split | |
prettier.ts | import type { PackageJson } from 'type-fest';
import Generator from '../generator.js';
export default class PrettierGenerator extends Generator {
public async configuring(): Promise<void> {
if (!this.isNpmPackage()) |
this.packageJson.merge({
scripts: {
format: 'prettier --write .',
'format:check': 'prettier --check .',
},
});
const devDependencies = ['prettier', 'prettier-plugin-pkg', 'prettier-plugin-sh'];
if (this.hasAnyDependency('typescript')) {
devDependencies.push('prettier-plugin-organize-imports');
}
await this.addDevDependencies(devDependencies);
}
public writing(): void {
const packageFiles = (this.packageJson.get('files') as PackageJson['files']) ?? [];
const options = {
files: packageFiles.map((packageFile) => `${packageFile}\n`).join(''),
flow: this.hasDevDependency('flow-bin'),
husky: this.hasFiles('.husky'),
jekyll: this.hasFiles('docs/_config.yml') || this.hasFiles('_config.yml'),
test: this.hasDevDependency('jest'),
yarn: this.hasFiles('.yarn'),
};
this.copyTemplate('prettierrc.json', '.prettierrc.json');
this.renderTemplate('prettierignore', '.prettierignore', options);
}
}
| {
return;
} | conditional_block |
test_distributed_scheduler.py | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Tests For Distributed Scheduler.
"""
import json
import nova.db
from nova import context
from nova import exception
from nova import rpc
from nova import test
from nova.compute import api as compute_api
from nova.scheduler import distributed_scheduler
from nova.scheduler import least_cost
from nova.scheduler import zone_manager
from nova.tests.scheduler import fake_zone_manager as ds_fakes
class FakeEmptyZoneManager(zone_manager.ZoneManager):
def __init__(self):
self.service_states = {}
def get_host_list_from_db(self, context):
return []
def _compute_node_get_all(*args, **kwargs):
return []
def _instance_get_all(*args, **kwargs):
return []
def fake_call_zone_method(context, method, specs, zones):
return [
(1, [
dict(weight=2, blob='AAAAAAA'),
dict(weight=4, blob='BBBBBBB'),
dict(weight=6, blob='CCCCCCC'),
dict(weight=8, blob='DDDDDDD'),
]),
(2, [
dict(weight=10, blob='EEEEEEE'),
dict(weight=12, blob='FFFFFFF'),
dict(weight=14, blob='GGGGGGG'),
dict(weight=16, blob='HHHHHHH'),
]),
(3, [
dict(weight=18, blob='IIIIIII'),
dict(weight=20, blob='JJJJJJJ'),
dict(weight=22, blob='KKKKKKK'),
dict(weight=24, blob='LLLLLLL'),
]),
]
def fake_zone_get_all(context):
return [
dict(id=1, api_url='zone1',
username='admin', password='password',
weight_offset=0.0, weight_scale=1.0),
dict(id=2, api_url='zone2',
username='admin', password='password',
weight_offset=1000.0, weight_scale=1.0),
dict(id=3, api_url='zone3',
username='admin', password='password',
weight_offset=0.0, weight_scale=1000.0),
]
class DistributedSchedulerTestCase(test.TestCase):
"""Test case for Distributed Scheduler."""
def test_adjust_child_weights(self):
"""Make sure the weights returned by child zones are
properly adjusted based on the scale/offset in the zone
db entries.
"""
sched = ds_fakes.FakeDistributedScheduler()
child_results = fake_call_zone_method(None, None, None, None)
zones = fake_zone_get_all(None)
weighted_hosts = sched._adjust_child_weights(child_results, zones)
scaled = [130000, 131000, 132000, 3000]
for weighted_host in weighted_hosts:
w = weighted_host.weight
if weighted_host.zone == 'zone1': # No change
self.assertTrue(w < 1000.0)
if weighted_host.zone == 'zone2': # Offset +1000
self.assertTrue(w >= 1000.0 and w < 2000)
if weighted_host.zone == 'zone3': # Scale x1000
self.assertEqual(scaled.pop(0), w)
def test_run_instance_no_hosts(self):
"""
Ensure empty hosts & child_zones result in NoValidHosts exception.
"""
def _fake_empty_call_zone_method(*args, **kwargs):
return []
sched = ds_fakes.FakeDistributedScheduler()
sched.zone_manager = FakeEmptyZoneManager()
self.stubs.Set(sched, '_call_zone_method',
_fake_empty_call_zone_method)
self.stubs.Set(nova.db, 'zone_get_all', fake_zone_get_all)
fake_context = context.RequestContext('user', 'project')
request_spec = dict(instance_type=dict(memory_mb=1, local_gb=1))
self.assertRaises(exception.NoValidHost, sched.schedule_run_instance,
fake_context, request_spec)
def test_run_instance_with_blob_hint(self):
"""
Check the local/child zone routing in the run_instance() call.
If the zone_blob hint was passed in, don't re-schedule.
"""
self.schedule_called = False
self.from_blob_called = False
self.locally_called = False
self.child_zone_called = False
def _fake_schedule(*args, **kwargs):
self.schedule_called = True
return least_cost.WeightedHost(1, host='x')
def _fake_make_weighted_host_from_blob(*args, **kwargs):
self.from_blob_called = True
return least_cost.WeightedHost(1, zone='x', blob='y')
def _fake_provision_resource_locally(*args, **kwargs):
self.locally_called = True
return 1
def _fake_ask_child_zone_to_create_instance(*args, **kwargs):
self.child_zone_called = True
return 2
sched = ds_fakes.FakeDistributedScheduler()
self.stubs.Set(sched, '_schedule', _fake_schedule)
self.stubs.Set(sched, '_make_weighted_host_from_blob',
_fake_make_weighted_host_from_blob)
self.stubs.Set(sched, '_provision_resource_locally',
_fake_provision_resource_locally)
self.stubs.Set(sched, '_ask_child_zone_to_create_instance',
_fake_ask_child_zone_to_create_instance)
request_spec = {
'instance_properties': {},
'instance_type': {},
'filter_driver': 'nova.scheduler.host_filter.AllHostsFilter',
'blob': "Non-None blob data",
}
fake_context = context.RequestContext('user', 'project')
instances = sched.schedule_run_instance(fake_context, request_spec)
self.assertTrue(instances)
self.assertFalse(self.schedule_called)
self.assertTrue(self.from_blob_called)
self.assertTrue(self.child_zone_called)
self.assertFalse(self.locally_called)
self.assertEquals(instances, [2])
def test_run_instance_non_admin(self):
"""Test creating an instance locally using run_instance, passing
a non-admin context. DB actions should work."""
self.was_admin = False
def fake_schedule(context, *args, **kwargs):
# make sure this is called with admin context, even though
# we're using user context below
self.was_admin = context.is_admin
return []
sched = ds_fakes.FakeDistributedScheduler()
self.stubs.Set(sched, '_schedule', fake_schedule)
fake_context = context.RequestContext('user', 'project')
self.assertRaises(exception.NoValidHost, sched.schedule_run_instance,
fake_context, {})
self.assertTrue(self.was_admin)
def test_schedule_bad_topic(self):
"""Parameter checking."""
sched = ds_fakes.FakeDistributedScheduler()
self.assertRaises(NotImplementedError, sched._schedule, None, "foo",
{})
def test_schedule_no_instance_type(self):
"""Parameter checking."""
sched = ds_fakes.FakeDistributedScheduler()
self.assertRaises(NotImplementedError, sched._schedule, None,
"compute", {})
def test_schedule_happy_day(self):
"""_schedule() has no branching logic beyond basic input parameter
checking. Just make sure there's nothing glaringly wrong by doing
a happy day pass through."""
self.next_weight = 1.0
def _fake_filter_hosts(topic, request_info, unfiltered_hosts,
options):
return unfiltered_hosts
def _fake_weighted_sum(functions, hosts, options):
self.next_weight += 2.0
host, hostinfo = hosts[0]
return least_cost.WeightedHost(self.next_weight, host=host,
hostinfo=hostinfo)
sched = ds_fakes.FakeDistributedScheduler()
fake_context = context.RequestContext('user', 'project')
sched.zone_manager = ds_fakes.FakeZoneManager()
self.stubs.Set(sched, '_filter_hosts', _fake_filter_hosts)
self.stubs.Set(least_cost, 'weighted_sum', _fake_weighted_sum)
self.stubs.Set(nova.db, 'zone_get_all', fake_zone_get_all)
self.stubs.Set(sched, '_call_zone_method', fake_call_zone_method)
instance_type = dict(memory_mb=512, local_gb=512)
request_spec = dict(num_instances=10, instance_type=instance_type)
weighted_hosts = sched._schedule(fake_context, 'compute',
request_spec)
self.assertEquals(len(weighted_hosts), 10)
for weighted_host in weighted_hosts:
# We set this up so remote hosts have even weights ...
if int(weighted_host.weight) % 2 == 0:
self.assertTrue(weighted_host.zone != None)
self.assertTrue(weighted_host.host == None)
else:
self.assertTrue(weighted_host.host != None)
self.assertTrue(weighted_host.zone == None)
def test_decrypt_blob(self):
"""Test that the decrypt method works."""
fixture = ds_fakes.FakeDistributedScheduler()
test_data = {'weight': 1, 'host': 'x', 'blob': 'y', 'zone': 'z'}
class StubDecryptor(object):
def decryptor(self, key):
return lambda blob: blob
self.stubs.Set(distributed_scheduler, 'crypto', StubDecryptor())
weighted_host = fixture._make_weighted_host_from_blob(
json.dumps(test_data))
self.assertTrue(isinstance(weighted_host, least_cost.WeightedHost))
self.assertEqual(weighted_host.to_dict(), dict(weight=1, host='x',
blob='y', zone='z')) |
def test_get_cost_functions(self):
fixture = ds_fakes.FakeDistributedScheduler()
fns = fixture.get_cost_functions()
self.assertEquals(len(fns), 1)
weight, fn = fns[0]
self.assertEquals(weight, 1.0)
hostinfo = zone_manager.HostInfo('host', free_ram_mb=1000)
self.assertEquals(1000, fn(hostinfo)) | random_line_split | |
test_distributed_scheduler.py | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Tests For Distributed Scheduler.
"""
import json
import nova.db
from nova import context
from nova import exception
from nova import rpc
from nova import test
from nova.compute import api as compute_api
from nova.scheduler import distributed_scheduler
from nova.scheduler import least_cost
from nova.scheduler import zone_manager
from nova.tests.scheduler import fake_zone_manager as ds_fakes
class FakeEmptyZoneManager(zone_manager.ZoneManager):
def __init__(self):
self.service_states = {}
def get_host_list_from_db(self, context):
return []
def _compute_node_get_all(*args, **kwargs):
return []
def _instance_get_all(*args, **kwargs):
return []
def fake_call_zone_method(context, method, specs, zones):
return [
(1, [
dict(weight=2, blob='AAAAAAA'),
dict(weight=4, blob='BBBBBBB'),
dict(weight=6, blob='CCCCCCC'),
dict(weight=8, blob='DDDDDDD'),
]),
(2, [
dict(weight=10, blob='EEEEEEE'),
dict(weight=12, blob='FFFFFFF'),
dict(weight=14, blob='GGGGGGG'),
dict(weight=16, blob='HHHHHHH'),
]),
(3, [
dict(weight=18, blob='IIIIIII'),
dict(weight=20, blob='JJJJJJJ'),
dict(weight=22, blob='KKKKKKK'),
dict(weight=24, blob='LLLLLLL'),
]),
]
def fake_zone_get_all(context):
return [
dict(id=1, api_url='zone1',
username='admin', password='password',
weight_offset=0.0, weight_scale=1.0),
dict(id=2, api_url='zone2',
username='admin', password='password',
weight_offset=1000.0, weight_scale=1.0),
dict(id=3, api_url='zone3',
username='admin', password='password',
weight_offset=0.0, weight_scale=1000.0),
]
class DistributedSchedulerTestCase(test.TestCase):
"""Test case for Distributed Scheduler."""
def test_adjust_child_weights(self):
"""Make sure the weights returned by child zones are
properly adjusted based on the scale/offset in the zone
db entries.
"""
sched = ds_fakes.FakeDistributedScheduler()
child_results = fake_call_zone_method(None, None, None, None)
zones = fake_zone_get_all(None)
weighted_hosts = sched._adjust_child_weights(child_results, zones)
scaled = [130000, 131000, 132000, 3000]
for weighted_host in weighted_hosts:
w = weighted_host.weight
if weighted_host.zone == 'zone1': # No change
self.assertTrue(w < 1000.0)
if weighted_host.zone == 'zone2': # Offset +1000
self.assertTrue(w >= 1000.0 and w < 2000)
if weighted_host.zone == 'zone3': # Scale x1000
self.assertEqual(scaled.pop(0), w)
def test_run_instance_no_hosts(self):
"""
Ensure empty hosts & child_zones result in NoValidHosts exception.
"""
def _fake_empty_call_zone_method(*args, **kwargs):
return []
sched = ds_fakes.FakeDistributedScheduler()
sched.zone_manager = FakeEmptyZoneManager()
self.stubs.Set(sched, '_call_zone_method',
_fake_empty_call_zone_method)
self.stubs.Set(nova.db, 'zone_get_all', fake_zone_get_all)
fake_context = context.RequestContext('user', 'project')
request_spec = dict(instance_type=dict(memory_mb=1, local_gb=1))
self.assertRaises(exception.NoValidHost, sched.schedule_run_instance,
fake_context, request_spec)
def test_run_instance_with_blob_hint(self):
"""
Check the local/child zone routing in the run_instance() call.
If the zone_blob hint was passed in, don't re-schedule.
"""
self.schedule_called = False
self.from_blob_called = False
self.locally_called = False
self.child_zone_called = False
def _fake_schedule(*args, **kwargs):
self.schedule_called = True
return least_cost.WeightedHost(1, host='x')
def _fake_make_weighted_host_from_blob(*args, **kwargs):
self.from_blob_called = True
return least_cost.WeightedHost(1, zone='x', blob='y')
def _fake_provision_resource_locally(*args, **kwargs):
self.locally_called = True
return 1
def _fake_ask_child_zone_to_create_instance(*args, **kwargs):
self.child_zone_called = True
return 2
sched = ds_fakes.FakeDistributedScheduler()
self.stubs.Set(sched, '_schedule', _fake_schedule)
self.stubs.Set(sched, '_make_weighted_host_from_blob',
_fake_make_weighted_host_from_blob)
self.stubs.Set(sched, '_provision_resource_locally',
_fake_provision_resource_locally)
self.stubs.Set(sched, '_ask_child_zone_to_create_instance',
_fake_ask_child_zone_to_create_instance)
request_spec = {
'instance_properties': {},
'instance_type': {},
'filter_driver': 'nova.scheduler.host_filter.AllHostsFilter',
'blob': "Non-None blob data",
}
fake_context = context.RequestContext('user', 'project')
instances = sched.schedule_run_instance(fake_context, request_spec)
self.assertTrue(instances)
self.assertFalse(self.schedule_called)
self.assertTrue(self.from_blob_called)
self.assertTrue(self.child_zone_called)
self.assertFalse(self.locally_called)
self.assertEquals(instances, [2])
def test_run_instance_non_admin(self):
"""Test creating an instance locally using run_instance, passing
a non-admin context. DB actions should work."""
self.was_admin = False
def fake_schedule(context, *args, **kwargs):
# make sure this is called with admin context, even though
# we're using user context below
self.was_admin = context.is_admin
return []
sched = ds_fakes.FakeDistributedScheduler()
self.stubs.Set(sched, '_schedule', fake_schedule)
fake_context = context.RequestContext('user', 'project')
self.assertRaises(exception.NoValidHost, sched.schedule_run_instance,
fake_context, {})
self.assertTrue(self.was_admin)
def test_schedule_bad_topic(self):
"""Parameter checking."""
sched = ds_fakes.FakeDistributedScheduler()
self.assertRaises(NotImplementedError, sched._schedule, None, "foo",
{})
def test_schedule_no_instance_type(self):
"""Parameter checking."""
sched = ds_fakes.FakeDistributedScheduler()
self.assertRaises(NotImplementedError, sched._schedule, None,
"compute", {})
def test_schedule_happy_day(self):
"""_schedule() has no branching logic beyond basic input parameter
checking. Just make sure there's nothing glaringly wrong by doing
a happy day pass through."""
self.next_weight = 1.0
def _fake_filter_hosts(topic, request_info, unfiltered_hosts,
options):
return unfiltered_hosts
def _fake_weighted_sum(functions, hosts, options):
self.next_weight += 2.0
host, hostinfo = hosts[0]
return least_cost.WeightedHost(self.next_weight, host=host,
hostinfo=hostinfo)
sched = ds_fakes.FakeDistributedScheduler()
fake_context = context.RequestContext('user', 'project')
sched.zone_manager = ds_fakes.FakeZoneManager()
self.stubs.Set(sched, '_filter_hosts', _fake_filter_hosts)
self.stubs.Set(least_cost, 'weighted_sum', _fake_weighted_sum)
self.stubs.Set(nova.db, 'zone_get_all', fake_zone_get_all)
self.stubs.Set(sched, '_call_zone_method', fake_call_zone_method)
instance_type = dict(memory_mb=512, local_gb=512)
request_spec = dict(num_instances=10, instance_type=instance_type)
weighted_hosts = sched._schedule(fake_context, 'compute',
request_spec)
self.assertEquals(len(weighted_hosts), 10)
for weighted_host in weighted_hosts:
# We set this up so remote hosts have even weights ...
if int(weighted_host.weight) % 2 == 0:
self.assertTrue(weighted_host.zone != None)
self.assertTrue(weighted_host.host == None)
else:
self.assertTrue(weighted_host.host != None)
self.assertTrue(weighted_host.zone == None)
def test_decrypt_blob(self):
"""Test that the decrypt method works."""
fixture = ds_fakes.FakeDistributedScheduler()
test_data = {'weight': 1, 'host': 'x', 'blob': 'y', 'zone': 'z'}
class | (object):
def decryptor(self, key):
return lambda blob: blob
self.stubs.Set(distributed_scheduler, 'crypto', StubDecryptor())
weighted_host = fixture._make_weighted_host_from_blob(
json.dumps(test_data))
self.assertTrue(isinstance(weighted_host, least_cost.WeightedHost))
self.assertEqual(weighted_host.to_dict(), dict(weight=1, host='x',
blob='y', zone='z'))
def test_get_cost_functions(self):
fixture = ds_fakes.FakeDistributedScheduler()
fns = fixture.get_cost_functions()
self.assertEquals(len(fns), 1)
weight, fn = fns[0]
self.assertEquals(weight, 1.0)
hostinfo = zone_manager.HostInfo('host', free_ram_mb=1000)
self.assertEquals(1000, fn(hostinfo))
| StubDecryptor | identifier_name |
test_distributed_scheduler.py | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Tests For Distributed Scheduler.
"""
import json
import nova.db
from nova import context
from nova import exception
from nova import rpc
from nova import test
from nova.compute import api as compute_api
from nova.scheduler import distributed_scheduler
from nova.scheduler import least_cost
from nova.scheduler import zone_manager
from nova.tests.scheduler import fake_zone_manager as ds_fakes
class FakeEmptyZoneManager(zone_manager.ZoneManager):
def __init__(self):
self.service_states = {}
def get_host_list_from_db(self, context):
return []
def _compute_node_get_all(*args, **kwargs):
return []
def _instance_get_all(*args, **kwargs):
return []
def fake_call_zone_method(context, method, specs, zones):
return [
(1, [
dict(weight=2, blob='AAAAAAA'),
dict(weight=4, blob='BBBBBBB'),
dict(weight=6, blob='CCCCCCC'),
dict(weight=8, blob='DDDDDDD'),
]),
(2, [
dict(weight=10, blob='EEEEEEE'),
dict(weight=12, blob='FFFFFFF'),
dict(weight=14, blob='GGGGGGG'),
dict(weight=16, blob='HHHHHHH'),
]),
(3, [
dict(weight=18, blob='IIIIIII'),
dict(weight=20, blob='JJJJJJJ'),
dict(weight=22, blob='KKKKKKK'),
dict(weight=24, blob='LLLLLLL'),
]),
]
def fake_zone_get_all(context):
return [
dict(id=1, api_url='zone1',
username='admin', password='password',
weight_offset=0.0, weight_scale=1.0),
dict(id=2, api_url='zone2',
username='admin', password='password',
weight_offset=1000.0, weight_scale=1.0),
dict(id=3, api_url='zone3',
username='admin', password='password',
weight_offset=0.0, weight_scale=1000.0),
]
class DistributedSchedulerTestCase(test.TestCase):
"""Test case for Distributed Scheduler."""
def test_adjust_child_weights(self):
"""Make sure the weights returned by child zones are
properly adjusted based on the scale/offset in the zone
db entries.
"""
sched = ds_fakes.FakeDistributedScheduler()
child_results = fake_call_zone_method(None, None, None, None)
zones = fake_zone_get_all(None)
weighted_hosts = sched._adjust_child_weights(child_results, zones)
scaled = [130000, 131000, 132000, 3000]
for weighted_host in weighted_hosts:
w = weighted_host.weight
if weighted_host.zone == 'zone1': # No change
self.assertTrue(w < 1000.0)
if weighted_host.zone == 'zone2': # Offset +1000
self.assertTrue(w >= 1000.0 and w < 2000)
if weighted_host.zone == 'zone3': # Scale x1000
self.assertEqual(scaled.pop(0), w)
def test_run_instance_no_hosts(self):
"""
Ensure empty hosts & child_zones result in NoValidHosts exception.
"""
def _fake_empty_call_zone_method(*args, **kwargs):
return []
sched = ds_fakes.FakeDistributedScheduler()
sched.zone_manager = FakeEmptyZoneManager()
self.stubs.Set(sched, '_call_zone_method',
_fake_empty_call_zone_method)
self.stubs.Set(nova.db, 'zone_get_all', fake_zone_get_all)
fake_context = context.RequestContext('user', 'project')
request_spec = dict(instance_type=dict(memory_mb=1, local_gb=1))
self.assertRaises(exception.NoValidHost, sched.schedule_run_instance,
fake_context, request_spec)
def test_run_instance_with_blob_hint(self):
"""
Check the local/child zone routing in the run_instance() call.
If the zone_blob hint was passed in, don't re-schedule.
"""
self.schedule_called = False
self.from_blob_called = False
self.locally_called = False
self.child_zone_called = False
def _fake_schedule(*args, **kwargs):
self.schedule_called = True
return least_cost.WeightedHost(1, host='x')
def _fake_make_weighted_host_from_blob(*args, **kwargs):
self.from_blob_called = True
return least_cost.WeightedHost(1, zone='x', blob='y')
def _fake_provision_resource_locally(*args, **kwargs):
|
def _fake_ask_child_zone_to_create_instance(*args, **kwargs):
self.child_zone_called = True
return 2
sched = ds_fakes.FakeDistributedScheduler()
self.stubs.Set(sched, '_schedule', _fake_schedule)
self.stubs.Set(sched, '_make_weighted_host_from_blob',
_fake_make_weighted_host_from_blob)
self.stubs.Set(sched, '_provision_resource_locally',
_fake_provision_resource_locally)
self.stubs.Set(sched, '_ask_child_zone_to_create_instance',
_fake_ask_child_zone_to_create_instance)
request_spec = {
'instance_properties': {},
'instance_type': {},
'filter_driver': 'nova.scheduler.host_filter.AllHostsFilter',
'blob': "Non-None blob data",
}
fake_context = context.RequestContext('user', 'project')
instances = sched.schedule_run_instance(fake_context, request_spec)
self.assertTrue(instances)
self.assertFalse(self.schedule_called)
self.assertTrue(self.from_blob_called)
self.assertTrue(self.child_zone_called)
self.assertFalse(self.locally_called)
self.assertEquals(instances, [2])
def test_run_instance_non_admin(self):
"""Test creating an instance locally using run_instance, passing
a non-admin context. DB actions should work."""
self.was_admin = False
def fake_schedule(context, *args, **kwargs):
# make sure this is called with admin context, even though
# we're using user context below
self.was_admin = context.is_admin
return []
sched = ds_fakes.FakeDistributedScheduler()
self.stubs.Set(sched, '_schedule', fake_schedule)
fake_context = context.RequestContext('user', 'project')
self.assertRaises(exception.NoValidHost, sched.schedule_run_instance,
fake_context, {})
self.assertTrue(self.was_admin)
def test_schedule_bad_topic(self):
"""Parameter checking."""
sched = ds_fakes.FakeDistributedScheduler()
self.assertRaises(NotImplementedError, sched._schedule, None, "foo",
{})
def test_schedule_no_instance_type(self):
"""Parameter checking."""
sched = ds_fakes.FakeDistributedScheduler()
self.assertRaises(NotImplementedError, sched._schedule, None,
"compute", {})
def test_schedule_happy_day(self):
"""_schedule() has no branching logic beyond basic input parameter
checking. Just make sure there's nothing glaringly wrong by doing
a happy day pass through."""
self.next_weight = 1.0
def _fake_filter_hosts(topic, request_info, unfiltered_hosts,
options):
return unfiltered_hosts
def _fake_weighted_sum(functions, hosts, options):
self.next_weight += 2.0
host, hostinfo = hosts[0]
return least_cost.WeightedHost(self.next_weight, host=host,
hostinfo=hostinfo)
sched = ds_fakes.FakeDistributedScheduler()
fake_context = context.RequestContext('user', 'project')
sched.zone_manager = ds_fakes.FakeZoneManager()
self.stubs.Set(sched, '_filter_hosts', _fake_filter_hosts)
self.stubs.Set(least_cost, 'weighted_sum', _fake_weighted_sum)
self.stubs.Set(nova.db, 'zone_get_all', fake_zone_get_all)
self.stubs.Set(sched, '_call_zone_method', fake_call_zone_method)
instance_type = dict(memory_mb=512, local_gb=512)
request_spec = dict(num_instances=10, instance_type=instance_type)
weighted_hosts = sched._schedule(fake_context, 'compute',
request_spec)
self.assertEquals(len(weighted_hosts), 10)
for weighted_host in weighted_hosts:
# We set this up so remote hosts have even weights ...
if int(weighted_host.weight) % 2 == 0:
self.assertTrue(weighted_host.zone != None)
self.assertTrue(weighted_host.host == None)
else:
self.assertTrue(weighted_host.host != None)
self.assertTrue(weighted_host.zone == None)
def test_decrypt_blob(self):
"""Test that the decrypt method works."""
fixture = ds_fakes.FakeDistributedScheduler()
test_data = {'weight': 1, 'host': 'x', 'blob': 'y', 'zone': 'z'}
class StubDecryptor(object):
def decryptor(self, key):
return lambda blob: blob
self.stubs.Set(distributed_scheduler, 'crypto', StubDecryptor())
weighted_host = fixture._make_weighted_host_from_blob(
json.dumps(test_data))
self.assertTrue(isinstance(weighted_host, least_cost.WeightedHost))
self.assertEqual(weighted_host.to_dict(), dict(weight=1, host='x',
blob='y', zone='z'))
def test_get_cost_functions(self):
fixture = ds_fakes.FakeDistributedScheduler()
fns = fixture.get_cost_functions()
self.assertEquals(len(fns), 1)
weight, fn = fns[0]
self.assertEquals(weight, 1.0)
hostinfo = zone_manager.HostInfo('host', free_ram_mb=1000)
self.assertEquals(1000, fn(hostinfo))
| self.locally_called = True
return 1 | identifier_body |
test_distributed_scheduler.py | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Tests For Distributed Scheduler.
"""
import json
import nova.db
from nova import context
from nova import exception
from nova import rpc
from nova import test
from nova.compute import api as compute_api
from nova.scheduler import distributed_scheduler
from nova.scheduler import least_cost
from nova.scheduler import zone_manager
from nova.tests.scheduler import fake_zone_manager as ds_fakes
class FakeEmptyZoneManager(zone_manager.ZoneManager):
def __init__(self):
self.service_states = {}
def get_host_list_from_db(self, context):
return []
def _compute_node_get_all(*args, **kwargs):
return []
def _instance_get_all(*args, **kwargs):
return []
def fake_call_zone_method(context, method, specs, zones):
return [
(1, [
dict(weight=2, blob='AAAAAAA'),
dict(weight=4, blob='BBBBBBB'),
dict(weight=6, blob='CCCCCCC'),
dict(weight=8, blob='DDDDDDD'),
]),
(2, [
dict(weight=10, blob='EEEEEEE'),
dict(weight=12, blob='FFFFFFF'),
dict(weight=14, blob='GGGGGGG'),
dict(weight=16, blob='HHHHHHH'),
]),
(3, [
dict(weight=18, blob='IIIIIII'),
dict(weight=20, blob='JJJJJJJ'),
dict(weight=22, blob='KKKKKKK'),
dict(weight=24, blob='LLLLLLL'),
]),
]
def fake_zone_get_all(context):
return [
dict(id=1, api_url='zone1',
username='admin', password='password',
weight_offset=0.0, weight_scale=1.0),
dict(id=2, api_url='zone2',
username='admin', password='password',
weight_offset=1000.0, weight_scale=1.0),
dict(id=3, api_url='zone3',
username='admin', password='password',
weight_offset=0.0, weight_scale=1000.0),
]
class DistributedSchedulerTestCase(test.TestCase):
"""Test case for Distributed Scheduler."""
def test_adjust_child_weights(self):
"""Make sure the weights returned by child zones are
properly adjusted based on the scale/offset in the zone
db entries.
"""
sched = ds_fakes.FakeDistributedScheduler()
child_results = fake_call_zone_method(None, None, None, None)
zones = fake_zone_get_all(None)
weighted_hosts = sched._adjust_child_weights(child_results, zones)
scaled = [130000, 131000, 132000, 3000]
for weighted_host in weighted_hosts:
|
def test_run_instance_no_hosts(self):
"""
Ensure empty hosts & child_zones result in NoValidHosts exception.
"""
def _fake_empty_call_zone_method(*args, **kwargs):
return []
sched = ds_fakes.FakeDistributedScheduler()
sched.zone_manager = FakeEmptyZoneManager()
self.stubs.Set(sched, '_call_zone_method',
_fake_empty_call_zone_method)
self.stubs.Set(nova.db, 'zone_get_all', fake_zone_get_all)
fake_context = context.RequestContext('user', 'project')
request_spec = dict(instance_type=dict(memory_mb=1, local_gb=1))
self.assertRaises(exception.NoValidHost, sched.schedule_run_instance,
fake_context, request_spec)
def test_run_instance_with_blob_hint(self):
"""
Check the local/child zone routing in the run_instance() call.
If the zone_blob hint was passed in, don't re-schedule.
"""
self.schedule_called = False
self.from_blob_called = False
self.locally_called = False
self.child_zone_called = False
def _fake_schedule(*args, **kwargs):
self.schedule_called = True
return least_cost.WeightedHost(1, host='x')
def _fake_make_weighted_host_from_blob(*args, **kwargs):
self.from_blob_called = True
return least_cost.WeightedHost(1, zone='x', blob='y')
def _fake_provision_resource_locally(*args, **kwargs):
self.locally_called = True
return 1
def _fake_ask_child_zone_to_create_instance(*args, **kwargs):
self.child_zone_called = True
return 2
sched = ds_fakes.FakeDistributedScheduler()
self.stubs.Set(sched, '_schedule', _fake_schedule)
self.stubs.Set(sched, '_make_weighted_host_from_blob',
_fake_make_weighted_host_from_blob)
self.stubs.Set(sched, '_provision_resource_locally',
_fake_provision_resource_locally)
self.stubs.Set(sched, '_ask_child_zone_to_create_instance',
_fake_ask_child_zone_to_create_instance)
request_spec = {
'instance_properties': {},
'instance_type': {},
'filter_driver': 'nova.scheduler.host_filter.AllHostsFilter',
'blob': "Non-None blob data",
}
fake_context = context.RequestContext('user', 'project')
instances = sched.schedule_run_instance(fake_context, request_spec)
self.assertTrue(instances)
self.assertFalse(self.schedule_called)
self.assertTrue(self.from_blob_called)
self.assertTrue(self.child_zone_called)
self.assertFalse(self.locally_called)
self.assertEquals(instances, [2])
def test_run_instance_non_admin(self):
"""Test creating an instance locally using run_instance, passing
a non-admin context. DB actions should work."""
self.was_admin = False
def fake_schedule(context, *args, **kwargs):
# make sure this is called with admin context, even though
# we're using user context below
self.was_admin = context.is_admin
return []
sched = ds_fakes.FakeDistributedScheduler()
self.stubs.Set(sched, '_schedule', fake_schedule)
fake_context = context.RequestContext('user', 'project')
self.assertRaises(exception.NoValidHost, sched.schedule_run_instance,
fake_context, {})
self.assertTrue(self.was_admin)
def test_schedule_bad_topic(self):
"""Parameter checking."""
sched = ds_fakes.FakeDistributedScheduler()
self.assertRaises(NotImplementedError, sched._schedule, None, "foo",
{})
def test_schedule_no_instance_type(self):
"""Parameter checking."""
sched = ds_fakes.FakeDistributedScheduler()
self.assertRaises(NotImplementedError, sched._schedule, None,
"compute", {})
def test_schedule_happy_day(self):
"""_schedule() has no branching logic beyond basic input parameter
checking. Just make sure there's nothing glaringly wrong by doing
a happy day pass through."""
self.next_weight = 1.0
def _fake_filter_hosts(topic, request_info, unfiltered_hosts,
options):
return unfiltered_hosts
def _fake_weighted_sum(functions, hosts, options):
self.next_weight += 2.0
host, hostinfo = hosts[0]
return least_cost.WeightedHost(self.next_weight, host=host,
hostinfo=hostinfo)
sched = ds_fakes.FakeDistributedScheduler()
fake_context = context.RequestContext('user', 'project')
sched.zone_manager = ds_fakes.FakeZoneManager()
self.stubs.Set(sched, '_filter_hosts', _fake_filter_hosts)
self.stubs.Set(least_cost, 'weighted_sum', _fake_weighted_sum)
self.stubs.Set(nova.db, 'zone_get_all', fake_zone_get_all)
self.stubs.Set(sched, '_call_zone_method', fake_call_zone_method)
instance_type = dict(memory_mb=512, local_gb=512)
request_spec = dict(num_instances=10, instance_type=instance_type)
weighted_hosts = sched._schedule(fake_context, 'compute',
request_spec)
self.assertEquals(len(weighted_hosts), 10)
for weighted_host in weighted_hosts:
# We set this up so remote hosts have even weights ...
if int(weighted_host.weight) % 2 == 0:
self.assertTrue(weighted_host.zone != None)
self.assertTrue(weighted_host.host == None)
else:
self.assertTrue(weighted_host.host != None)
self.assertTrue(weighted_host.zone == None)
def test_decrypt_blob(self):
"""Test that the decrypt method works."""
fixture = ds_fakes.FakeDistributedScheduler()
test_data = {'weight': 1, 'host': 'x', 'blob': 'y', 'zone': 'z'}
class StubDecryptor(object):
def decryptor(self, key):
return lambda blob: blob
self.stubs.Set(distributed_scheduler, 'crypto', StubDecryptor())
weighted_host = fixture._make_weighted_host_from_blob(
json.dumps(test_data))
self.assertTrue(isinstance(weighted_host, least_cost.WeightedHost))
self.assertEqual(weighted_host.to_dict(), dict(weight=1, host='x',
blob='y', zone='z'))
def test_get_cost_functions(self):
fixture = ds_fakes.FakeDistributedScheduler()
fns = fixture.get_cost_functions()
self.assertEquals(len(fns), 1)
weight, fn = fns[0]
self.assertEquals(weight, 1.0)
hostinfo = zone_manager.HostInfo('host', free_ram_mb=1000)
self.assertEquals(1000, fn(hostinfo))
| w = weighted_host.weight
if weighted_host.zone == 'zone1': # No change
self.assertTrue(w < 1000.0)
if weighted_host.zone == 'zone2': # Offset +1000
self.assertTrue(w >= 1000.0 and w < 2000)
if weighted_host.zone == 'zone3': # Scale x1000
self.assertEqual(scaled.pop(0), w) | conditional_block |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf}; | search_paths: &[PathBuf],
sess: &Session,
) -> PathBuf {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = if verbatim {
name.to_string()
} else {
format!("{}{}{}", sess.target.staticlib_prefix, name, sess.target.staticlib_suffix)
};
let unixlibname = format!("lib{}.a", name);
for path in search_paths {
debug!("looking for {} inside {:?}", name, path);
let test = path.join(&oslibname);
if test.exists() {
return test;
}
if oslibname != unixlibname {
let test = path.join(&unixlibname);
if test.exists() {
return test;
}
}
}
sess.fatal(&format!(
"could not find native static library `{}`, \
perhaps an -L flag is missing?",
name
));
}
pub trait ArchiveBuilder<'a> {
fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self;
fn add_file(&mut self, path: &Path);
fn remove_file(&mut self, name: &str);
fn src_files(&mut self) -> Vec<String>;
fn add_archive<F>(&mut self, archive: &Path, skip: F) -> io::Result<()>
where
F: FnMut(&str) -> bool + 'static;
fn update_symbols(&mut self);
fn build(self);
fn inject_dll_import_lib(
&mut self,
lib_name: &str,
dll_imports: &[DllImport],
tmpdir: &MaybeTempDir,
);
} |
pub(super) fn find_library(
name: Symbol,
verbatim: bool, | random_line_split |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf};
pub(super) fn find_library(
name: Symbol,
verbatim: bool,
search_paths: &[PathBuf],
sess: &Session,
) -> PathBuf {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = if verbatim {
name.to_string()
} else | ;
let unixlibname = format!("lib{}.a", name);
for path in search_paths {
debug!("looking for {} inside {:?}", name, path);
let test = path.join(&oslibname);
if test.exists() {
return test;
}
if oslibname != unixlibname {
let test = path.join(&unixlibname);
if test.exists() {
return test;
}
}
}
sess.fatal(&format!(
"could not find native static library `{}`, \
perhaps an -L flag is missing?",
name
));
}
pub trait ArchiveBuilder<'a> {
fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self;
fn add_file(&mut self, path: &Path);
fn remove_file(&mut self, name: &str);
fn src_files(&mut self) -> Vec<String>;
fn add_archive<F>(&mut self, archive: &Path, skip: F) -> io::Result<()>
where
F: FnMut(&str) -> bool + 'static;
fn update_symbols(&mut self);
fn build(self);
fn inject_dll_import_lib(
&mut self,
lib_name: &str,
dll_imports: &[DllImport],
tmpdir: &MaybeTempDir,
);
}
| {
format!("{}{}{}", sess.target.staticlib_prefix, name, sess.target.staticlib_suffix)
} | conditional_block |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf};
pub(super) fn | (
name: Symbol,
verbatim: bool,
search_paths: &[PathBuf],
sess: &Session,
) -> PathBuf {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = if verbatim {
name.to_string()
} else {
format!("{}{}{}", sess.target.staticlib_prefix, name, sess.target.staticlib_suffix)
};
let unixlibname = format!("lib{}.a", name);
for path in search_paths {
debug!("looking for {} inside {:?}", name, path);
let test = path.join(&oslibname);
if test.exists() {
return test;
}
if oslibname != unixlibname {
let test = path.join(&unixlibname);
if test.exists() {
return test;
}
}
}
sess.fatal(&format!(
"could not find native static library `{}`, \
perhaps an -L flag is missing?",
name
));
}
pub trait ArchiveBuilder<'a> {
fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self;
fn add_file(&mut self, path: &Path);
fn remove_file(&mut self, name: &str);
fn src_files(&mut self) -> Vec<String>;
fn add_archive<F>(&mut self, archive: &Path, skip: F) -> io::Result<()>
where
F: FnMut(&str) -> bool + 'static;
fn update_symbols(&mut self);
fn build(self);
fn inject_dll_import_lib(
&mut self,
lib_name: &str,
dll_imports: &[DllImport],
tmpdir: &MaybeTempDir,
);
}
| find_library | identifier_name |
archive.rs | use rustc_data_structures::temp_dir::MaybeTempDir;
use rustc_session::cstore::DllImport;
use rustc_session::Session;
use rustc_span::symbol::Symbol;
use std::io;
use std::path::{Path, PathBuf};
pub(super) fn find_library(
name: Symbol,
verbatim: bool,
search_paths: &[PathBuf],
sess: &Session,
) -> PathBuf |
pub trait ArchiveBuilder<'a> {
fn new(sess: &'a Session, output: &Path, input: Option<&Path>) -> Self;
fn add_file(&mut self, path: &Path);
fn remove_file(&mut self, name: &str);
fn src_files(&mut self) -> Vec<String>;
fn add_archive<F>(&mut self, archive: &Path, skip: F) -> io::Result<()>
where
F: FnMut(&str) -> bool + 'static;
fn update_symbols(&mut self);
fn build(self);
fn inject_dll_import_lib(
&mut self,
lib_name: &str,
dll_imports: &[DllImport],
tmpdir: &MaybeTempDir,
);
}
| {
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = if verbatim {
name.to_string()
} else {
format!("{}{}{}", sess.target.staticlib_prefix, name, sess.target.staticlib_suffix)
};
let unixlibname = format!("lib{}.a", name);
for path in search_paths {
debug!("looking for {} inside {:?}", name, path);
let test = path.join(&oslibname);
if test.exists() {
return test;
}
if oslibname != unixlibname {
let test = path.join(&unixlibname);
if test.exists() {
return test;
}
}
}
sess.fatal(&format!(
"could not find native static library `{}`, \
perhaps an -L flag is missing?",
name
));
} | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
"""
Moisture Plugin
Copyright (C) 2013 Olaf Lüke <olaf@tinkerforge.com>
__init__.py: package initialization
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public
License along with this program; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
"""
|
device_class = Moisture | from brickv.plugin_system.plugins.moisture.moisture import Moisture | random_line_split |
__init__.py | # PPFem: An educational finite element code
# Copyright (C) 2015 Matthias Rambausek
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import ppfem.user_elements
import ppfem.user_equations
import ppfem.quadrature
from ppfem.user_elements import *
from ppfem.user_equations import *
from ppfem.quadrature import *
from ppfem.mesh.mesh import Mesh
from ppfem.geometry import Point, Vertex, Line, Face, Cell, Mapping |
__all__ = ["Mesh", "Point", "Line", "Vertex", "Face", "Cell", "Mapping", "FunctionSpace", "Functional",
"LinearForm", "BilinearForm", "FormCollection", "DefaultSystemAssembler", "FEFunction", "FunctionEvaluator",
"PDE"]
__all__ += ppfem.user_elements.__all__ + ppfem.quadrature.__all__ + ppfem.user_equations.__all__ | from ppfem.fem.assembler import DefaultSystemAssembler
from ppfem.fem.form import Functional, LinearForm, BilinearForm, FormCollection
from ppfem.fem.function import FEFunction, FunctionEvaluator
from ppfem.fem.function_space import FunctionSpace
from ppfem.fem.partial_differential_equation import PDE | random_line_split |
stackmachine.py | import operator
import math
class Machine():
"""Simple stack based machine designed for genetic programming (GP) experiments.
Easy to use and forgiving with nonfatal errors.
See README and tests for examples.
"""
def __init__(self, debug=False):
self.stack = []
self.debug = debug
self.code = ""
self.stack_safety = False
self.has_errors = False
self._max_runlines = 1000
self._max_stack = 1000
self.instructions = {
'CLR': self._clr,
'PUSH': self._push, # takes 1 value
'POP': self._pop,
'SWP': self._swp,
'ROT': self._rot,
'DUP': self._dup,
'INC': self._inc,
'MUL': lambda: self._operator2(operator.mul),
'DIV': lambda: self._operator2(operator.div),
'MOD': lambda: self._operator2(operator.mod),
'ADD': lambda: self._operator2(operator.add),
'SUB': lambda: self._operator2(operator.sub),
'EXP': lambda: self._operator2(operator.pow),
'MIN': lambda: self._operator2(min),
'MAX': lambda: self._operator2(max),
'LOG': lambda: self._operator1(math.log),
'TRUNC':lambda: self._operator1(math.trunc),
'JMP': self._jmp, # all jumps take an offset value
'JZ': self._jz,
'JE': self._je,
'JNE': self._jne,
'JLT': self._jlt,
'JGT': self._jgt,
'END': None
}
def _operator1(self, operator): | def _operator2(self, operator):
if len(self.stack) < 2:
self.stack = [0]
else:
val = operator(self.stack[-1], self.stack[-2])
self.stack = self.stack[:-2]
self.stack.append(val)
def _clr(self):
self.stack = []
def _push(self, a):
try:
a = float(a)
self.stack.append(a)
except:
pass
def _pop(self):
if self.stack:
self.stack.pop()
def _inc(self):
if self.stack:
self.stack[-1] += 1
def _swp(self):
if len(self.stack) > 1:
self.stack[-2], self.stack[-1] = self.stack[-1], self.stack[-2]
def _rot(self):
if len(self.stack) > 1:
self.stack = self.stack[1:] + self.stack[:1]
def _dup(self):
if self.stack:
self.stack.append(self.stack[-1])
def _jmp(self, a):
n = self._curline + int(a)
if n == self._curline or n < 0 or n > len(self.lines) - 1:
return
self._curline = n-1
def _jz(self, a):
if self.stack:
if self.stack.pop() == 0:
self._jmp(a)
def _je(self, a):
if len(self.stack) > 1:
if self.stack.pop() == self.stack.pop():
self._jmp(a)
def _jne(self, a):
if len(self.stack) > 1:
if self.stack.pop() != self.stack.pop():
self._jmp(a)
def _jlt(self, a):
if len(self.stack) > 1:
if self.stack.pop() < self.stack.pop():
self._jmp(a)
def _jgt(self, a):
if len(self.stack) > 1:
if self.stack.pop() > self.stack.pop():
self._jmp(a)
def verify_stack(self):
if len(self.stack) > self._max_stack:
return False
allowed_types = [int, float, long]
return all([type(v) in allowed_types for v in self.stack])
def code_listing(self):
self.lines = self.code.split('\n')
for num, line in enumerate(self.lines):
line = line.strip().upper()
print num, '\t', line
def evaluate(self, line):
if line:
debug = self.debug
if debug: print self._curline, '> ', line
tokens = line.split()
instr = tokens[0]
if instr == 'END': return False
if len(tokens) > 1:
values = tokens [1:]
else: values = []
try:
self.instructions[instr](*values)
except Exception as e:
if debug: print "Error:", e
self.has_errors = True
if debug: print self.stack, '\n'
self._curline += 1
return True
def run(self):
# Note: some class members are duplicated with locals for faster comparisons in the main loop
self._curline = 0
self.has_errors = False
self._lines_executed = 0
lines_exec = 0
max_exec = self._max_runlines
lines = [line.split(';')[0].strip().upper() for line in self.code.split('\n')]
self.lines = lines
if self.stack_safety and not self.verify_stack():
if self.debug: print "Invalid stack, must only contain ints, longs, and floats"
return
while(self.evaluate(self.lines[self._curline])):
lines_exec += 1
if lines_exec > max_exec:
if self.debug: print "Reached maximum runlines:", self._max_runlines
self.has_errors = True
break
if self._curline >= len(self.lines):
break
self._lines_executed = lines_exec
return self.has_errors | if self.stack:
self.stack.append(operator(self.stack.pop()))
| random_line_split |
stackmachine.py | import operator
import math
class Machine():
"""Simple stack based machine designed for genetic programming (GP) experiments.
Easy to use and forgiving with nonfatal errors.
See README and tests for examples.
"""
def __init__(self, debug=False):
self.stack = []
self.debug = debug
self.code = ""
self.stack_safety = False
self.has_errors = False
self._max_runlines = 1000
self._max_stack = 1000
self.instructions = {
'CLR': self._clr,
'PUSH': self._push, # takes 1 value
'POP': self._pop,
'SWP': self._swp,
'ROT': self._rot,
'DUP': self._dup,
'INC': self._inc,
'MUL': lambda: self._operator2(operator.mul),
'DIV': lambda: self._operator2(operator.div),
'MOD': lambda: self._operator2(operator.mod),
'ADD': lambda: self._operator2(operator.add),
'SUB': lambda: self._operator2(operator.sub),
'EXP': lambda: self._operator2(operator.pow),
'MIN': lambda: self._operator2(min),
'MAX': lambda: self._operator2(max),
'LOG': lambda: self._operator1(math.log),
'TRUNC':lambda: self._operator1(math.trunc),
'JMP': self._jmp, # all jumps take an offset value
'JZ': self._jz,
'JE': self._je,
'JNE': self._jne,
'JLT': self._jlt,
'JGT': self._jgt,
'END': None
}
def _operator1(self, operator):
if self.stack:
self.stack.append(operator(self.stack.pop()))
def _operator2(self, operator):
if len(self.stack) < 2:
self.stack = [0]
else:
val = operator(self.stack[-1], self.stack[-2])
self.stack = self.stack[:-2]
self.stack.append(val)
def _clr(self):
self.stack = []
def _push(self, a):
try:
a = float(a)
self.stack.append(a)
except:
pass
def _pop(self):
if self.stack:
self.stack.pop()
def _inc(self):
if self.stack:
self.stack[-1] += 1
def _swp(self):
if len(self.stack) > 1:
self.stack[-2], self.stack[-1] = self.stack[-1], self.stack[-2]
def _rot(self):
if len(self.stack) > 1:
self.stack = self.stack[1:] + self.stack[:1]
def _dup(self):
if self.stack:
self.stack.append(self.stack[-1])
def _jmp(self, a):
n = self._curline + int(a)
if n == self._curline or n < 0 or n > len(self.lines) - 1:
return
self._curline = n-1
def _jz(self, a):
if self.stack:
if self.stack.pop() == 0:
self._jmp(a)
def _je(self, a):
if len(self.stack) > 1:
if self.stack.pop() == self.stack.pop():
self._jmp(a)
def _jne(self, a):
|
def _jlt(self, a):
if len(self.stack) > 1:
if self.stack.pop() < self.stack.pop():
self._jmp(a)
def _jgt(self, a):
if len(self.stack) > 1:
if self.stack.pop() > self.stack.pop():
self._jmp(a)
def verify_stack(self):
if len(self.stack) > self._max_stack:
return False
allowed_types = [int, float, long]
return all([type(v) in allowed_types for v in self.stack])
def code_listing(self):
self.lines = self.code.split('\n')
for num, line in enumerate(self.lines):
line = line.strip().upper()
print num, '\t', line
def evaluate(self, line):
if line:
debug = self.debug
if debug: print self._curline, '> ', line
tokens = line.split()
instr = tokens[0]
if instr == 'END': return False
if len(tokens) > 1:
values = tokens [1:]
else: values = []
try:
self.instructions[instr](*values)
except Exception as e:
if debug: print "Error:", e
self.has_errors = True
if debug: print self.stack, '\n'
self._curline += 1
return True
def run(self):
# Note: some class members are duplicated with locals for faster comparisons in the main loop
self._curline = 0
self.has_errors = False
self._lines_executed = 0
lines_exec = 0
max_exec = self._max_runlines
lines = [line.split(';')[0].strip().upper() for line in self.code.split('\n')]
self.lines = lines
if self.stack_safety and not self.verify_stack():
if self.debug: print "Invalid stack, must only contain ints, longs, and floats"
return
while(self.evaluate(self.lines[self._curline])):
lines_exec += 1
if lines_exec > max_exec:
if self.debug: print "Reached maximum runlines:", self._max_runlines
self.has_errors = True
break
if self._curline >= len(self.lines):
break
self._lines_executed = lines_exec
return self.has_errors
| if len(self.stack) > 1:
if self.stack.pop() != self.stack.pop():
self._jmp(a) | identifier_body |
stackmachine.py | import operator
import math
class Machine():
"""Simple stack based machine designed for genetic programming (GP) experiments.
Easy to use and forgiving with nonfatal errors.
See README and tests for examples.
"""
def __init__(self, debug=False):
self.stack = []
self.debug = debug
self.code = ""
self.stack_safety = False
self.has_errors = False
self._max_runlines = 1000
self._max_stack = 1000
self.instructions = {
'CLR': self._clr,
'PUSH': self._push, # takes 1 value
'POP': self._pop,
'SWP': self._swp,
'ROT': self._rot,
'DUP': self._dup,
'INC': self._inc,
'MUL': lambda: self._operator2(operator.mul),
'DIV': lambda: self._operator2(operator.div),
'MOD': lambda: self._operator2(operator.mod),
'ADD': lambda: self._operator2(operator.add),
'SUB': lambda: self._operator2(operator.sub),
'EXP': lambda: self._operator2(operator.pow),
'MIN': lambda: self._operator2(min),
'MAX': lambda: self._operator2(max),
'LOG': lambda: self._operator1(math.log),
'TRUNC':lambda: self._operator1(math.trunc),
'JMP': self._jmp, # all jumps take an offset value
'JZ': self._jz,
'JE': self._je,
'JNE': self._jne,
'JLT': self._jlt,
'JGT': self._jgt,
'END': None
}
def _operator1(self, operator):
if self.stack:
self.stack.append(operator(self.stack.pop()))
def _operator2(self, operator):
if len(self.stack) < 2:
self.stack = [0]
else:
val = operator(self.stack[-1], self.stack[-2])
self.stack = self.stack[:-2]
self.stack.append(val)
def _clr(self):
self.stack = []
def _push(self, a):
try:
a = float(a)
self.stack.append(a)
except:
pass
def _pop(self):
if self.stack:
self.stack.pop()
def _inc(self):
if self.stack:
self.stack[-1] += 1
def _swp(self):
if len(self.stack) > 1:
self.stack[-2], self.stack[-1] = self.stack[-1], self.stack[-2]
def _rot(self):
if len(self.stack) > 1:
self.stack = self.stack[1:] + self.stack[:1]
def _dup(self):
if self.stack:
self.stack.append(self.stack[-1])
def _jmp(self, a):
n = self._curline + int(a)
if n == self._curline or n < 0 or n > len(self.lines) - 1:
return
self._curline = n-1
def _jz(self, a):
if self.stack:
if self.stack.pop() == 0:
self._jmp(a)
def _je(self, a):
if len(self.stack) > 1:
if self.stack.pop() == self.stack.pop():
|
def _jne(self, a):
if len(self.stack) > 1:
if self.stack.pop() != self.stack.pop():
self._jmp(a)
def _jlt(self, a):
if len(self.stack) > 1:
if self.stack.pop() < self.stack.pop():
self._jmp(a)
def _jgt(self, a):
if len(self.stack) > 1:
if self.stack.pop() > self.stack.pop():
self._jmp(a)
def verify_stack(self):
if len(self.stack) > self._max_stack:
return False
allowed_types = [int, float, long]
return all([type(v) in allowed_types for v in self.stack])
def code_listing(self):
self.lines = self.code.split('\n')
for num, line in enumerate(self.lines):
line = line.strip().upper()
print num, '\t', line
def evaluate(self, line):
if line:
debug = self.debug
if debug: print self._curline, '> ', line
tokens = line.split()
instr = tokens[0]
if instr == 'END': return False
if len(tokens) > 1:
values = tokens [1:]
else: values = []
try:
self.instructions[instr](*values)
except Exception as e:
if debug: print "Error:", e
self.has_errors = True
if debug: print self.stack, '\n'
self._curline += 1
return True
def run(self):
# Note: some class members are duplicated with locals for faster comparisons in the main loop
self._curline = 0
self.has_errors = False
self._lines_executed = 0
lines_exec = 0
max_exec = self._max_runlines
lines = [line.split(';')[0].strip().upper() for line in self.code.split('\n')]
self.lines = lines
if self.stack_safety and not self.verify_stack():
if self.debug: print "Invalid stack, must only contain ints, longs, and floats"
return
while(self.evaluate(self.lines[self._curline])):
lines_exec += 1
if lines_exec > max_exec:
if self.debug: print "Reached maximum runlines:", self._max_runlines
self.has_errors = True
break
if self._curline >= len(self.lines):
break
self._lines_executed = lines_exec
return self.has_errors
| self._jmp(a) | conditional_block |
stackmachine.py | import operator
import math
class Machine():
"""Simple stack based machine designed for genetic programming (GP) experiments.
Easy to use and forgiving with nonfatal errors.
See README and tests for examples.
"""
def __init__(self, debug=False):
self.stack = []
self.debug = debug
self.code = ""
self.stack_safety = False
self.has_errors = False
self._max_runlines = 1000
self._max_stack = 1000
self.instructions = {
'CLR': self._clr,
'PUSH': self._push, # takes 1 value
'POP': self._pop,
'SWP': self._swp,
'ROT': self._rot,
'DUP': self._dup,
'INC': self._inc,
'MUL': lambda: self._operator2(operator.mul),
'DIV': lambda: self._operator2(operator.div),
'MOD': lambda: self._operator2(operator.mod),
'ADD': lambda: self._operator2(operator.add),
'SUB': lambda: self._operator2(operator.sub),
'EXP': lambda: self._operator2(operator.pow),
'MIN': lambda: self._operator2(min),
'MAX': lambda: self._operator2(max),
'LOG': lambda: self._operator1(math.log),
'TRUNC':lambda: self._operator1(math.trunc),
'JMP': self._jmp, # all jumps take an offset value
'JZ': self._jz,
'JE': self._je,
'JNE': self._jne,
'JLT': self._jlt,
'JGT': self._jgt,
'END': None
}
def _operator1(self, operator):
if self.stack:
self.stack.append(operator(self.stack.pop()))
def _operator2(self, operator):
if len(self.stack) < 2:
self.stack = [0]
else:
val = operator(self.stack[-1], self.stack[-2])
self.stack = self.stack[:-2]
self.stack.append(val)
def | (self):
self.stack = []
def _push(self, a):
try:
a = float(a)
self.stack.append(a)
except:
pass
def _pop(self):
if self.stack:
self.stack.pop()
def _inc(self):
if self.stack:
self.stack[-1] += 1
def _swp(self):
if len(self.stack) > 1:
self.stack[-2], self.stack[-1] = self.stack[-1], self.stack[-2]
def _rot(self):
if len(self.stack) > 1:
self.stack = self.stack[1:] + self.stack[:1]
def _dup(self):
if self.stack:
self.stack.append(self.stack[-1])
def _jmp(self, a):
n = self._curline + int(a)
if n == self._curline or n < 0 or n > len(self.lines) - 1:
return
self._curline = n-1
def _jz(self, a):
if self.stack:
if self.stack.pop() == 0:
self._jmp(a)
def _je(self, a):
if len(self.stack) > 1:
if self.stack.pop() == self.stack.pop():
self._jmp(a)
def _jne(self, a):
if len(self.stack) > 1:
if self.stack.pop() != self.stack.pop():
self._jmp(a)
def _jlt(self, a):
if len(self.stack) > 1:
if self.stack.pop() < self.stack.pop():
self._jmp(a)
def _jgt(self, a):
if len(self.stack) > 1:
if self.stack.pop() > self.stack.pop():
self._jmp(a)
def verify_stack(self):
if len(self.stack) > self._max_stack:
return False
allowed_types = [int, float, long]
return all([type(v) in allowed_types for v in self.stack])
def code_listing(self):
self.lines = self.code.split('\n')
for num, line in enumerate(self.lines):
line = line.strip().upper()
print num, '\t', line
def evaluate(self, line):
if line:
debug = self.debug
if debug: print self._curline, '> ', line
tokens = line.split()
instr = tokens[0]
if instr == 'END': return False
if len(tokens) > 1:
values = tokens [1:]
else: values = []
try:
self.instructions[instr](*values)
except Exception as e:
if debug: print "Error:", e
self.has_errors = True
if debug: print self.stack, '\n'
self._curline += 1
return True
def run(self):
# Note: some class members are duplicated with locals for faster comparisons in the main loop
self._curline = 0
self.has_errors = False
self._lines_executed = 0
lines_exec = 0
max_exec = self._max_runlines
lines = [line.split(';')[0].strip().upper() for line in self.code.split('\n')]
self.lines = lines
if self.stack_safety and not self.verify_stack():
if self.debug: print "Invalid stack, must only contain ints, longs, and floats"
return
while(self.evaluate(self.lines[self._curline])):
lines_exec += 1
if lines_exec > max_exec:
if self.debug: print "Reached maximum runlines:", self._max_runlines
self.has_errors = True
break
if self._curline >= len(self.lines):
break
self._lines_executed = lines_exec
return self.has_errors
| _clr | identifier_name |
elasticsearch_util.py | #!/usr/bin/env python
# coding=utf-8
import commands
import sys
from docopt import docopt
#from handler import LogFileClient
from sdutil.log_util import getLogger
from sdutil.date_util import *
reload(sys)
sys.setdefaultencoding('utf-8')
from elasticsearch import Elasticsearch
from pdb import *
import requests
import json
logger = getLogger(__name__, __file__)
"""
host like:"http://172.17.0.33:8081"
"""
def count_from_es(host,index,query_str,startTime,endTime,scroll=False):
logger.info('search_from_es startTime:%s,endTime:%s'%(startTime,endTime))
startTimeStamp = int(str2timestamp(startTime))*1000
endTimeStamp = int(str2timestamp(endTime))*1000+999
data_post_search = {"query":{"filtered":{"query":{"query_string":{"query":query_str,"analyze_wildcard":'true'}},"filter":{"bool":{"must":[{"range":{"@timestamp":{"gte":startTimeStamp,"lte":endTimeStamp,"format":"epoch_millis"}}}],"must_not":[]}}}}}
logger.info('search_from_es,post_data:%s'%(data_post_search))
es = Elasticsearch(host,timeout=120)
response = es.count(index=index, body=data_post_search)
return response
def do_search(host,index,query_str,startTimeStamp,endTimeStamp,scroll,_source,time_step):
es = Elasticsearch(host,timeout=120)
response ={}
data_post_search = {"query":{"filtered":{"query":{"query_string":{"query":query_str,"analyze_wildcard":'true'}},"filter":{"bool":{"must":[{"range":{"@timestamp":{"gte":startTimeStamp,"lte":endTimeStamp,"format":"epoch_millis"}}}],"must_not":[]}}}}}
logger.info('search_from_es,post_data:%s'%(data_post_search))
if not scroll:
if _source:
response = es.search(index=index, body=data_post_search,size=10000,_source=_source)
else:
response = es.search(index=index, body=data_post_search,size=10000)
else:
page_size=10000
scan_resp =None
if _source:
scan_resp = es.search(index=index, body=data_post_search,search_type="scan", scroll="5m",size=page_size,_source=_source) | scrollId= scan_resp['_scroll_id']
response={}
total = scan_resp['hits']['total']
response_list =[]
scrollId_list =[]
for page_num in range(total/page_size + 1):
response_tmp ={}
response_tmp = es.scroll(scroll_id=scrollId, scroll= "5m")
#es.clear_scroll([scrollId])
scrollId = response_tmp['_scroll_id']
scrollId_list.append(str(scrollId))
response_list.append(response_tmp)
if response.has_key('hits'):
_hits = response['hits']
_hits['hits']+=response_tmp['hits']['hits']
response['hits'] = _hits
else:
response['hits'] = response_tmp['hits']
return response
def search_from_es(host,index,query_str,startTime,endTime,scroll=False,_source=None,time_step=0):
logger.info('search_from_es startTime:%s,endTime:%s'%(startTime,endTime))
startTimeStamp = int(str2timestamp(startTime))*1000
endTimeStamp = int(str2timestamp(endTime))*1000+999
all_response={}
timegap = endTimeStamp-startTimeStamp
if time_step>0:
_s1=startTimeStamp
_s2=startTimeStamp+time_step
run_time =0
all_response = {}
time_count = {}
while(_s2<=endTimeStamp):
response_tmp = do_search(host,index,query_str,_s1,_s2,scroll,_source,time_step)
#response_tmp = do_search(_s1,_s2)
if all_response.has_key('hits'):
_hits = all_response['hits']
_hits['hits']+=response_tmp['hits']['hits']
all_response['hits'] = _hits
else:
all_response['hits'] = response_tmp['hits']
run_time+=1
_s1=_s1+time_step
_s2 = _s2+time_step
if time_count.has_key(_s1):
time_count[_s1]+=1
else:
time_count[_s1]=1
if time_count.has_key(_s2):
time_count[_s2]+=1
else:
time_count[_s2]=1
print '----run_time:',run_time,'_s1:',_s1,',_s2:',_s2,',len:',len(all_response['hits']['hits'])
print '-s1--',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(_s1/1000))
print '-s2--',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(_s2/1000))
print time_count
time.sleep(2)
else:
all_response = do_search(host,index,query_str,startTimeStamp,endTimeStamp,scroll,_source,time_step)
return all_response | else:
scan_resp = es.search(index=index, body=data_post_search,search_type="scan", scroll="5m",size=page_size)
| random_line_split |
elasticsearch_util.py | #!/usr/bin/env python
# coding=utf-8
import commands
import sys
from docopt import docopt
#from handler import LogFileClient
from sdutil.log_util import getLogger
from sdutil.date_util import *
reload(sys)
sys.setdefaultencoding('utf-8')
from elasticsearch import Elasticsearch
from pdb import *
import requests
import json
logger = getLogger(__name__, __file__)
"""
host like:"http://172.17.0.33:8081"
"""
def count_from_es(host,index,query_str,startTime,endTime,scroll=False):
logger.info('search_from_es startTime:%s,endTime:%s'%(startTime,endTime))
startTimeStamp = int(str2timestamp(startTime))*1000
endTimeStamp = int(str2timestamp(endTime))*1000+999
data_post_search = {"query":{"filtered":{"query":{"query_string":{"query":query_str,"analyze_wildcard":'true'}},"filter":{"bool":{"must":[{"range":{"@timestamp":{"gte":startTimeStamp,"lte":endTimeStamp,"format":"epoch_millis"}}}],"must_not":[]}}}}}
logger.info('search_from_es,post_data:%s'%(data_post_search))
es = Elasticsearch(host,timeout=120)
response = es.count(index=index, body=data_post_search)
return response
def do_search(host,index,query_str,startTimeStamp,endTimeStamp,scroll,_source,time_step):
|
def search_from_es(host,index,query_str,startTime,endTime,scroll=False,_source=None,time_step=0):
logger.info('search_from_es startTime:%s,endTime:%s'%(startTime,endTime))
startTimeStamp = int(str2timestamp(startTime))*1000
endTimeStamp = int(str2timestamp(endTime))*1000+999
all_response={}
timegap = endTimeStamp-startTimeStamp
if time_step>0:
_s1=startTimeStamp
_s2=startTimeStamp+time_step
run_time =0
all_response = {}
time_count = {}
while(_s2<=endTimeStamp):
response_tmp = do_search(host,index,query_str,_s1,_s2,scroll,_source,time_step)
#response_tmp = do_search(_s1,_s2)
if all_response.has_key('hits'):
_hits = all_response['hits']
_hits['hits']+=response_tmp['hits']['hits']
all_response['hits'] = _hits
else:
all_response['hits'] = response_tmp['hits']
run_time+=1
_s1=_s1+time_step
_s2 = _s2+time_step
if time_count.has_key(_s1):
time_count[_s1]+=1
else:
time_count[_s1]=1
if time_count.has_key(_s2):
time_count[_s2]+=1
else:
time_count[_s2]=1
print '----run_time:',run_time,'_s1:',_s1,',_s2:',_s2,',len:',len(all_response['hits']['hits'])
print '-s1--',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(_s1/1000))
print '-s2--',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(_s2/1000))
print time_count
time.sleep(2)
else:
all_response = do_search(host,index,query_str,startTimeStamp,endTimeStamp,scroll,_source,time_step)
return all_response
| es = Elasticsearch(host,timeout=120)
response ={}
data_post_search = {"query":{"filtered":{"query":{"query_string":{"query":query_str,"analyze_wildcard":'true'}},"filter":{"bool":{"must":[{"range":{"@timestamp":{"gte":startTimeStamp,"lte":endTimeStamp,"format":"epoch_millis"}}}],"must_not":[]}}}}}
logger.info('search_from_es,post_data:%s'%(data_post_search))
if not scroll:
if _source:
response = es.search(index=index, body=data_post_search,size=10000,_source=_source)
else:
response = es.search(index=index, body=data_post_search,size=10000)
else:
page_size=10000
scan_resp =None
if _source:
scan_resp = es.search(index=index, body=data_post_search,search_type="scan", scroll="5m",size=page_size,_source=_source)
else:
scan_resp = es.search(index=index, body=data_post_search,search_type="scan", scroll="5m",size=page_size)
scrollId= scan_resp['_scroll_id']
response={}
total = scan_resp['hits']['total']
response_list =[]
scrollId_list =[]
for page_num in range(total/page_size + 1):
response_tmp ={}
response_tmp = es.scroll(scroll_id=scrollId, scroll= "5m")
#es.clear_scroll([scrollId])
scrollId = response_tmp['_scroll_id']
scrollId_list.append(str(scrollId))
response_list.append(response_tmp)
if response.has_key('hits'):
_hits = response['hits']
_hits['hits']+=response_tmp['hits']['hits']
response['hits'] = _hits
else:
response['hits'] = response_tmp['hits']
return response | identifier_body |
elasticsearch_util.py | #!/usr/bin/env python
# coding=utf-8
import commands
import sys
from docopt import docopt
#from handler import LogFileClient
from sdutil.log_util import getLogger
from sdutil.date_util import *
reload(sys)
sys.setdefaultencoding('utf-8')
from elasticsearch import Elasticsearch
from pdb import *
import requests
import json
logger = getLogger(__name__, __file__)
"""
host like:"http://172.17.0.33:8081"
"""
def count_from_es(host,index,query_str,startTime,endTime,scroll=False):
logger.info('search_from_es startTime:%s,endTime:%s'%(startTime,endTime))
startTimeStamp = int(str2timestamp(startTime))*1000
endTimeStamp = int(str2timestamp(endTime))*1000+999
data_post_search = {"query":{"filtered":{"query":{"query_string":{"query":query_str,"analyze_wildcard":'true'}},"filter":{"bool":{"must":[{"range":{"@timestamp":{"gte":startTimeStamp,"lte":endTimeStamp,"format":"epoch_millis"}}}],"must_not":[]}}}}}
logger.info('search_from_es,post_data:%s'%(data_post_search))
es = Elasticsearch(host,timeout=120)
response = es.count(index=index, body=data_post_search)
return response
def do_search(host,index,query_str,startTimeStamp,endTimeStamp,scroll,_source,time_step):
es = Elasticsearch(host,timeout=120)
response ={}
data_post_search = {"query":{"filtered":{"query":{"query_string":{"query":query_str,"analyze_wildcard":'true'}},"filter":{"bool":{"must":[{"range":{"@timestamp":{"gte":startTimeStamp,"lte":endTimeStamp,"format":"epoch_millis"}}}],"must_not":[]}}}}}
logger.info('search_from_es,post_data:%s'%(data_post_search))
if not scroll:
if _source:
response = es.search(index=index, body=data_post_search,size=10000,_source=_source)
else:
response = es.search(index=index, body=data_post_search,size=10000)
else:
page_size=10000
scan_resp =None
if _source:
scan_resp = es.search(index=index, body=data_post_search,search_type="scan", scroll="5m",size=page_size,_source=_source)
else:
scan_resp = es.search(index=index, body=data_post_search,search_type="scan", scroll="5m",size=page_size)
scrollId= scan_resp['_scroll_id']
response={}
total = scan_resp['hits']['total']
response_list =[]
scrollId_list =[]
for page_num in range(total/page_size + 1):
response_tmp ={}
response_tmp = es.scroll(scroll_id=scrollId, scroll= "5m")
#es.clear_scroll([scrollId])
scrollId = response_tmp['_scroll_id']
scrollId_list.append(str(scrollId))
response_list.append(response_tmp)
if response.has_key('hits'):
_hits = response['hits']
_hits['hits']+=response_tmp['hits']['hits']
response['hits'] = _hits
else:
response['hits'] = response_tmp['hits']
return response
def search_from_es(host,index,query_str,startTime,endTime,scroll=False,_source=None,time_step=0):
logger.info('search_from_es startTime:%s,endTime:%s'%(startTime,endTime))
startTimeStamp = int(str2timestamp(startTime))*1000
endTimeStamp = int(str2timestamp(endTime))*1000+999
all_response={}
timegap = endTimeStamp-startTimeStamp
if time_step>0:
_s1=startTimeStamp
_s2=startTimeStamp+time_step
run_time =0
all_response = {}
time_count = {}
while(_s2<=endTimeStamp):
|
else:
all_response = do_search(host,index,query_str,startTimeStamp,endTimeStamp,scroll,_source,time_step)
return all_response
| response_tmp = do_search(host,index,query_str,_s1,_s2,scroll,_source,time_step)
#response_tmp = do_search(_s1,_s2)
if all_response.has_key('hits'):
_hits = all_response['hits']
_hits['hits']+=response_tmp['hits']['hits']
all_response['hits'] = _hits
else:
all_response['hits'] = response_tmp['hits']
run_time+=1
_s1=_s1+time_step
_s2 = _s2+time_step
if time_count.has_key(_s1):
time_count[_s1]+=1
else:
time_count[_s1]=1
if time_count.has_key(_s2):
time_count[_s2]+=1
else:
time_count[_s2]=1
print '----run_time:',run_time,'_s1:',_s1,',_s2:',_s2,',len:',len(all_response['hits']['hits'])
print '-s1--',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(_s1/1000))
print '-s2--',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(_s2/1000))
print time_count
time.sleep(2) | conditional_block |
elasticsearch_util.py | #!/usr/bin/env python
# coding=utf-8
import commands
import sys
from docopt import docopt
#from handler import LogFileClient
from sdutil.log_util import getLogger
from sdutil.date_util import *
reload(sys)
sys.setdefaultencoding('utf-8')
from elasticsearch import Elasticsearch
from pdb import *
import requests
import json
logger = getLogger(__name__, __file__)
"""
host like:"http://172.17.0.33:8081"
"""
def | (host,index,query_str,startTime,endTime,scroll=False):
logger.info('search_from_es startTime:%s,endTime:%s'%(startTime,endTime))
startTimeStamp = int(str2timestamp(startTime))*1000
endTimeStamp = int(str2timestamp(endTime))*1000+999
data_post_search = {"query":{"filtered":{"query":{"query_string":{"query":query_str,"analyze_wildcard":'true'}},"filter":{"bool":{"must":[{"range":{"@timestamp":{"gte":startTimeStamp,"lte":endTimeStamp,"format":"epoch_millis"}}}],"must_not":[]}}}}}
logger.info('search_from_es,post_data:%s'%(data_post_search))
es = Elasticsearch(host,timeout=120)
response = es.count(index=index, body=data_post_search)
return response
def do_search(host,index,query_str,startTimeStamp,endTimeStamp,scroll,_source,time_step):
es = Elasticsearch(host,timeout=120)
response ={}
data_post_search = {"query":{"filtered":{"query":{"query_string":{"query":query_str,"analyze_wildcard":'true'}},"filter":{"bool":{"must":[{"range":{"@timestamp":{"gte":startTimeStamp,"lte":endTimeStamp,"format":"epoch_millis"}}}],"must_not":[]}}}}}
logger.info('search_from_es,post_data:%s'%(data_post_search))
if not scroll:
if _source:
response = es.search(index=index, body=data_post_search,size=10000,_source=_source)
else:
response = es.search(index=index, body=data_post_search,size=10000)
else:
page_size=10000
scan_resp =None
if _source:
scan_resp = es.search(index=index, body=data_post_search,search_type="scan", scroll="5m",size=page_size,_source=_source)
else:
scan_resp = es.search(index=index, body=data_post_search,search_type="scan", scroll="5m",size=page_size)
scrollId= scan_resp['_scroll_id']
response={}
total = scan_resp['hits']['total']
response_list =[]
scrollId_list =[]
for page_num in range(total/page_size + 1):
response_tmp ={}
response_tmp = es.scroll(scroll_id=scrollId, scroll= "5m")
#es.clear_scroll([scrollId])
scrollId = response_tmp['_scroll_id']
scrollId_list.append(str(scrollId))
response_list.append(response_tmp)
if response.has_key('hits'):
_hits = response['hits']
_hits['hits']+=response_tmp['hits']['hits']
response['hits'] = _hits
else:
response['hits'] = response_tmp['hits']
return response
def search_from_es(host,index,query_str,startTime,endTime,scroll=False,_source=None,time_step=0):
logger.info('search_from_es startTime:%s,endTime:%s'%(startTime,endTime))
startTimeStamp = int(str2timestamp(startTime))*1000
endTimeStamp = int(str2timestamp(endTime))*1000+999
all_response={}
timegap = endTimeStamp-startTimeStamp
if time_step>0:
_s1=startTimeStamp
_s2=startTimeStamp+time_step
run_time =0
all_response = {}
time_count = {}
while(_s2<=endTimeStamp):
response_tmp = do_search(host,index,query_str,_s1,_s2,scroll,_source,time_step)
#response_tmp = do_search(_s1,_s2)
if all_response.has_key('hits'):
_hits = all_response['hits']
_hits['hits']+=response_tmp['hits']['hits']
all_response['hits'] = _hits
else:
all_response['hits'] = response_tmp['hits']
run_time+=1
_s1=_s1+time_step
_s2 = _s2+time_step
if time_count.has_key(_s1):
time_count[_s1]+=1
else:
time_count[_s1]=1
if time_count.has_key(_s2):
time_count[_s2]+=1
else:
time_count[_s2]=1
print '----run_time:',run_time,'_s1:',_s1,',_s2:',_s2,',len:',len(all_response['hits']['hits'])
print '-s1--',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(_s1/1000))
print '-s2--',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(_s2/1000))
print time_count
time.sleep(2)
else:
all_response = do_search(host,index,query_str,startTimeStamp,endTimeStamp,scroll,_source,time_step)
return all_response
| count_from_es | identifier_name |
DataContainer.js | import React from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import _ from 'lodash';
import { api } from './Api';
import { formatJSON } from './utils';
export default createReactClass({
propTypes: {
params: PropTypes.object,
},
getInitialState() {
return {
data_container: null,
};
},
componentDidMount() {
const id = this.props.params.id;
const payload = {
aggregate: [
{ $match: { _id: id } },
],
};
api.getDataContainers(payload)
.then(response => this.setState({ data_container: _.get(response, 'data_containers[0]', {}) }));
},
render() {
if (this.state.data_container == null) {
return (<h1>Loading Data Container<span className="loading" /></h1>);
}
if (_.isEmpty(this.state.data_container)) |
return (
<div>
<h1>Data Container</h1>
<pre className="scroll">
{formatJSON(this.state.data_container)}
</pre>
</div>
);
},
});
| {
return (<div className="alert alert-error">Data not available</div>);
} | conditional_block |
DataContainer.js | import React from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class'; |
export default createReactClass({
propTypes: {
params: PropTypes.object,
},
getInitialState() {
return {
data_container: null,
};
},
componentDidMount() {
const id = this.props.params.id;
const payload = {
aggregate: [
{ $match: { _id: id } },
],
};
api.getDataContainers(payload)
.then(response => this.setState({ data_container: _.get(response, 'data_containers[0]', {}) }));
},
render() {
if (this.state.data_container == null) {
return (<h1>Loading Data Container<span className="loading" /></h1>);
}
if (_.isEmpty(this.state.data_container)) {
return (<div className="alert alert-error">Data not available</div>);
}
return (
<div>
<h1>Data Container</h1>
<pre className="scroll">
{formatJSON(this.state.data_container)}
</pre>
</div>
);
},
}); | import _ from 'lodash';
import { api } from './Api';
import { formatJSON } from './utils'; | random_line_split |
DataContainer.js | import React from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import _ from 'lodash';
import { api } from './Api';
import { formatJSON } from './utils';
export default createReactClass({
propTypes: {
params: PropTypes.object,
},
getInitialState() {
return {
data_container: null,
};
},
componentDidMount() {
const id = this.props.params.id;
const payload = {
aggregate: [
{ $match: { _id: id } },
],
};
api.getDataContainers(payload)
.then(response => this.setState({ data_container: _.get(response, 'data_containers[0]', {}) }));
},
| () {
if (this.state.data_container == null) {
return (<h1>Loading Data Container<span className="loading" /></h1>);
}
if (_.isEmpty(this.state.data_container)) {
return (<div className="alert alert-error">Data not available</div>);
}
return (
<div>
<h1>Data Container</h1>
<pre className="scroll">
{formatJSON(this.state.data_container)}
</pre>
</div>
);
},
});
| render | identifier_name |
DataContainer.js | import React from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import _ from 'lodash';
import { api } from './Api';
import { formatJSON } from './utils';
export default createReactClass({
propTypes: {
params: PropTypes.object,
},
getInitialState() | ,
componentDidMount() {
const id = this.props.params.id;
const payload = {
aggregate: [
{ $match: { _id: id } },
],
};
api.getDataContainers(payload)
.then(response => this.setState({ data_container: _.get(response, 'data_containers[0]', {}) }));
},
render() {
if (this.state.data_container == null) {
return (<h1>Loading Data Container<span className="loading" /></h1>);
}
if (_.isEmpty(this.state.data_container)) {
return (<div className="alert alert-error">Data not available</div>);
}
return (
<div>
<h1>Data Container</h1>
<pre className="scroll">
{formatJSON(this.state.data_container)}
</pre>
</div>
);
},
});
| {
return {
data_container: null,
};
} | identifier_body |
train.py | import argparse
import copy
import numpy as np
import chainer
from chainer.datasets import ConcatenatedDataset
from chainer.datasets import TransformDataset
from chainer.optimizer_hooks import WeightDecay
from chainer import serializers
from chainer import training
from chainer.training import extensions
from chainer.training import triggers
from chainercv.datasets import voc_bbox_label_names
from chainercv.datasets import VOCBboxDataset
from chainercv.extensions import DetectionVOCEvaluator
from chainercv.links.model.ssd import GradientScaling
from chainercv.links.model.ssd import multibox_loss
from chainercv.links import SSD300
from chainercv.links import SSD512
from chainercv import transforms
from chainercv.links.model.ssd import random_crop_with_bbox_constraints
from chainercv.links.model.ssd import random_distort
from chainercv.links.model.ssd import resize_with_random_interpolation
# https://docs.chainer.org/en/stable/tips.html#my-training-process-gets-stuck-when-using-multiprocessiterator
import cv2
cv2.setNumThreads(0)
class MultiboxTrainChain(chainer.Chain):
def __init__(self, model, alpha=1, k=3):
super(MultiboxTrainChain, self).__init__()
with self.init_scope():
self.model = model
self.alpha = alpha
self.k = k
def forward(self, imgs, gt_mb_locs, gt_mb_labels):
mb_locs, mb_confs = self.model(imgs)
loc_loss, conf_loss = multibox_loss(
mb_locs, mb_confs, gt_mb_locs, gt_mb_labels, self.k)
loss = loc_loss * self.alpha + conf_loss
chainer.reporter.report(
{'loss': loss, 'loss/loc': loc_loss, 'loss/conf': conf_loss},
self)
return loss
class Transform(object):
def __init__(self, coder, size, mean):
# to send cpu, make a copy
self.coder = copy.copy(coder)
self.coder.to_cpu()
self.size = size
self.mean = mean
def | (self, in_data):
# There are five data augmentation steps
# 1. Color augmentation
# 2. Random expansion
# 3. Random cropping
# 4. Resizing with random interpolation
# 5. Random horizontal flipping
img, bbox, label = in_data
# 1. Color augmentation
img = random_distort(img)
# 2. Random expansion
if np.random.randint(2):
img, param = transforms.random_expand(
img, fill=self.mean, return_param=True)
bbox = transforms.translate_bbox(
bbox, y_offset=param['y_offset'], x_offset=param['x_offset'])
# 3. Random cropping
img, param = random_crop_with_bbox_constraints(
img, bbox, return_param=True)
bbox, param = transforms.crop_bbox(
bbox, y_slice=param['y_slice'], x_slice=param['x_slice'],
allow_outside_center=False, return_param=True)
label = label[param['index']]
# 4. Resizing with random interpolatation
_, H, W = img.shape
img = resize_with_random_interpolation(img, (self.size, self.size))
bbox = transforms.resize_bbox(bbox, (H, W), (self.size, self.size))
# 5. Random horizontal flipping
img, params = transforms.random_flip(
img, x_random=True, return_param=True)
bbox = transforms.flip_bbox(
bbox, (self.size, self.size), x_flip=params['x_flip'])
# Preparation for SSD network
img -= self.mean
mb_loc, mb_label = self.coder.encode(bbox, label)
return img, mb_loc, mb_label
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--model', choices=('ssd300', 'ssd512'), default='ssd300')
parser.add_argument('--batchsize', type=int, default=32)
parser.add_argument('--iteration', type=int, default=120000)
parser.add_argument('--step', type=int, nargs='*', default=[80000, 100000])
parser.add_argument('--gpu', type=int, default=-1)
parser.add_argument('--out', default='result')
parser.add_argument('--resume')
args = parser.parse_args()
if args.model == 'ssd300':
model = SSD300(
n_fg_class=len(voc_bbox_label_names),
pretrained_model='imagenet')
elif args.model == 'ssd512':
model = SSD512(
n_fg_class=len(voc_bbox_label_names),
pretrained_model='imagenet')
model.use_preset('evaluate')
train_chain = MultiboxTrainChain(model)
if args.gpu >= 0:
chainer.cuda.get_device_from_id(args.gpu).use()
model.to_gpu()
train = TransformDataset(
ConcatenatedDataset(
VOCBboxDataset(year='2007', split='trainval'),
VOCBboxDataset(year='2012', split='trainval')
),
Transform(model.coder, model.insize, model.mean))
train_iter = chainer.iterators.MultiprocessIterator(train, args.batchsize)
test = VOCBboxDataset(
year='2007', split='test',
use_difficult=True, return_difficult=True)
test_iter = chainer.iterators.SerialIterator(
test, args.batchsize, repeat=False, shuffle=False)
# initial lr is set to 1e-3 by ExponentialShift
optimizer = chainer.optimizers.MomentumSGD()
optimizer.setup(train_chain)
for param in train_chain.params():
if param.name == 'b':
param.update_rule.add_hook(GradientScaling(2))
else:
param.update_rule.add_hook(WeightDecay(0.0005))
updater = training.updaters.StandardUpdater(
train_iter, optimizer, device=args.gpu)
trainer = training.Trainer(
updater, (args.iteration, 'iteration'), args.out)
trainer.extend(
extensions.ExponentialShift('lr', 0.1, init=1e-3),
trigger=triggers.ManualScheduleTrigger(args.step, 'iteration'))
trainer.extend(
DetectionVOCEvaluator(
test_iter, model, use_07_metric=True,
label_names=voc_bbox_label_names),
trigger=triggers.ManualScheduleTrigger(
args.step + [args.iteration], 'iteration'))
log_interval = 10, 'iteration'
trainer.extend(extensions.LogReport(trigger=log_interval))
trainer.extend(extensions.observe_lr(), trigger=log_interval)
trainer.extend(extensions.PrintReport(
['epoch', 'iteration', 'lr',
'main/loss', 'main/loss/loc', 'main/loss/conf',
'validation/main/map']),
trigger=log_interval)
trainer.extend(extensions.ProgressBar(update_interval=10))
trainer.extend(
extensions.snapshot(),
trigger=triggers.ManualScheduleTrigger(
args.step + [args.iteration], 'iteration'))
trainer.extend(
extensions.snapshot_object(model, 'model_iter_{.updater.iteration}'),
trigger=(args.iteration, 'iteration'))
if args.resume:
serializers.load_npz(args.resume, trainer)
trainer.run()
if __name__ == '__main__':
main()
| __call__ | identifier_name |
train.py | import argparse
import copy
import numpy as np
import chainer
from chainer.datasets import ConcatenatedDataset
from chainer.datasets import TransformDataset
from chainer.optimizer_hooks import WeightDecay
from chainer import serializers
from chainer import training
from chainer.training import extensions
from chainer.training import triggers
from chainercv.datasets import voc_bbox_label_names
from chainercv.datasets import VOCBboxDataset
from chainercv.extensions import DetectionVOCEvaluator
from chainercv.links.model.ssd import GradientScaling
from chainercv.links.model.ssd import multibox_loss
from chainercv.links import SSD300
from chainercv.links import SSD512
from chainercv import transforms
from chainercv.links.model.ssd import random_crop_with_bbox_constraints
from chainercv.links.model.ssd import random_distort
from chainercv.links.model.ssd import resize_with_random_interpolation
# https://docs.chainer.org/en/stable/tips.html#my-training-process-gets-stuck-when-using-multiprocessiterator
import cv2
cv2.setNumThreads(0)
class MultiboxTrainChain(chainer.Chain):
def __init__(self, model, alpha=1, k=3):
super(MultiboxTrainChain, self).__init__()
with self.init_scope():
self.model = model
self.alpha = alpha
self.k = k
def forward(self, imgs, gt_mb_locs, gt_mb_labels):
mb_locs, mb_confs = self.model(imgs)
loc_loss, conf_loss = multibox_loss(
mb_locs, mb_confs, gt_mb_locs, gt_mb_labels, self.k)
loss = loc_loss * self.alpha + conf_loss
chainer.reporter.report(
{'loss': loss, 'loss/loc': loc_loss, 'loss/conf': conf_loss},
self)
return loss
class Transform(object):
def __init__(self, coder, size, mean):
# to send cpu, make a copy
self.coder = copy.copy(coder)
self.coder.to_cpu()
self.size = size
self.mean = mean
def __call__(self, in_data):
# There are five data augmentation steps
# 1. Color augmentation
# 2. Random expansion
# 3. Random cropping
# 4. Resizing with random interpolation
# 5. Random horizontal flipping
img, bbox, label = in_data
# 1. Color augmentation
img = random_distort(img)
# 2. Random expansion
if np.random.randint(2):
img, param = transforms.random_expand(
img, fill=self.mean, return_param=True)
bbox = transforms.translate_bbox(
bbox, y_offset=param['y_offset'], x_offset=param['x_offset'])
# 3. Random cropping
img, param = random_crop_with_bbox_constraints(
img, bbox, return_param=True)
bbox, param = transforms.crop_bbox(
bbox, y_slice=param['y_slice'], x_slice=param['x_slice'],
allow_outside_center=False, return_param=True)
label = label[param['index']]
# 4. Resizing with random interpolatation
_, H, W = img.shape
img = resize_with_random_interpolation(img, (self.size, self.size))
bbox = transforms.resize_bbox(bbox, (H, W), (self.size, self.size))
# 5. Random horizontal flipping
img, params = transforms.random_flip(
img, x_random=True, return_param=True)
bbox = transforms.flip_bbox(
bbox, (self.size, self.size), x_flip=params['x_flip'])
# Preparation for SSD network
img -= self.mean
mb_loc, mb_label = self.coder.encode(bbox, label)
return img, mb_loc, mb_label
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--model', choices=('ssd300', 'ssd512'), default='ssd300')
parser.add_argument('--batchsize', type=int, default=32)
parser.add_argument('--iteration', type=int, default=120000)
parser.add_argument('--step', type=int, nargs='*', default=[80000, 100000])
parser.add_argument('--gpu', type=int, default=-1)
parser.add_argument('--out', default='result')
parser.add_argument('--resume')
args = parser.parse_args()
if args.model == 'ssd300':
model = SSD300(
n_fg_class=len(voc_bbox_label_names),
pretrained_model='imagenet')
elif args.model == 'ssd512':
model = SSD512(
n_fg_class=len(voc_bbox_label_names),
pretrained_model='imagenet')
model.use_preset('evaluate')
train_chain = MultiboxTrainChain(model)
if args.gpu >= 0:
|
train = TransformDataset(
ConcatenatedDataset(
VOCBboxDataset(year='2007', split='trainval'),
VOCBboxDataset(year='2012', split='trainval')
),
Transform(model.coder, model.insize, model.mean))
train_iter = chainer.iterators.MultiprocessIterator(train, args.batchsize)
test = VOCBboxDataset(
year='2007', split='test',
use_difficult=True, return_difficult=True)
test_iter = chainer.iterators.SerialIterator(
test, args.batchsize, repeat=False, shuffle=False)
# initial lr is set to 1e-3 by ExponentialShift
optimizer = chainer.optimizers.MomentumSGD()
optimizer.setup(train_chain)
for param in train_chain.params():
if param.name == 'b':
param.update_rule.add_hook(GradientScaling(2))
else:
param.update_rule.add_hook(WeightDecay(0.0005))
updater = training.updaters.StandardUpdater(
train_iter, optimizer, device=args.gpu)
trainer = training.Trainer(
updater, (args.iteration, 'iteration'), args.out)
trainer.extend(
extensions.ExponentialShift('lr', 0.1, init=1e-3),
trigger=triggers.ManualScheduleTrigger(args.step, 'iteration'))
trainer.extend(
DetectionVOCEvaluator(
test_iter, model, use_07_metric=True,
label_names=voc_bbox_label_names),
trigger=triggers.ManualScheduleTrigger(
args.step + [args.iteration], 'iteration'))
log_interval = 10, 'iteration'
trainer.extend(extensions.LogReport(trigger=log_interval))
trainer.extend(extensions.observe_lr(), trigger=log_interval)
trainer.extend(extensions.PrintReport(
['epoch', 'iteration', 'lr',
'main/loss', 'main/loss/loc', 'main/loss/conf',
'validation/main/map']),
trigger=log_interval)
trainer.extend(extensions.ProgressBar(update_interval=10))
trainer.extend(
extensions.snapshot(),
trigger=triggers.ManualScheduleTrigger(
args.step + [args.iteration], 'iteration'))
trainer.extend(
extensions.snapshot_object(model, 'model_iter_{.updater.iteration}'),
trigger=(args.iteration, 'iteration'))
if args.resume:
serializers.load_npz(args.resume, trainer)
trainer.run()
if __name__ == '__main__':
main()
| chainer.cuda.get_device_from_id(args.gpu).use()
model.to_gpu() | conditional_block |
train.py | import argparse
import copy
import numpy as np
import chainer
from chainer.datasets import ConcatenatedDataset
from chainer.datasets import TransformDataset
from chainer.optimizer_hooks import WeightDecay
from chainer import serializers
from chainer import training
from chainer.training import extensions
from chainer.training import triggers
from chainercv.datasets import voc_bbox_label_names
from chainercv.datasets import VOCBboxDataset
from chainercv.extensions import DetectionVOCEvaluator
from chainercv.links.model.ssd import GradientScaling
from chainercv.links.model.ssd import multibox_loss
from chainercv.links import SSD300
from chainercv.links import SSD512
from chainercv import transforms
from chainercv.links.model.ssd import random_crop_with_bbox_constraints
from chainercv.links.model.ssd import random_distort
from chainercv.links.model.ssd import resize_with_random_interpolation
# https://docs.chainer.org/en/stable/tips.html#my-training-process-gets-stuck-when-using-multiprocessiterator
import cv2
cv2.setNumThreads(0)
class MultiboxTrainChain(chainer.Chain):
def __init__(self, model, alpha=1, k=3):
super(MultiboxTrainChain, self).__init__()
with self.init_scope():
self.model = model
self.alpha = alpha
self.k = k
def forward(self, imgs, gt_mb_locs, gt_mb_labels):
mb_locs, mb_confs = self.model(imgs)
loc_loss, conf_loss = multibox_loss(
mb_locs, mb_confs, gt_mb_locs, gt_mb_labels, self.k)
loss = loc_loss * self.alpha + conf_loss
chainer.reporter.report(
{'loss': loss, 'loss/loc': loc_loss, 'loss/conf': conf_loss},
self)
return loss
class Transform(object):
def __init__(self, coder, size, mean):
# to send cpu, make a copy
self.coder = copy.copy(coder)
self.coder.to_cpu()
self.size = size
self.mean = mean
def __call__(self, in_data):
# There are five data augmentation steps
# 1. Color augmentation
# 2. Random expansion
# 3. Random cropping
# 4. Resizing with random interpolation
# 5. Random horizontal flipping
img, bbox, label = in_data
# 1. Color augmentation
img = random_distort(img)
# 2. Random expansion
if np.random.randint(2):
img, param = transforms.random_expand(
img, fill=self.mean, return_param=True)
bbox = transforms.translate_bbox(
bbox, y_offset=param['y_offset'], x_offset=param['x_offset'])
# 3. Random cropping
img, param = random_crop_with_bbox_constraints(
img, bbox, return_param=True)
bbox, param = transforms.crop_bbox(
bbox, y_slice=param['y_slice'], x_slice=param['x_slice'],
allow_outside_center=False, return_param=True)
label = label[param['index']]
# 4. Resizing with random interpolatation
_, H, W = img.shape
img = resize_with_random_interpolation(img, (self.size, self.size))
bbox = transforms.resize_bbox(bbox, (H, W), (self.size, self.size))
# 5. Random horizontal flipping
img, params = transforms.random_flip(
img, x_random=True, return_param=True)
bbox = transforms.flip_bbox(
bbox, (self.size, self.size), x_flip=params['x_flip'])
# Preparation for SSD network
img -= self.mean
mb_loc, mb_label = self.coder.encode(bbox, label)
return img, mb_loc, mb_label
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--model', choices=('ssd300', 'ssd512'), default='ssd300')
parser.add_argument('--batchsize', type=int, default=32)
parser.add_argument('--iteration', type=int, default=120000)
parser.add_argument('--step', type=int, nargs='*', default=[80000, 100000])
parser.add_argument('--gpu', type=int, default=-1)
parser.add_argument('--out', default='result')
parser.add_argument('--resume') | pretrained_model='imagenet')
elif args.model == 'ssd512':
model = SSD512(
n_fg_class=len(voc_bbox_label_names),
pretrained_model='imagenet')
model.use_preset('evaluate')
train_chain = MultiboxTrainChain(model)
if args.gpu >= 0:
chainer.cuda.get_device_from_id(args.gpu).use()
model.to_gpu()
train = TransformDataset(
ConcatenatedDataset(
VOCBboxDataset(year='2007', split='trainval'),
VOCBboxDataset(year='2012', split='trainval')
),
Transform(model.coder, model.insize, model.mean))
train_iter = chainer.iterators.MultiprocessIterator(train, args.batchsize)
test = VOCBboxDataset(
year='2007', split='test',
use_difficult=True, return_difficult=True)
test_iter = chainer.iterators.SerialIterator(
test, args.batchsize, repeat=False, shuffle=False)
# initial lr is set to 1e-3 by ExponentialShift
optimizer = chainer.optimizers.MomentumSGD()
optimizer.setup(train_chain)
for param in train_chain.params():
if param.name == 'b':
param.update_rule.add_hook(GradientScaling(2))
else:
param.update_rule.add_hook(WeightDecay(0.0005))
updater = training.updaters.StandardUpdater(
train_iter, optimizer, device=args.gpu)
trainer = training.Trainer(
updater, (args.iteration, 'iteration'), args.out)
trainer.extend(
extensions.ExponentialShift('lr', 0.1, init=1e-3),
trigger=triggers.ManualScheduleTrigger(args.step, 'iteration'))
trainer.extend(
DetectionVOCEvaluator(
test_iter, model, use_07_metric=True,
label_names=voc_bbox_label_names),
trigger=triggers.ManualScheduleTrigger(
args.step + [args.iteration], 'iteration'))
log_interval = 10, 'iteration'
trainer.extend(extensions.LogReport(trigger=log_interval))
trainer.extend(extensions.observe_lr(), trigger=log_interval)
trainer.extend(extensions.PrintReport(
['epoch', 'iteration', 'lr',
'main/loss', 'main/loss/loc', 'main/loss/conf',
'validation/main/map']),
trigger=log_interval)
trainer.extend(extensions.ProgressBar(update_interval=10))
trainer.extend(
extensions.snapshot(),
trigger=triggers.ManualScheduleTrigger(
args.step + [args.iteration], 'iteration'))
trainer.extend(
extensions.snapshot_object(model, 'model_iter_{.updater.iteration}'),
trigger=(args.iteration, 'iteration'))
if args.resume:
serializers.load_npz(args.resume, trainer)
trainer.run()
if __name__ == '__main__':
main() | args = parser.parse_args()
if args.model == 'ssd300':
model = SSD300(
n_fg_class=len(voc_bbox_label_names), | random_line_split |
train.py | import argparse
import copy
import numpy as np
import chainer
from chainer.datasets import ConcatenatedDataset
from chainer.datasets import TransformDataset
from chainer.optimizer_hooks import WeightDecay
from chainer import serializers
from chainer import training
from chainer.training import extensions
from chainer.training import triggers
from chainercv.datasets import voc_bbox_label_names
from chainercv.datasets import VOCBboxDataset
from chainercv.extensions import DetectionVOCEvaluator
from chainercv.links.model.ssd import GradientScaling
from chainercv.links.model.ssd import multibox_loss
from chainercv.links import SSD300
from chainercv.links import SSD512
from chainercv import transforms
from chainercv.links.model.ssd import random_crop_with_bbox_constraints
from chainercv.links.model.ssd import random_distort
from chainercv.links.model.ssd import resize_with_random_interpolation
# https://docs.chainer.org/en/stable/tips.html#my-training-process-gets-stuck-when-using-multiprocessiterator
import cv2
cv2.setNumThreads(0)
class MultiboxTrainChain(chainer.Chain):
|
class Transform(object):
def __init__(self, coder, size, mean):
# to send cpu, make a copy
self.coder = copy.copy(coder)
self.coder.to_cpu()
self.size = size
self.mean = mean
def __call__(self, in_data):
# There are five data augmentation steps
# 1. Color augmentation
# 2. Random expansion
# 3. Random cropping
# 4. Resizing with random interpolation
# 5. Random horizontal flipping
img, bbox, label = in_data
# 1. Color augmentation
img = random_distort(img)
# 2. Random expansion
if np.random.randint(2):
img, param = transforms.random_expand(
img, fill=self.mean, return_param=True)
bbox = transforms.translate_bbox(
bbox, y_offset=param['y_offset'], x_offset=param['x_offset'])
# 3. Random cropping
img, param = random_crop_with_bbox_constraints(
img, bbox, return_param=True)
bbox, param = transforms.crop_bbox(
bbox, y_slice=param['y_slice'], x_slice=param['x_slice'],
allow_outside_center=False, return_param=True)
label = label[param['index']]
# 4. Resizing with random interpolatation
_, H, W = img.shape
img = resize_with_random_interpolation(img, (self.size, self.size))
bbox = transforms.resize_bbox(bbox, (H, W), (self.size, self.size))
# 5. Random horizontal flipping
img, params = transforms.random_flip(
img, x_random=True, return_param=True)
bbox = transforms.flip_bbox(
bbox, (self.size, self.size), x_flip=params['x_flip'])
# Preparation for SSD network
img -= self.mean
mb_loc, mb_label = self.coder.encode(bbox, label)
return img, mb_loc, mb_label
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'--model', choices=('ssd300', 'ssd512'), default='ssd300')
parser.add_argument('--batchsize', type=int, default=32)
parser.add_argument('--iteration', type=int, default=120000)
parser.add_argument('--step', type=int, nargs='*', default=[80000, 100000])
parser.add_argument('--gpu', type=int, default=-1)
parser.add_argument('--out', default='result')
parser.add_argument('--resume')
args = parser.parse_args()
if args.model == 'ssd300':
model = SSD300(
n_fg_class=len(voc_bbox_label_names),
pretrained_model='imagenet')
elif args.model == 'ssd512':
model = SSD512(
n_fg_class=len(voc_bbox_label_names),
pretrained_model='imagenet')
model.use_preset('evaluate')
train_chain = MultiboxTrainChain(model)
if args.gpu >= 0:
chainer.cuda.get_device_from_id(args.gpu).use()
model.to_gpu()
train = TransformDataset(
ConcatenatedDataset(
VOCBboxDataset(year='2007', split='trainval'),
VOCBboxDataset(year='2012', split='trainval')
),
Transform(model.coder, model.insize, model.mean))
train_iter = chainer.iterators.MultiprocessIterator(train, args.batchsize)
test = VOCBboxDataset(
year='2007', split='test',
use_difficult=True, return_difficult=True)
test_iter = chainer.iterators.SerialIterator(
test, args.batchsize, repeat=False, shuffle=False)
# initial lr is set to 1e-3 by ExponentialShift
optimizer = chainer.optimizers.MomentumSGD()
optimizer.setup(train_chain)
for param in train_chain.params():
if param.name == 'b':
param.update_rule.add_hook(GradientScaling(2))
else:
param.update_rule.add_hook(WeightDecay(0.0005))
updater = training.updaters.StandardUpdater(
train_iter, optimizer, device=args.gpu)
trainer = training.Trainer(
updater, (args.iteration, 'iteration'), args.out)
trainer.extend(
extensions.ExponentialShift('lr', 0.1, init=1e-3),
trigger=triggers.ManualScheduleTrigger(args.step, 'iteration'))
trainer.extend(
DetectionVOCEvaluator(
test_iter, model, use_07_metric=True,
label_names=voc_bbox_label_names),
trigger=triggers.ManualScheduleTrigger(
args.step + [args.iteration], 'iteration'))
log_interval = 10, 'iteration'
trainer.extend(extensions.LogReport(trigger=log_interval))
trainer.extend(extensions.observe_lr(), trigger=log_interval)
trainer.extend(extensions.PrintReport(
['epoch', 'iteration', 'lr',
'main/loss', 'main/loss/loc', 'main/loss/conf',
'validation/main/map']),
trigger=log_interval)
trainer.extend(extensions.ProgressBar(update_interval=10))
trainer.extend(
extensions.snapshot(),
trigger=triggers.ManualScheduleTrigger(
args.step + [args.iteration], 'iteration'))
trainer.extend(
extensions.snapshot_object(model, 'model_iter_{.updater.iteration}'),
trigger=(args.iteration, 'iteration'))
if args.resume:
serializers.load_npz(args.resume, trainer)
trainer.run()
if __name__ == '__main__':
main()
| def __init__(self, model, alpha=1, k=3):
super(MultiboxTrainChain, self).__init__()
with self.init_scope():
self.model = model
self.alpha = alpha
self.k = k
def forward(self, imgs, gt_mb_locs, gt_mb_labels):
mb_locs, mb_confs = self.model(imgs)
loc_loss, conf_loss = multibox_loss(
mb_locs, mb_confs, gt_mb_locs, gt_mb_labels, self.k)
loss = loc_loss * self.alpha + conf_loss
chainer.reporter.report(
{'loss': loss, 'loss/loc': loc_loss, 'loss/conf': conf_loss},
self)
return loss | identifier_body |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib::network::protocol::socket_cleanup;
use pueue_lib::network::secret::init_shared_secret;
use pueue_lib::settings::Settings;
use pueue_lib::state::State;
use self::state_helper::{restore_state, save_state};
use crate::network::socket::accept_incoming;
use crate::task_handler::TaskHandler;
pub mod cli;
mod network;
mod pid;
mod platform;
/// Contains re-usable helper functions, that operate on the pueue-lib state.
pub mod state_helper;
mod task_handler;
/// The main entry point for the daemon logic.
/// It's basically the `main`, but publicly exported as a library.
/// That way we can properly do integration testing for the daemon.
///
/// For the purpose of testing, some things shouldn't be run during tests.
/// There are some global operations that crash during tests, such as the ctlc handler.
/// This is due to the fact, that tests in the same file are executed in multiple threads.
/// Since the threads own the same global space, this would crash.
pub async fn run(config_path: Option<PathBuf>, profile: Option<String>, test: bool) -> Result<()> {
// Try to read settings from the configuration file.
let (mut settings, config_found) = Settings::read(&config_path)?;
// We couldn't find a configuration file.
// This probably means that Pueue has been started for the first time and we have to create a
// default config file once.
if !config_found {
if let Err(error) = settings.save(&config_path) {
bail!("Failed saving config file: {error:?}.");
}
};
// Load any requested profile.
if let Some(profile) = &profile {
settings.load_profile(profile)?;
}
#[allow(deprecated)]
if settings.daemon.groups.is_some() {
error!(
"Please delete the 'daemon.groups' section from your config file. \n\
It is no longer used and groups can now only be edited via the commandline interface. \n\n\
Attention: The first time the daemon is restarted this update, the amount of parallel tasks per group will be reset to 1!!"
)
}
init_directories(&settings.shared.pueue_directory());
if !settings.shared.daemon_key().exists() && !settings.shared.daemon_cert().exists() {
create_certificates(&settings.shared)?;
}
init_shared_secret(&settings.shared.shared_secret_path())?;
pid::create_pid_file(&settings.shared.pueue_directory())?;
// Restore the previous state and save any changes that might have happened during this
// process. If no previous state exists, just create a new one.
// Create a new empty state if any errors occur, but print the error message.
let mut state = match restore_state(&settings.shared.pueue_directory()) {
Ok(Some(state)) => state,
Ok(None) => State::new(&settings, config_path.clone()),
Err(error) => {
warn!("Failed to restore previous state:\n {error:?}");
warn!("Using clean state instead.");
State::new(&settings, config_path.clone())
}
};
state.settings = settings.clone();
save_state(&state)?;
let state = Arc::new(Mutex::new(state));
let (sender, receiver) = unbounded();
let mut task_handler = TaskHandler::new(state.clone(), receiver);
// Don't set ctrlc and panic handlers during testing.
// This is necessary for multithreaded integration testing, since multiple listener per process
// aren't prophibited. On top of this, ctrlc also somehow breaks test error output.
if !test |
std::thread::spawn(move || {
task_handler.run();
});
accept_incoming(sender, state.clone()).await?;
Ok(())
}
/// Initialize all directories needed for normal operation.
fn init_directories(pueue_dir: &Path) {
// Pueue base path
if !pueue_dir.exists() {
if let Err(error) = create_dir_all(&pueue_dir) {
panic!("Failed to create main directory at {pueue_dir:?} error: {error:?}");
}
}
// Task log dir
let log_dir = pueue_dir.join("log");
if !log_dir.exists() {
if let Err(error) = create_dir_all(&log_dir) {
panic!("Failed to create log directory at {log_dir:?} error: {error:?}",);
}
}
// Task certs dir
let certs_dir = pueue_dir.join("certs");
if !certs_dir.exists() {
if let Err(error) = create_dir_all(&certs_dir) {
panic!("Failed to create certificate directory at {certs_dir:?} error: {error:?}");
}
}
// Task log dir
let logs_dir = pueue_dir.join("task_logs");
if !logs_dir.exists() {
if let Err(error) = create_dir_all(&logs_dir) {
panic!("Failed to create task logs directory at {logs_dir:?} error: {error:?}");
}
}
}
/// Setup signal handling and panic handling.
///
/// On SIGINT and SIGTERM, we exit gracefully by sending a DaemonShutdown message to the
/// TaskHandler. This is to prevent dangling processes and other weird edge-cases.
///
/// On panic, we want to cleanup existing unix sockets and the PID file.
fn setup_signal_panic_handling(settings: &Settings, sender: &Sender<Message>) -> Result<()> {
let sender_clone = sender.clone();
// This section handles Shutdown via SigTerm/SigInt process signals
// Notify the TaskHandler, so it can shutdown gracefully.
// The actual program exit will be done via the TaskHandler.
ctrlc::set_handler(move || {
// Notify the task handler
sender_clone
.send(Message::DaemonShutdown(Shutdown::Emergency))
.expect("Failed to send Message to TaskHandler on Shutdown");
})?;
// Try to do some final cleanup, even if we panic.
let settings_clone = settings.clone();
let orig_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
// invoke the default handler and exit the process
orig_hook(panic_info);
// Cleanup the pid file
if let Err(error) = pid::cleanup_pid_file(&settings_clone.shared.pueue_directory()) {
println!("Failed to cleanup pid after panic.");
println!("{error}");
}
// Remove the unix socket.
if let Err(error) = socket_cleanup(&settings_clone.shared) {
println!("Failed to cleanup socket after panic.");
println!("{error}");
}
std::process::exit(1);
}));
Ok(())
}
| {
setup_signal_panic_handling(&settings, &sender)?;
} | conditional_block |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib::network::protocol::socket_cleanup;
use pueue_lib::network::secret::init_shared_secret;
use pueue_lib::settings::Settings;
use pueue_lib::state::State;
use self::state_helper::{restore_state, save_state};
use crate::network::socket::accept_incoming;
use crate::task_handler::TaskHandler;
pub mod cli;
mod network;
mod pid;
mod platform;
/// Contains re-usable helper functions, that operate on the pueue-lib state.
pub mod state_helper;
mod task_handler;
/// The main entry point for the daemon logic.
/// It's basically the `main`, but publicly exported as a library.
/// That way we can properly do integration testing for the daemon.
///
/// For the purpose of testing, some things shouldn't be run during tests.
/// There are some global operations that crash during tests, such as the ctlc handler.
/// This is due to the fact, that tests in the same file are executed in multiple threads.
/// Since the threads own the same global space, this would crash.
pub async fn run(config_path: Option<PathBuf>, profile: Option<String>, test: bool) -> Result<()> {
// Try to read settings from the configuration file.
let (mut settings, config_found) = Settings::read(&config_path)?;
// We couldn't find a configuration file.
// This probably means that Pueue has been started for the first time and we have to create a
// default config file once.
if !config_found {
if let Err(error) = settings.save(&config_path) {
bail!("Failed saving config file: {error:?}.");
}
};
// Load any requested profile.
if let Some(profile) = &profile {
settings.load_profile(profile)?;
}
#[allow(deprecated)]
if settings.daemon.groups.is_some() {
error!(
"Please delete the 'daemon.groups' section from your config file. \n\
It is no longer used and groups can now only be edited via the commandline interface. \n\n\
Attention: The first time the daemon is restarted this update, the amount of parallel tasks per group will be reset to 1!!"
)
}
init_directories(&settings.shared.pueue_directory());
if !settings.shared.daemon_key().exists() && !settings.shared.daemon_cert().exists() {
create_certificates(&settings.shared)?;
}
init_shared_secret(&settings.shared.shared_secret_path())?;
pid::create_pid_file(&settings.shared.pueue_directory())?;
// Restore the previous state and save any changes that might have happened during this
// process. If no previous state exists, just create a new one.
// Create a new empty state if any errors occur, but print the error message.
let mut state = match restore_state(&settings.shared.pueue_directory()) {
Ok(Some(state)) => state,
Ok(None) => State::new(&settings, config_path.clone()),
Err(error) => {
warn!("Failed to restore previous state:\n {error:?}");
warn!("Using clean state instead.");
State::new(&settings, config_path.clone())
}
};
state.settings = settings.clone();
save_state(&state)?;
let state = Arc::new(Mutex::new(state));
let (sender, receiver) = unbounded();
let mut task_handler = TaskHandler::new(state.clone(), receiver);
| }
std::thread::spawn(move || {
task_handler.run();
});
accept_incoming(sender, state.clone()).await?;
Ok(())
}
/// Initialize all directories needed for normal operation.
fn init_directories(pueue_dir: &Path) {
// Pueue base path
if !pueue_dir.exists() {
if let Err(error) = create_dir_all(&pueue_dir) {
panic!("Failed to create main directory at {pueue_dir:?} error: {error:?}");
}
}
// Task log dir
let log_dir = pueue_dir.join("log");
if !log_dir.exists() {
if let Err(error) = create_dir_all(&log_dir) {
panic!("Failed to create log directory at {log_dir:?} error: {error:?}",);
}
}
// Task certs dir
let certs_dir = pueue_dir.join("certs");
if !certs_dir.exists() {
if let Err(error) = create_dir_all(&certs_dir) {
panic!("Failed to create certificate directory at {certs_dir:?} error: {error:?}");
}
}
// Task log dir
let logs_dir = pueue_dir.join("task_logs");
if !logs_dir.exists() {
if let Err(error) = create_dir_all(&logs_dir) {
panic!("Failed to create task logs directory at {logs_dir:?} error: {error:?}");
}
}
}
/// Setup signal handling and panic handling.
///
/// On SIGINT and SIGTERM, we exit gracefully by sending a DaemonShutdown message to the
/// TaskHandler. This is to prevent dangling processes and other weird edge-cases.
///
/// On panic, we want to cleanup existing unix sockets and the PID file.
fn setup_signal_panic_handling(settings: &Settings, sender: &Sender<Message>) -> Result<()> {
let sender_clone = sender.clone();
// This section handles Shutdown via SigTerm/SigInt process signals
// Notify the TaskHandler, so it can shutdown gracefully.
// The actual program exit will be done via the TaskHandler.
ctrlc::set_handler(move || {
// Notify the task handler
sender_clone
.send(Message::DaemonShutdown(Shutdown::Emergency))
.expect("Failed to send Message to TaskHandler on Shutdown");
})?;
// Try to do some final cleanup, even if we panic.
let settings_clone = settings.clone();
let orig_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
// invoke the default handler and exit the process
orig_hook(panic_info);
// Cleanup the pid file
if let Err(error) = pid::cleanup_pid_file(&settings_clone.shared.pueue_directory()) {
println!("Failed to cleanup pid after panic.");
println!("{error}");
}
// Remove the unix socket.
if let Err(error) = socket_cleanup(&settings_clone.shared) {
println!("Failed to cleanup socket after panic.");
println!("{error}");
}
std::process::exit(1);
}));
Ok(())
} | // Don't set ctrlc and panic handlers during testing.
// This is necessary for multithreaded integration testing, since multiple listener per process
// aren't prophibited. On top of this, ctrlc also somehow breaks test error output.
if !test {
setup_signal_panic_handling(&settings, &sender)?; | random_line_split |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib::network::protocol::socket_cleanup;
use pueue_lib::network::secret::init_shared_secret;
use pueue_lib::settings::Settings;
use pueue_lib::state::State;
use self::state_helper::{restore_state, save_state};
use crate::network::socket::accept_incoming;
use crate::task_handler::TaskHandler;
pub mod cli;
mod network;
mod pid;
mod platform;
/// Contains re-usable helper functions, that operate on the pueue-lib state.
pub mod state_helper;
mod task_handler;
/// The main entry point for the daemon logic.
/// It's basically the `main`, but publicly exported as a library.
/// That way we can properly do integration testing for the daemon.
///
/// For the purpose of testing, some things shouldn't be run during tests.
/// There are some global operations that crash during tests, such as the ctlc handler.
/// This is due to the fact, that tests in the same file are executed in multiple threads.
/// Since the threads own the same global space, this would crash.
pub async fn | (config_path: Option<PathBuf>, profile: Option<String>, test: bool) -> Result<()> {
// Try to read settings from the configuration file.
let (mut settings, config_found) = Settings::read(&config_path)?;
// We couldn't find a configuration file.
// This probably means that Pueue has been started for the first time and we have to create a
// default config file once.
if !config_found {
if let Err(error) = settings.save(&config_path) {
bail!("Failed saving config file: {error:?}.");
}
};
// Load any requested profile.
if let Some(profile) = &profile {
settings.load_profile(profile)?;
}
#[allow(deprecated)]
if settings.daemon.groups.is_some() {
error!(
"Please delete the 'daemon.groups' section from your config file. \n\
It is no longer used and groups can now only be edited via the commandline interface. \n\n\
Attention: The first time the daemon is restarted this update, the amount of parallel tasks per group will be reset to 1!!"
)
}
init_directories(&settings.shared.pueue_directory());
if !settings.shared.daemon_key().exists() && !settings.shared.daemon_cert().exists() {
create_certificates(&settings.shared)?;
}
init_shared_secret(&settings.shared.shared_secret_path())?;
pid::create_pid_file(&settings.shared.pueue_directory())?;
// Restore the previous state and save any changes that might have happened during this
// process. If no previous state exists, just create a new one.
// Create a new empty state if any errors occur, but print the error message.
let mut state = match restore_state(&settings.shared.pueue_directory()) {
Ok(Some(state)) => state,
Ok(None) => State::new(&settings, config_path.clone()),
Err(error) => {
warn!("Failed to restore previous state:\n {error:?}");
warn!("Using clean state instead.");
State::new(&settings, config_path.clone())
}
};
state.settings = settings.clone();
save_state(&state)?;
let state = Arc::new(Mutex::new(state));
let (sender, receiver) = unbounded();
let mut task_handler = TaskHandler::new(state.clone(), receiver);
// Don't set ctrlc and panic handlers during testing.
// This is necessary for multithreaded integration testing, since multiple listener per process
// aren't prophibited. On top of this, ctrlc also somehow breaks test error output.
if !test {
setup_signal_panic_handling(&settings, &sender)?;
}
std::thread::spawn(move || {
task_handler.run();
});
accept_incoming(sender, state.clone()).await?;
Ok(())
}
/// Initialize all directories needed for normal operation.
fn init_directories(pueue_dir: &Path) {
// Pueue base path
if !pueue_dir.exists() {
if let Err(error) = create_dir_all(&pueue_dir) {
panic!("Failed to create main directory at {pueue_dir:?} error: {error:?}");
}
}
// Task log dir
let log_dir = pueue_dir.join("log");
if !log_dir.exists() {
if let Err(error) = create_dir_all(&log_dir) {
panic!("Failed to create log directory at {log_dir:?} error: {error:?}",);
}
}
// Task certs dir
let certs_dir = pueue_dir.join("certs");
if !certs_dir.exists() {
if let Err(error) = create_dir_all(&certs_dir) {
panic!("Failed to create certificate directory at {certs_dir:?} error: {error:?}");
}
}
// Task log dir
let logs_dir = pueue_dir.join("task_logs");
if !logs_dir.exists() {
if let Err(error) = create_dir_all(&logs_dir) {
panic!("Failed to create task logs directory at {logs_dir:?} error: {error:?}");
}
}
}
/// Setup signal handling and panic handling.
///
/// On SIGINT and SIGTERM, we exit gracefully by sending a DaemonShutdown message to the
/// TaskHandler. This is to prevent dangling processes and other weird edge-cases.
///
/// On panic, we want to cleanup existing unix sockets and the PID file.
fn setup_signal_panic_handling(settings: &Settings, sender: &Sender<Message>) -> Result<()> {
let sender_clone = sender.clone();
// This section handles Shutdown via SigTerm/SigInt process signals
// Notify the TaskHandler, so it can shutdown gracefully.
// The actual program exit will be done via the TaskHandler.
ctrlc::set_handler(move || {
// Notify the task handler
sender_clone
.send(Message::DaemonShutdown(Shutdown::Emergency))
.expect("Failed to send Message to TaskHandler on Shutdown");
})?;
// Try to do some final cleanup, even if we panic.
let settings_clone = settings.clone();
let orig_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
// invoke the default handler and exit the process
orig_hook(panic_info);
// Cleanup the pid file
if let Err(error) = pid::cleanup_pid_file(&settings_clone.shared.pueue_directory()) {
println!("Failed to cleanup pid after panic.");
println!("{error}");
}
// Remove the unix socket.
if let Err(error) = socket_cleanup(&settings_clone.shared) {
println!("Failed to cleanup socket after panic.");
println!("{error}");
}
std::process::exit(1);
}));
Ok(())
}
| run | identifier_name |
lib.rs | use std::path::Path;
use std::sync::{Arc, Mutex};
use std::{fs::create_dir_all, path::PathBuf};
use anyhow::{bail, Result};
use crossbeam_channel::{unbounded, Sender};
use log::{error, warn};
use pueue_lib::network::certificate::create_certificates;
use pueue_lib::network::message::{Message, Shutdown};
use pueue_lib::network::protocol::socket_cleanup;
use pueue_lib::network::secret::init_shared_secret;
use pueue_lib::settings::Settings;
use pueue_lib::state::State;
use self::state_helper::{restore_state, save_state};
use crate::network::socket::accept_incoming;
use crate::task_handler::TaskHandler;
pub mod cli;
mod network;
mod pid;
mod platform;
/// Contains re-usable helper functions, that operate on the pueue-lib state.
pub mod state_helper;
mod task_handler;
/// The main entry point for the daemon logic.
/// It's basically the `main`, but publicly exported as a library.
/// That way we can properly do integration testing for the daemon.
///
/// For the purpose of testing, some things shouldn't be run during tests.
/// There are some global operations that crash during tests, such as the ctlc handler.
/// This is due to the fact, that tests in the same file are executed in multiple threads.
/// Since the threads own the same global space, this would crash.
pub async fn run(config_path: Option<PathBuf>, profile: Option<String>, test: bool) -> Result<()> {
// Try to read settings from the configuration file.
let (mut settings, config_found) = Settings::read(&config_path)?;
// We couldn't find a configuration file.
// This probably means that Pueue has been started for the first time and we have to create a
// default config file once.
if !config_found {
if let Err(error) = settings.save(&config_path) {
bail!("Failed saving config file: {error:?}.");
}
};
// Load any requested profile.
if let Some(profile) = &profile {
settings.load_profile(profile)?;
}
#[allow(deprecated)]
if settings.daemon.groups.is_some() {
error!(
"Please delete the 'daemon.groups' section from your config file. \n\
It is no longer used and groups can now only be edited via the commandline interface. \n\n\
Attention: The first time the daemon is restarted this update, the amount of parallel tasks per group will be reset to 1!!"
)
}
init_directories(&settings.shared.pueue_directory());
if !settings.shared.daemon_key().exists() && !settings.shared.daemon_cert().exists() {
create_certificates(&settings.shared)?;
}
init_shared_secret(&settings.shared.shared_secret_path())?;
pid::create_pid_file(&settings.shared.pueue_directory())?;
// Restore the previous state and save any changes that might have happened during this
// process. If no previous state exists, just create a new one.
// Create a new empty state if any errors occur, but print the error message.
let mut state = match restore_state(&settings.shared.pueue_directory()) {
Ok(Some(state)) => state,
Ok(None) => State::new(&settings, config_path.clone()),
Err(error) => {
warn!("Failed to restore previous state:\n {error:?}");
warn!("Using clean state instead.");
State::new(&settings, config_path.clone())
}
};
state.settings = settings.clone();
save_state(&state)?;
let state = Arc::new(Mutex::new(state));
let (sender, receiver) = unbounded();
let mut task_handler = TaskHandler::new(state.clone(), receiver);
// Don't set ctrlc and panic handlers during testing.
// This is necessary for multithreaded integration testing, since multiple listener per process
// aren't prophibited. On top of this, ctrlc also somehow breaks test error output.
if !test {
setup_signal_panic_handling(&settings, &sender)?;
}
std::thread::spawn(move || {
task_handler.run();
});
accept_incoming(sender, state.clone()).await?;
Ok(())
}
/// Initialize all directories needed for normal operation.
fn init_directories(pueue_dir: &Path) {
// Pueue base path
if !pueue_dir.exists() {
if let Err(error) = create_dir_all(&pueue_dir) {
panic!("Failed to create main directory at {pueue_dir:?} error: {error:?}");
}
}
// Task log dir
let log_dir = pueue_dir.join("log");
if !log_dir.exists() {
if let Err(error) = create_dir_all(&log_dir) {
panic!("Failed to create log directory at {log_dir:?} error: {error:?}",);
}
}
// Task certs dir
let certs_dir = pueue_dir.join("certs");
if !certs_dir.exists() {
if let Err(error) = create_dir_all(&certs_dir) {
panic!("Failed to create certificate directory at {certs_dir:?} error: {error:?}");
}
}
// Task log dir
let logs_dir = pueue_dir.join("task_logs");
if !logs_dir.exists() {
if let Err(error) = create_dir_all(&logs_dir) {
panic!("Failed to create task logs directory at {logs_dir:?} error: {error:?}");
}
}
}
/// Setup signal handling and panic handling.
///
/// On SIGINT and SIGTERM, we exit gracefully by sending a DaemonShutdown message to the
/// TaskHandler. This is to prevent dangling processes and other weird edge-cases.
///
/// On panic, we want to cleanup existing unix sockets and the PID file.
fn setup_signal_panic_handling(settings: &Settings, sender: &Sender<Message>) -> Result<()> | {
let sender_clone = sender.clone();
// This section handles Shutdown via SigTerm/SigInt process signals
// Notify the TaskHandler, so it can shutdown gracefully.
// The actual program exit will be done via the TaskHandler.
ctrlc::set_handler(move || {
// Notify the task handler
sender_clone
.send(Message::DaemonShutdown(Shutdown::Emergency))
.expect("Failed to send Message to TaskHandler on Shutdown");
})?;
// Try to do some final cleanup, even if we panic.
let settings_clone = settings.clone();
let orig_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
// invoke the default handler and exit the process
orig_hook(panic_info);
// Cleanup the pid file
if let Err(error) = pid::cleanup_pid_file(&settings_clone.shared.pueue_directory()) {
println!("Failed to cleanup pid after panic.");
println!("{error}");
}
// Remove the unix socket.
if let Err(error) = socket_cleanup(&settings_clone.shared) {
println!("Failed to cleanup socket after panic.");
println!("{error}");
}
std::process::exit(1);
}));
Ok(())
} | identifier_body | |
rankings_helper.py | from typing import List, Optional
from backend.common.consts.ranking_sort_orders import SORT_ORDER_INFO
from backend.common.models.event_details import EventDetails
from backend.common.models.event_ranking import EventRanking
from backend.common.models.event_team_status import WLTRecord
from backend.common.models.keys import TeamKey, Year
from backend.common.models.ranking_sort_order_info import RankingSortOrderInfo
class RankingsHelper:
NO_RECORD_YEARS = {2010, 2015, 2021}
QUAL_AVERAGE_YEARS = {2015}
@classmethod
def build_ranking(
cls,
year: Year,
rank: int,
team_key: TeamKey,
wins: int,
losses: int,
ties: int,
qual_average: Optional[float],
matches_played: int,
dq: int,
sort_orders: List[float],
) -> EventRanking:
record: Optional[WLTRecord] = None
if year not in cls.NO_RECORD_YEARS:
record = {
"wins": int(wins),
"losses": int(losses),
"ties": int(ties),
} |
if year not in cls.QUAL_AVERAGE_YEARS:
qual_average = None
sort_orders_sanitized = []
for so in sort_orders:
try:
sort_orders_sanitized.append(float(so))
except Exception:
sort_orders_sanitized.append(0.0)
return {
"rank": int(rank),
"team_key": team_key,
"record": record, # None if record doesn't affect rank (e.g. 2010, 2015)
"qual_average": qual_average, # None if qual_average doesn't affect rank (all years except 2015)
"matches_played": int(matches_played),
"dq": int(dq),
"sort_orders": sort_orders_sanitized,
}
@classmethod
def get_sort_order_info(
cls, event_details: EventDetails
) -> Optional[List[RankingSortOrderInfo]]:
return SORT_ORDER_INFO.get(event_details.game_year) | random_line_split | |
rankings_helper.py | from typing import List, Optional
from backend.common.consts.ranking_sort_orders import SORT_ORDER_INFO
from backend.common.models.event_details import EventDetails
from backend.common.models.event_ranking import EventRanking
from backend.common.models.event_team_status import WLTRecord
from backend.common.models.keys import TeamKey, Year
from backend.common.models.ranking_sort_order_info import RankingSortOrderInfo
class RankingsHelper:
NO_RECORD_YEARS = {2010, 2015, 2021}
QUAL_AVERAGE_YEARS = {2015}
@classmethod
def build_ranking(
cls,
year: Year,
rank: int,
team_key: TeamKey,
wins: int,
losses: int,
ties: int,
qual_average: Optional[float],
matches_played: int,
dq: int,
sort_orders: List[float],
) -> EventRanking:
record: Optional[WLTRecord] = None
if year not in cls.NO_RECORD_YEARS:
record = {
"wins": int(wins),
"losses": int(losses),
"ties": int(ties),
}
if year not in cls.QUAL_AVERAGE_YEARS:
|
sort_orders_sanitized = []
for so in sort_orders:
try:
sort_orders_sanitized.append(float(so))
except Exception:
sort_orders_sanitized.append(0.0)
return {
"rank": int(rank),
"team_key": team_key,
"record": record, # None if record doesn't affect rank (e.g. 2010, 2015)
"qual_average": qual_average, # None if qual_average doesn't affect rank (all years except 2015)
"matches_played": int(matches_played),
"dq": int(dq),
"sort_orders": sort_orders_sanitized,
}
@classmethod
def get_sort_order_info(
cls, event_details: EventDetails
) -> Optional[List[RankingSortOrderInfo]]:
return SORT_ORDER_INFO.get(event_details.game_year)
| qual_average = None | conditional_block |
rankings_helper.py | from typing import List, Optional
from backend.common.consts.ranking_sort_orders import SORT_ORDER_INFO
from backend.common.models.event_details import EventDetails
from backend.common.models.event_ranking import EventRanking
from backend.common.models.event_team_status import WLTRecord
from backend.common.models.keys import TeamKey, Year
from backend.common.models.ranking_sort_order_info import RankingSortOrderInfo
class RankingsHelper:
NO_RECORD_YEARS = {2010, 2015, 2021}
QUAL_AVERAGE_YEARS = {2015}
@classmethod
def build_ranking(
cls,
year: Year,
rank: int,
team_key: TeamKey,
wins: int,
losses: int,
ties: int,
qual_average: Optional[float],
matches_played: int,
dq: int,
sort_orders: List[float],
) -> EventRanking:
record: Optional[WLTRecord] = None
if year not in cls.NO_RECORD_YEARS:
record = {
"wins": int(wins),
"losses": int(losses),
"ties": int(ties),
}
if year not in cls.QUAL_AVERAGE_YEARS:
qual_average = None
sort_orders_sanitized = []
for so in sort_orders:
try:
sort_orders_sanitized.append(float(so))
except Exception:
sort_orders_sanitized.append(0.0)
return {
"rank": int(rank),
"team_key": team_key,
"record": record, # None if record doesn't affect rank (e.g. 2010, 2015)
"qual_average": qual_average, # None if qual_average doesn't affect rank (all years except 2015)
"matches_played": int(matches_played),
"dq": int(dq),
"sort_orders": sort_orders_sanitized,
}
@classmethod
def | (
cls, event_details: EventDetails
) -> Optional[List[RankingSortOrderInfo]]:
return SORT_ORDER_INFO.get(event_details.game_year)
| get_sort_order_info | identifier_name |
rankings_helper.py | from typing import List, Optional
from backend.common.consts.ranking_sort_orders import SORT_ORDER_INFO
from backend.common.models.event_details import EventDetails
from backend.common.models.event_ranking import EventRanking
from backend.common.models.event_team_status import WLTRecord
from backend.common.models.keys import TeamKey, Year
from backend.common.models.ranking_sort_order_info import RankingSortOrderInfo
class RankingsHelper:
NO_RECORD_YEARS = {2010, 2015, 2021}
QUAL_AVERAGE_YEARS = {2015}
@classmethod
def build_ranking(
cls,
year: Year,
rank: int,
team_key: TeamKey,
wins: int,
losses: int,
ties: int,
qual_average: Optional[float],
matches_played: int,
dq: int,
sort_orders: List[float],
) -> EventRanking:
record: Optional[WLTRecord] = None
if year not in cls.NO_RECORD_YEARS:
record = {
"wins": int(wins),
"losses": int(losses),
"ties": int(ties),
}
if year not in cls.QUAL_AVERAGE_YEARS:
qual_average = None
sort_orders_sanitized = []
for so in sort_orders:
try:
sort_orders_sanitized.append(float(so))
except Exception:
sort_orders_sanitized.append(0.0)
return {
"rank": int(rank),
"team_key": team_key,
"record": record, # None if record doesn't affect rank (e.g. 2010, 2015)
"qual_average": qual_average, # None if qual_average doesn't affect rank (all years except 2015)
"matches_played": int(matches_played),
"dq": int(dq),
"sort_orders": sort_orders_sanitized,
}
@classmethod
def get_sort_order_info(
cls, event_details: EventDetails
) -> Optional[List[RankingSortOrderInfo]]:
| return SORT_ORDER_INFO.get(event_details.game_year) | identifier_body | |
assert.js | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import { ExtendableError } from './errors';
var ErrorConditionFailed = function (_ExtendableError) {
_inherits(ErrorConditionFailed, _ExtendableError);
function ErrorConditionFailed() {
_classCallCheck(this, ErrorConditionFailed);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _possibleConstructorReturn(this, _ExtendableError.call(this, args));
}
return ErrorConditionFailed;
}(ExtendableError);
export function | (condition) {
var msg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'pre-condition failed';
if (!condition) {
throw new ErrorConditionFailed(msg);
}
} | require_condition | identifier_name |
assert.js | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import { ExtendableError } from './errors';
var ErrorConditionFailed = function (_ExtendableError) {
_inherits(ErrorConditionFailed, _ExtendableError);
function ErrorConditionFailed() {
_classCallCheck(this, ErrorConditionFailed);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _possibleConstructorReturn(this, _ExtendableError.call(this, args));
}
return ErrorConditionFailed;
}(ExtendableError);
export function require_condition(condition) {
var msg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'pre-condition failed';
if (!condition) |
} | {
throw new ErrorConditionFailed(msg);
} | conditional_block |
assert.js | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import { ExtendableError } from './errors';
var ErrorConditionFailed = function (_ExtendableError) {
_inherits(ErrorConditionFailed, _ExtendableError);
function ErrorConditionFailed() |
return ErrorConditionFailed;
}(ExtendableError);
export function require_condition(condition) {
var msg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'pre-condition failed';
if (!condition) {
throw new ErrorConditionFailed(msg);
}
} | {
_classCallCheck(this, ErrorConditionFailed);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _possibleConstructorReturn(this, _ExtendableError.call(this, args));
} | identifier_body |
assert.js | import _inherits from 'babel-runtime/helpers/inherits';
import { ExtendableError } from './errors';
var ErrorConditionFailed = function (_ExtendableError) {
_inherits(ErrorConditionFailed, _ExtendableError);
function ErrorConditionFailed() {
_classCallCheck(this, ErrorConditionFailed);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _possibleConstructorReturn(this, _ExtendableError.call(this, args));
}
return ErrorConditionFailed;
}(ExtendableError);
export function require_condition(condition) {
var msg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'pre-condition failed';
if (!condition) {
throw new ErrorConditionFailed(msg);
}
} | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; | random_line_split | |
0002_contact_project_socialsite.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-13 18:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('myblog', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('message_from_me', models.TextField()),
('subject', models.CharField(max_length=33)),
('message_from_user', models.TextField()),
],
),
migrations.CreateModel(
name='Project',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('link', models.URLField()),
('image', models.ImageField(default=None, upload_to='myblog/image/project')),
('detail', models.TextField()),
('created_on', models.DateTimeField()),
],
),
migrations.CreateModel(
name='SocialSite',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('site_name', models.CharField(max_length=10)),
('link', models.URLField()),
],
options={
'verbose_name_plural': 'Social Sites',
},
),
] | identifier_body | |
0002_contact_project_socialsite.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-13 18:19
from __future__ import unicode_literals
from django.db import migrations, models
class | (migrations.Migration):
dependencies = [
('myblog', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('message_from_me', models.TextField()),
('subject', models.CharField(max_length=33)),
('message_from_user', models.TextField()),
],
),
migrations.CreateModel(
name='Project',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('link', models.URLField()),
('image', models.ImageField(default=None, upload_to='myblog/image/project')),
('detail', models.TextField()),
('created_on', models.DateTimeField()),
],
),
migrations.CreateModel(
name='SocialSite',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('site_name', models.CharField(max_length=10)),
('link', models.URLField()),
],
options={
'verbose_name_plural': 'Social Sites',
},
),
]
| Migration | identifier_name |
0002_contact_project_socialsite.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-13 18:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myblog', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Contact',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('message_from_me', models.TextField()),
('subject', models.CharField(max_length=33)),
('message_from_user', models.TextField()),
],
), | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('link', models.URLField()),
('image', models.ImageField(default=None, upload_to='myblog/image/project')),
('detail', models.TextField()),
('created_on', models.DateTimeField()),
],
),
migrations.CreateModel(
name='SocialSite',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('site_name', models.CharField(max_length=10)),
('link', models.URLField()),
],
options={
'verbose_name_plural': 'Social Sites',
},
),
] | migrations.CreateModel(
name='Project',
fields=[ | random_line_split |
role.upgrader.js | const { collectResource } = require('utils'),
role = {
/** @param {Creep} creep **/
run: function(creep) {
// If the sign is unclaimed or not claimed by me
if(!creep.room.controller.sign || creep.room.controller.sign.username != creep.owner.username) {
if(creep.signController(creep.room.controller, "I'm claiming the objective") == ERR_NOT_IN_RANGE) {
creep.doMove(creep.room.controller, {visualizePathStyle: {stroke: '#ccffcc'}});
}
}
if(creep.memory.upgrading && creep.carry.energy == 0) {
creep.memory.upgrading = false;
}
if(!creep.memory.upgrading && creep.carry.energy == creep.carryCapacity) {
creep.memory.upgrading = true;
}
if(creep.memory.upgrading) |
else {
collectResource(creep);
}
},
doUpgrade: function(creep) {
if(creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
creep.doMove(creep.room.controller, {visualizePathStyle: {stroke: '#ffffff'}});
}
}
};
module.exports = role;
| {
role.doUpgrade(creep);
} | conditional_block |
role.upgrader.js | const { collectResource } = require('utils'),
role = {
/** @param {Creep} creep **/
run: function(creep) { | }
}
if(creep.memory.upgrading && creep.carry.energy == 0) {
creep.memory.upgrading = false;
}
if(!creep.memory.upgrading && creep.carry.energy == creep.carryCapacity) {
creep.memory.upgrading = true;
}
if(creep.memory.upgrading) {
role.doUpgrade(creep);
}
else {
collectResource(creep);
}
},
doUpgrade: function(creep) {
if(creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
creep.doMove(creep.room.controller, {visualizePathStyle: {stroke: '#ffffff'}});
}
}
};
module.exports = role; | // If the sign is unclaimed or not claimed by me
if(!creep.room.controller.sign || creep.room.controller.sign.username != creep.owner.username) {
if(creep.signController(creep.room.controller, "I'm claiming the objective") == ERR_NOT_IN_RANGE) {
creep.doMove(creep.room.controller, {visualizePathStyle: {stroke: '#ccffcc'}}); | random_line_split |
search.ts | import _ from 'lodash';
import impressionSrv from './impression';
import { contextSrv } from './context';
import { hasFilters } from 'src/views/search/utils';
import { SECTION_STORAGE_KEY } from 'src/views/search/constants';
import { DashboardSection, DashboardSearchItemType, DashboardSearchHit, SearchLayout } from 'src/views/search/types';
import { backendSrv } from './backend/backend';
import localStore from '../library/utils/localStore';
interface Sections {
[key: string]: Partial<DashboardSection>;
}
export class SearchSrv {
private getRecentDashboards(sections: DashboardSection[] | any) {
return this.queryForRecentDashboards().then((result: any[]) => {
if (result.length > 0) {
sections['recent'] = {
title: 'Recent',
icon: 'clock-nine',
score: -1,
expanded: localStore.getBool(`${SECTION_STORAGE_KEY}.recent`, true),
items: result,
type: DashboardSearchItemType.DashFolder,
};
}
});
}
private queryForRecentDashboards(): Promise<DashboardSearchHit[]> {
const dashIds: number[] = _.take(impressionSrv.getDashboardOpened(), 30);
if (dashIds.length === 0) {
return Promise.resolve([]);
}
return backendSrv.search({ dashboardIds: dashIds }).then(res => {
const dashes = res.data
return dashIds
.map(orderId => dashes.find(dash => dash.id === orderId))
.filter(hit => hit && !hit.isStarred) as DashboardSearchHit[];
}).catch(() => []);
}
private getStarred(sections: DashboardSection): Promise<any> {
if (!contextSrv.isSignedIn) {
return Promise.resolve();
}
return backendSrv.search({ starred: true, limit: 30 }).then(result => {
if (result.length > 0) {
(sections as any)['starred'] = {
title: 'Starred',
icon: 'star',
score: -2,
expanded: localStore.getBool(`${SECTION_STORAGE_KEY}.starred`, true),
items: result,
type: DashboardSearchItemType.DashFolder,
};
}
});
}
search(options: any) {
const sections: any = {};
const promises = [];
const query = _.clone(options);
const filters = hasFilters(options) || query.folderIds?.length > 0;
query.folderIds = query.folderIds || [];
if (query.layout === SearchLayout.List) {
return backendSrv
.search({ ...query, type: DashboardSearchItemType.DashDB })
.then(res => (res.data.length ? [{ title: '', items: res.data }] : []));
}
if (!filters) {
query.folderIds = [0];
}
if (!options.skipRecent && !filters) {
promises.push(this.getRecentDashboards(sections));
}
if (!options.skipStarred && !filters) {
promises.push(this.getStarred(sections));
}
promises.push(
backendSrv.search(query).then(res => {
return this.handleSearchResult(sections, res.data);
})
);
return Promise.all(promises).then(() => {
return _.sortBy(_.values(sections), 'score');
});
}
private handleSearchResult(sections: Sections, results: DashboardSearchHit[]): any |
getDashboardTags() {
return backendSrv.get('/api/dashboard/tags').then((res) => res.data);
}
getSortOptions() {
return backendSrv.get('/api/search/sorting').then((res) => res.data);
}
}
| {
if (results.length === 0) {
return sections;
}
// create folder index
for (const hit of results) {
if (hit.type === 'dash-folder') {
sections[hit.id] = {
id: hit.id,
uid: hit.uid,
title: hit.title,
expanded: false,
items: [],
url: hit.url,
icon: 'folder',
score: _.keys(sections).length,
type: hit.type,
};
}
}
for (const hit of results) {
if (hit.type === 'dash-folder') {
continue;
}
let section = sections[hit.folderId || 0];
if (!section) {
if (hit.folderId) {
section = {
id: hit.folderId,
uid: hit.folderUid,
title: hit.folderTitle,
url: hit.folderUrl,
items: [],
icon: 'folder-open',
score: _.keys(sections).length,
type: DashboardSearchItemType.DashFolder,
};
} else {
section = {
id: 0,
title: 'General',
items: [],
icon: 'folder-open',
score: _.keys(sections).length,
type: DashboardSearchItemType.DashFolder,
};
}
// add section
sections[hit.folderId || 0] = section;
}
section.expanded = true;
section.items && section.items.push(hit);
}
} | identifier_body |
search.ts | import _ from 'lodash';
import impressionSrv from './impression';
import { contextSrv } from './context';
import { hasFilters } from 'src/views/search/utils';
import { SECTION_STORAGE_KEY } from 'src/views/search/constants';
import { DashboardSection, DashboardSearchItemType, DashboardSearchHit, SearchLayout } from 'src/views/search/types';
import { backendSrv } from './backend/backend';
import localStore from '../library/utils/localStore';
interface Sections {
[key: string]: Partial<DashboardSection>;
}
export class SearchSrv {
private getRecentDashboards(sections: DashboardSection[] | any) {
return this.queryForRecentDashboards().then((result: any[]) => {
if (result.length > 0) {
sections['recent'] = {
title: 'Recent',
icon: 'clock-nine',
score: -1,
expanded: localStore.getBool(`${SECTION_STORAGE_KEY}.recent`, true),
items: result,
type: DashboardSearchItemType.DashFolder,
};
}
});
}
private queryForRecentDashboards(): Promise<DashboardSearchHit[]> {
const dashIds: number[] = _.take(impressionSrv.getDashboardOpened(), 30);
if (dashIds.length === 0) {
return Promise.resolve([]);
}
return backendSrv.search({ dashboardIds: dashIds }).then(res => {
const dashes = res.data
return dashIds
.map(orderId => dashes.find(dash => dash.id === orderId))
.filter(hit => hit && !hit.isStarred) as DashboardSearchHit[];
}).catch(() => []);
}
private getStarred(sections: DashboardSection): Promise<any> {
if (!contextSrv.isSignedIn) {
return Promise.resolve();
}
return backendSrv.search({ starred: true, limit: 30 }).then(result => {
if (result.length > 0) {
(sections as any)['starred'] = {
title: 'Starred',
icon: 'star',
score: -2,
expanded: localStore.getBool(`${SECTION_STORAGE_KEY}.starred`, true),
items: result,
type: DashboardSearchItemType.DashFolder,
};
}
});
}
search(options: any) {
const sections: any = {};
const promises = [];
const query = _.clone(options);
const filters = hasFilters(options) || query.folderIds?.length > 0;
query.folderIds = query.folderIds || [];
if (query.layout === SearchLayout.List) {
return backendSrv
.search({ ...query, type: DashboardSearchItemType.DashDB })
.then(res => (res.data.length ? [{ title: '', items: res.data }] : []));
}
if (!filters) {
query.folderIds = [0];
}
if (!options.skipRecent && !filters) {
promises.push(this.getRecentDashboards(sections));
}
if (!options.skipStarred && !filters) {
promises.push(this.getStarred(sections));
}
promises.push(
backendSrv.search(query).then(res => {
return this.handleSearchResult(sections, res.data);
})
);
return Promise.all(promises).then(() => {
return _.sortBy(_.values(sections), 'score');
});
}
private handleSearchResult(sections: Sections, results: DashboardSearchHit[]): any {
if (results.length === 0) {
return sections;
}
// create folder index
for (const hit of results) {
if (hit.type === 'dash-folder') {
sections[hit.id] = {
id: hit.id,
uid: hit.uid,
title: hit.title,
expanded: false,
items: [],
url: hit.url,
icon: 'folder',
score: _.keys(sections).length,
type: hit.type,
};
}
}
for (const hit of results) {
if (hit.type === 'dash-folder') {
continue;
}
let section = sections[hit.folderId || 0];
if (!section) {
if (hit.folderId) {
section = {
id: hit.folderId,
uid: hit.folderUid,
title: hit.folderTitle,
url: hit.folderUrl,
items: [],
icon: 'folder-open',
score: _.keys(sections).length,
type: DashboardSearchItemType.DashFolder,
};
} else {
section = {
id: 0,
title: 'General',
items: [],
icon: 'folder-open',
score: _.keys(sections).length,
type: DashboardSearchItemType.DashFolder,
};
}
// add section
sections[hit.folderId || 0] = section;
}
section.expanded = true;
section.items && section.items.push(hit);
}
}
| () {
return backendSrv.get('/api/dashboard/tags').then((res) => res.data);
}
getSortOptions() {
return backendSrv.get('/api/search/sorting').then((res) => res.data);
}
}
| getDashboardTags | identifier_name |
search.ts | import _ from 'lodash';
import impressionSrv from './impression';
import { contextSrv } from './context';
import { hasFilters } from 'src/views/search/utils';
import { SECTION_STORAGE_KEY } from 'src/views/search/constants';
import { DashboardSection, DashboardSearchItemType, DashboardSearchHit, SearchLayout } from 'src/views/search/types';
import { backendSrv } from './backend/backend';
import localStore from '../library/utils/localStore';
interface Sections {
[key: string]: Partial<DashboardSection>;
}
export class SearchSrv {
private getRecentDashboards(sections: DashboardSection[] | any) {
return this.queryForRecentDashboards().then((result: any[]) => {
if (result.length > 0) {
sections['recent'] = {
title: 'Recent',
icon: 'clock-nine',
score: -1,
expanded: localStore.getBool(`${SECTION_STORAGE_KEY}.recent`, true),
items: result,
type: DashboardSearchItemType.DashFolder,
};
}
});
}
private queryForRecentDashboards(): Promise<DashboardSearchHit[]> {
const dashIds: number[] = _.take(impressionSrv.getDashboardOpened(), 30);
if (dashIds.length === 0) {
return Promise.resolve([]);
}
return backendSrv.search({ dashboardIds: dashIds }).then(res => {
const dashes = res.data
return dashIds
.map(orderId => dashes.find(dash => dash.id === orderId))
.filter(hit => hit && !hit.isStarred) as DashboardSearchHit[];
}).catch(() => []);
}
private getStarred(sections: DashboardSection): Promise<any> {
if (!contextSrv.isSignedIn) {
return Promise.resolve();
}
return backendSrv.search({ starred: true, limit: 30 }).then(result => {
if (result.length > 0) {
(sections as any)['starred'] = {
title: 'Starred',
icon: 'star',
score: -2,
expanded: localStore.getBool(`${SECTION_STORAGE_KEY}.starred`, true),
items: result,
type: DashboardSearchItemType.DashFolder,
};
}
});
}
search(options: any) {
const sections: any = {};
const promises = [];
const query = _.clone(options);
const filters = hasFilters(options) || query.folderIds?.length > 0;
query.folderIds = query.folderIds || [];
if (query.layout === SearchLayout.List) {
return backendSrv
.search({ ...query, type: DashboardSearchItemType.DashDB })
.then(res => (res.data.length ? [{ title: '', items: res.data }] : []));
}
if (!filters) {
query.folderIds = [0];
}
if (!options.skipRecent && !filters) {
promises.push(this.getRecentDashboards(sections));
}
if (!options.skipStarred && !filters) {
promises.push(this.getStarred(sections));
}
promises.push(
backendSrv.search(query).then(res => {
return this.handleSearchResult(sections, res.data);
})
);
return Promise.all(promises).then(() => {
return _.sortBy(_.values(sections), 'score');
});
}
private handleSearchResult(sections: Sections, results: DashboardSearchHit[]): any {
if (results.length === 0) {
return sections;
}
// create folder index
for (const hit of results) {
if (hit.type === 'dash-folder') {
sections[hit.id] = {
id: hit.id,
uid: hit.uid,
title: hit.title,
expanded: false,
items: [],
url: hit.url,
icon: 'folder',
score: _.keys(sections).length,
type: hit.type,
};
}
}
for (const hit of results) {
if (hit.type === 'dash-folder') |
let section = sections[hit.folderId || 0];
if (!section) {
if (hit.folderId) {
section = {
id: hit.folderId,
uid: hit.folderUid,
title: hit.folderTitle,
url: hit.folderUrl,
items: [],
icon: 'folder-open',
score: _.keys(sections).length,
type: DashboardSearchItemType.DashFolder,
};
} else {
section = {
id: 0,
title: 'General',
items: [],
icon: 'folder-open',
score: _.keys(sections).length,
type: DashboardSearchItemType.DashFolder,
};
}
// add section
sections[hit.folderId || 0] = section;
}
section.expanded = true;
section.items && section.items.push(hit);
}
}
getDashboardTags() {
return backendSrv.get('/api/dashboard/tags').then((res) => res.data);
}
getSortOptions() {
return backendSrv.get('/api/search/sorting').then((res) => res.data);
}
}
| {
continue;
} | conditional_block |
search.ts | import _ from 'lodash';
import impressionSrv from './impression';
import { contextSrv } from './context';
import { hasFilters } from 'src/views/search/utils';
import { SECTION_STORAGE_KEY } from 'src/views/search/constants';
import { DashboardSection, DashboardSearchItemType, DashboardSearchHit, SearchLayout } from 'src/views/search/types';
import { backendSrv } from './backend/backend';
import localStore from '../library/utils/localStore';
interface Sections {
[key: string]: Partial<DashboardSection>;
}
export class SearchSrv {
private getRecentDashboards(sections: DashboardSection[] | any) {
return this.queryForRecentDashboards().then((result: any[]) => {
if (result.length > 0) {
sections['recent'] = {
title: 'Recent',
icon: 'clock-nine',
score: -1,
expanded: localStore.getBool(`${SECTION_STORAGE_KEY}.recent`, true),
items: result,
type: DashboardSearchItemType.DashFolder,
};
}
});
}
private queryForRecentDashboards(): Promise<DashboardSearchHit[]> {
const dashIds: number[] = _.take(impressionSrv.getDashboardOpened(), 30);
if (dashIds.length === 0) {
return Promise.resolve([]);
}
return backendSrv.search({ dashboardIds: dashIds }).then(res => {
const dashes = res.data
return dashIds
.map(orderId => dashes.find(dash => dash.id === orderId))
.filter(hit => hit && !hit.isStarred) as DashboardSearchHit[];
}).catch(() => []);
}
private getStarred(sections: DashboardSection): Promise<any> {
if (!contextSrv.isSignedIn) {
return Promise.resolve();
}
return backendSrv.search({ starred: true, limit: 30 }).then(result => {
if (result.length > 0) {
(sections as any)['starred'] = {
title: 'Starred',
icon: 'star', | type: DashboardSearchItemType.DashFolder,
};
}
});
}
search(options: any) {
const sections: any = {};
const promises = [];
const query = _.clone(options);
const filters = hasFilters(options) || query.folderIds?.length > 0;
query.folderIds = query.folderIds || [];
if (query.layout === SearchLayout.List) {
return backendSrv
.search({ ...query, type: DashboardSearchItemType.DashDB })
.then(res => (res.data.length ? [{ title: '', items: res.data }] : []));
}
if (!filters) {
query.folderIds = [0];
}
if (!options.skipRecent && !filters) {
promises.push(this.getRecentDashboards(sections));
}
if (!options.skipStarred && !filters) {
promises.push(this.getStarred(sections));
}
promises.push(
backendSrv.search(query).then(res => {
return this.handleSearchResult(sections, res.data);
})
);
return Promise.all(promises).then(() => {
return _.sortBy(_.values(sections), 'score');
});
}
private handleSearchResult(sections: Sections, results: DashboardSearchHit[]): any {
if (results.length === 0) {
return sections;
}
// create folder index
for (const hit of results) {
if (hit.type === 'dash-folder') {
sections[hit.id] = {
id: hit.id,
uid: hit.uid,
title: hit.title,
expanded: false,
items: [],
url: hit.url,
icon: 'folder',
score: _.keys(sections).length,
type: hit.type,
};
}
}
for (const hit of results) {
if (hit.type === 'dash-folder') {
continue;
}
let section = sections[hit.folderId || 0];
if (!section) {
if (hit.folderId) {
section = {
id: hit.folderId,
uid: hit.folderUid,
title: hit.folderTitle,
url: hit.folderUrl,
items: [],
icon: 'folder-open',
score: _.keys(sections).length,
type: DashboardSearchItemType.DashFolder,
};
} else {
section = {
id: 0,
title: 'General',
items: [],
icon: 'folder-open',
score: _.keys(sections).length,
type: DashboardSearchItemType.DashFolder,
};
}
// add section
sections[hit.folderId || 0] = section;
}
section.expanded = true;
section.items && section.items.push(hit);
}
}
getDashboardTags() {
return backendSrv.get('/api/dashboard/tags').then((res) => res.data);
}
getSortOptions() {
return backendSrv.get('/api/search/sorting').then((res) => res.data);
}
} | score: -2,
expanded: localStore.getBool(`${SECTION_STORAGE_KEY}.starred`, true),
items: result, | random_line_split |
boolean.py | from copy import deepcopy
import numpy as np
from menpo.image.base import Image
from skimage.transform import pyramid_gaussian
class BooleanImage(Image):
r"""
A mask image made from binary pixels. The region of the image that is
left exposed by the mask is referred to as the 'masked region'. The
set of 'masked' pixels is those pixels corresponding to a True value in
the mask.
Parameters
-----------
mask_data : (M, N, ..., L) ndarray
The binary mask data. Note that there is no channel axis - a 2D Mask
Image is built from just a 2D numpy array of mask_data.
Automatically coerced in to boolean values.
"""
def __init__(self, mask_data):
# Enforce boolean pixels, and add a channel dim
mask_data = np.asarray(mask_data[..., None], dtype=np.bool)
super(BooleanImage, self).__init__(mask_data)
@classmethod
def _init_with_channel(cls, image_data_with_channel):
r"""
Constructor that always requires the image has a
channel on the last axis. Only used by from_vector. By default,
just calls the constructor. Subclasses with constructors that don't
require channel axes need to overwrite this.
"""
return cls(image_data_with_channel[..., 0])
@classmethod
def blank(cls, shape, fill=True, round='ceil', **kwargs):
r"""
Returns a blank :class:`BooleanImage` of the requested shape
Parameters
----------
shape : tuple or list
The shape of the image. Any floating point values are rounded
according to the ``round`` kwarg.
fill : True or False, optional
The mask value to be set everywhere
Default: True (masked region is the whole image - meaning the whole
image is exposed)
round: {'ceil', 'floor', 'round'}
Rounding function to be applied to floating point shapes.
Default: 'ceil'
Returns
-------
blank_image : :class:`BooleanImage`
A blank mask of the requested size
"""
if round not in ['ceil', 'round', 'floor']:
raise ValueError('round must be either ceil, round or floor')
# Ensure that the '+' operator means concatenate tuples
shape = tuple(getattr(np, round)(shape))
if fill:
mask = np.ones(shape, dtype=np.bool)
else:
mask = np.zeros(shape, dtype=np.bool)
return cls(mask)
@property
def mask(self):
r"""
Returns the pixels of the mask with no channel axis. This is what
should be used to mask any k-dimensional image.
:type: (M, N, ..., L), np.bool ndarray
"""
return self.pixels[..., 0]
@property
def n_true(self):
r"""
The number of ``True`` values in the mask
:type: int
"""
return np.sum(self.pixels)
@property
def n_false(self):
r"""
The number of ``False`` values in the mask
:type: int
"""
return self.n_pixels - self.n_true
@property
def proportion_true(self):
r"""
The proportion of the mask which is ``True``
:type: double
"""
return (self.n_true * 1.0) / self.n_pixels
@property
def proportion_false(self):
r"""
The proportion of the mask which is ``False``
:type: double
"""
return (self.n_false * 1.0) / self.n_pixels
@property
def true_indices(self):
r"""
The indices of pixels that are true.
:type: (``n_dims``, ``n_true``) ndarray
"""
# Ignore the channel axis
return np.vstack(np.nonzero(self.pixels[..., 0])).T
@property
def false_indices(self):
r"""
The indices of pixels that are false.
:type: (``n_dims``, ``n_false``) ndarray
"""
# Ignore the channel axis
return np.vstack(np.nonzero(~self.pixels[..., 0])).T
@property
def all_indices(self):
r"""
Indices into all pixels of the mask, as consistent with
true_indices and false_indices
:type: (``n_dims``, ``n_pixels``) ndarray
"""
return np.indices(self.shape).reshape([self.n_dims, -1]).T
def __str__(self):
return ('{} {}D mask, {:.1%} '
'of which is True '.format(self._str_shape, self.n_dims,
self.proportion_true))
def | (self, flattened):
r"""
Takes a flattened vector and returns a new
:class:`BooleanImage` formed by
reshaping the vector to the correct dimensions. Note that this is
rebuilding a boolean image **itself** from boolean values. The mask
is in no way interpreted in performing the operation, in contrast to
MaskedImage, where only the masked region is used in from_vector()
and as_vector(). Any image landmarks are transferred in the process.
Parameters
----------
flattened : (``n_pixels``,) np.bool ndarray
A flattened vector of all the pixels of a BooleanImage.
Returns
-------
image : :class:`BooleanImage`
New BooleanImage of same shape as this image
"""
mask = BooleanImage(flattened.reshape(self.shape))
mask.landmarks = self.landmarks
return mask
def invert(self):
r"""
Inverts the current mask in place, setting all True values to False,
and all False values to True.
"""
self.pixels = ~self.pixels
def inverted_copy(self):
r"""
Returns a copy of this Boolean image, which is inverted.
Returns
-------
inverted_image: :class:`BooleanNSImage`
An inverted copy of this boolean image.
"""
inverse = deepcopy(self)
inverse.invert()
return inverse
def bounds_true(self, boundary=0, constrain_to_bounds=True):
r"""
Returns the minimum to maximum indices along all dimensions that the
mask includes which fully surround the True mask values. In the case
of a 2D Image for instance, the min and max define two corners of a
rectangle bounding the True pixel values.
Parameters
----------
boundary : int, optional
A number of pixels that should be added to the extent. A
negative value can be used to shrink the bounds in.
Default: 0
constrain_to_bounds: bool, optional
If True, the bounding extent is snapped to not go beyond
the edge of the image. If False, the bounds are left unchanged.
Default: True
Returns
--------
min_b : (D,) ndarray
The minimum extent of the True mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
max_b : (D,) ndarray
The maximum extent of the True mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
"""
mpi = self.true_indices
maxes = np.max(mpi, axis=0) + boundary
mins = np.min(mpi, axis=0) - boundary
if constrain_to_bounds:
maxes = self.constrain_points_to_bounds(maxes)
mins = self.constrain_points_to_bounds(mins)
return mins, maxes
def bounds_false(self, boundary=0, constrain_to_bounds=True):
r"""
Returns the minimum to maximum indices along all dimensions that the
mask includes which fully surround the False mask values. In the case
of a 2D Image for instance, the min and max define two corners of a
rectangle bounding the False pixel values.
Parameters
----------
boundary : int >= 0, optional
A number of pixels that should be added to the extent. A
negative value can be used to shrink the bounds in.
Default: 0
constrain_to_bounds: bool, optional
If True, the bounding extent is snapped to not go beyond
the edge of the image. If False, the bounds are left unchanged.
Default: True
Returns
--------
min_b : (D,) ndarray
The minimum extent of the False mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
max_b : (D,) ndarray
The maximum extent of the False mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
"""
return self.inverted_copy().bounds_true(
boundary=boundary, constrain_to_bounds=constrain_to_bounds)
def warp_to(self, template_mask, transform, warp_landmarks=False,
interpolator='scipy', **kwargs):
r"""
Warps this BooleanImage into a different reference space.
Parameters
----------
template_mask : :class:`menpo.image.boolean.BooleanImage`
Defines the shape of the result, and what pixels should be
sampled.
transform : :class:`menpo.transform.base.Transform`
Transform **from the template space back to this image**.
Defines, for each True pixel location on the template, which pixel
location should be sampled from on this image.
warp_landmarks : bool, optional
If ``True``, warped_image will have the same landmark dictionary
as self, but with each landmark updated to the warped position.
Default: ``False``
interpolator : 'scipy' or 'c', optional
The interpolator that should be used to perform the warp.
Default: 'scipy'
kwargs : dict
Passed through to the interpolator. See `menpo.interpolation`
for details.
Returns
-------
warped_image : type(self)
A copy of this image, warped.
"""
# enforce the order as 0, for this boolean data, then call super
manually_set_order = kwargs.get('order', 0)
if manually_set_order != 0:
raise ValueError(
"The order of the interpolation on a boolean image has to be "
"0 (attempted to set {})".format(manually_set_order))
kwargs['order'] = 0
return Image.warp_to(self, template_mask, transform,
warp_landmarks=warp_landmarks,
interpolator=interpolator, **kwargs)
def _build_warped_image(self, template_mask, sampled_pixel_values,
**kwargs):
r"""
Builds the warped image from the template mask and
sampled pixel values. Overridden for BooleanImage as we can't use
the usual from_vector_inplace method.
"""
warped_image = BooleanImage.blank(template_mask.shape)
# As we are a mask image, we have to implement the update a little
# more manually than other image classes.
warped_image.pixels[warped_image.mask] = sampled_pixel_values
return warped_image
| from_vector | identifier_name |
boolean.py | from copy import deepcopy
import numpy as np
from menpo.image.base import Image
from skimage.transform import pyramid_gaussian
class BooleanImage(Image):
r"""
A mask image made from binary pixels. The region of the image that is
left exposed by the mask is referred to as the 'masked region'. The
set of 'masked' pixels is those pixels corresponding to a True value in
the mask.
Parameters
-----------
mask_data : (M, N, ..., L) ndarray
The binary mask data. Note that there is no channel axis - a 2D Mask
Image is built from just a 2D numpy array of mask_data.
Automatically coerced in to boolean values.
"""
def __init__(self, mask_data):
# Enforce boolean pixels, and add a channel dim
mask_data = np.asarray(mask_data[..., None], dtype=np.bool)
super(BooleanImage, self).__init__(mask_data)
@classmethod
def _init_with_channel(cls, image_data_with_channel):
r"""
Constructor that always requires the image has a
channel on the last axis. Only used by from_vector. By default,
just calls the constructor. Subclasses with constructors that don't
require channel axes need to overwrite this.
"""
return cls(image_data_with_channel[..., 0])
@classmethod
def blank(cls, shape, fill=True, round='ceil', **kwargs):
r"""
Returns a blank :class:`BooleanImage` of the requested shape
Parameters
----------
shape : tuple or list
The shape of the image. Any floating point values are rounded
according to the ``round`` kwarg.
fill : True or False, optional
The mask value to be set everywhere
Default: True (masked region is the whole image - meaning the whole
image is exposed)
round: {'ceil', 'floor', 'round'}
Rounding function to be applied to floating point shapes.
Default: 'ceil'
Returns
-------
blank_image : :class:`BooleanImage` | """
if round not in ['ceil', 'round', 'floor']:
raise ValueError('round must be either ceil, round or floor')
# Ensure that the '+' operator means concatenate tuples
shape = tuple(getattr(np, round)(shape))
if fill:
mask = np.ones(shape, dtype=np.bool)
else:
mask = np.zeros(shape, dtype=np.bool)
return cls(mask)
@property
def mask(self):
r"""
Returns the pixels of the mask with no channel axis. This is what
should be used to mask any k-dimensional image.
:type: (M, N, ..., L), np.bool ndarray
"""
return self.pixels[..., 0]
@property
def n_true(self):
r"""
The number of ``True`` values in the mask
:type: int
"""
return np.sum(self.pixels)
@property
def n_false(self):
r"""
The number of ``False`` values in the mask
:type: int
"""
return self.n_pixels - self.n_true
@property
def proportion_true(self):
r"""
The proportion of the mask which is ``True``
:type: double
"""
return (self.n_true * 1.0) / self.n_pixels
@property
def proportion_false(self):
r"""
The proportion of the mask which is ``False``
:type: double
"""
return (self.n_false * 1.0) / self.n_pixels
@property
def true_indices(self):
r"""
The indices of pixels that are true.
:type: (``n_dims``, ``n_true``) ndarray
"""
# Ignore the channel axis
return np.vstack(np.nonzero(self.pixels[..., 0])).T
@property
def false_indices(self):
r"""
The indices of pixels that are false.
:type: (``n_dims``, ``n_false``) ndarray
"""
# Ignore the channel axis
return np.vstack(np.nonzero(~self.pixels[..., 0])).T
@property
def all_indices(self):
r"""
Indices into all pixels of the mask, as consistent with
true_indices and false_indices
:type: (``n_dims``, ``n_pixels``) ndarray
"""
return np.indices(self.shape).reshape([self.n_dims, -1]).T
def __str__(self):
return ('{} {}D mask, {:.1%} '
'of which is True '.format(self._str_shape, self.n_dims,
self.proportion_true))
def from_vector(self, flattened):
r"""
Takes a flattened vector and returns a new
:class:`BooleanImage` formed by
reshaping the vector to the correct dimensions. Note that this is
rebuilding a boolean image **itself** from boolean values. The mask
is in no way interpreted in performing the operation, in contrast to
MaskedImage, where only the masked region is used in from_vector()
and as_vector(). Any image landmarks are transferred in the process.
Parameters
----------
flattened : (``n_pixels``,) np.bool ndarray
A flattened vector of all the pixels of a BooleanImage.
Returns
-------
image : :class:`BooleanImage`
New BooleanImage of same shape as this image
"""
mask = BooleanImage(flattened.reshape(self.shape))
mask.landmarks = self.landmarks
return mask
def invert(self):
r"""
Inverts the current mask in place, setting all True values to False,
and all False values to True.
"""
self.pixels = ~self.pixels
def inverted_copy(self):
r"""
Returns a copy of this Boolean image, which is inverted.
Returns
-------
inverted_image: :class:`BooleanNSImage`
An inverted copy of this boolean image.
"""
inverse = deepcopy(self)
inverse.invert()
return inverse
def bounds_true(self, boundary=0, constrain_to_bounds=True):
r"""
Returns the minimum to maximum indices along all dimensions that the
mask includes which fully surround the True mask values. In the case
of a 2D Image for instance, the min and max define two corners of a
rectangle bounding the True pixel values.
Parameters
----------
boundary : int, optional
A number of pixels that should be added to the extent. A
negative value can be used to shrink the bounds in.
Default: 0
constrain_to_bounds: bool, optional
If True, the bounding extent is snapped to not go beyond
the edge of the image. If False, the bounds are left unchanged.
Default: True
Returns
--------
min_b : (D,) ndarray
The minimum extent of the True mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
max_b : (D,) ndarray
The maximum extent of the True mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
"""
mpi = self.true_indices
maxes = np.max(mpi, axis=0) + boundary
mins = np.min(mpi, axis=0) - boundary
if constrain_to_bounds:
maxes = self.constrain_points_to_bounds(maxes)
mins = self.constrain_points_to_bounds(mins)
return mins, maxes
def bounds_false(self, boundary=0, constrain_to_bounds=True):
r"""
Returns the minimum to maximum indices along all dimensions that the
mask includes which fully surround the False mask values. In the case
of a 2D Image for instance, the min and max define two corners of a
rectangle bounding the False pixel values.
Parameters
----------
boundary : int >= 0, optional
A number of pixels that should be added to the extent. A
negative value can be used to shrink the bounds in.
Default: 0
constrain_to_bounds: bool, optional
If True, the bounding extent is snapped to not go beyond
the edge of the image. If False, the bounds are left unchanged.
Default: True
Returns
--------
min_b : (D,) ndarray
The minimum extent of the False mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
max_b : (D,) ndarray
The maximum extent of the False mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
"""
return self.inverted_copy().bounds_true(
boundary=boundary, constrain_to_bounds=constrain_to_bounds)
def warp_to(self, template_mask, transform, warp_landmarks=False,
interpolator='scipy', **kwargs):
r"""
Warps this BooleanImage into a different reference space.
Parameters
----------
template_mask : :class:`menpo.image.boolean.BooleanImage`
Defines the shape of the result, and what pixels should be
sampled.
transform : :class:`menpo.transform.base.Transform`
Transform **from the template space back to this image**.
Defines, for each True pixel location on the template, which pixel
location should be sampled from on this image.
warp_landmarks : bool, optional
If ``True``, warped_image will have the same landmark dictionary
as self, but with each landmark updated to the warped position.
Default: ``False``
interpolator : 'scipy' or 'c', optional
The interpolator that should be used to perform the warp.
Default: 'scipy'
kwargs : dict
Passed through to the interpolator. See `menpo.interpolation`
for details.
Returns
-------
warped_image : type(self)
A copy of this image, warped.
"""
# enforce the order as 0, for this boolean data, then call super
manually_set_order = kwargs.get('order', 0)
if manually_set_order != 0:
raise ValueError(
"The order of the interpolation on a boolean image has to be "
"0 (attempted to set {})".format(manually_set_order))
kwargs['order'] = 0
return Image.warp_to(self, template_mask, transform,
warp_landmarks=warp_landmarks,
interpolator=interpolator, **kwargs)
def _build_warped_image(self, template_mask, sampled_pixel_values,
**kwargs):
r"""
Builds the warped image from the template mask and
sampled pixel values. Overridden for BooleanImage as we can't use
the usual from_vector_inplace method.
"""
warped_image = BooleanImage.blank(template_mask.shape)
# As we are a mask image, we have to implement the update a little
# more manually than other image classes.
warped_image.pixels[warped_image.mask] = sampled_pixel_values
return warped_image | A blank mask of the requested size | random_line_split |
boolean.py | from copy import deepcopy
import numpy as np
from menpo.image.base import Image
from skimage.transform import pyramid_gaussian
class BooleanImage(Image):
| r"""
A mask image made from binary pixels. The region of the image that is
left exposed by the mask is referred to as the 'masked region'. The
set of 'masked' pixels is those pixels corresponding to a True value in
the mask.
Parameters
-----------
mask_data : (M, N, ..., L) ndarray
The binary mask data. Note that there is no channel axis - a 2D Mask
Image is built from just a 2D numpy array of mask_data.
Automatically coerced in to boolean values.
"""
def __init__(self, mask_data):
# Enforce boolean pixels, and add a channel dim
mask_data = np.asarray(mask_data[..., None], dtype=np.bool)
super(BooleanImage, self).__init__(mask_data)
@classmethod
def _init_with_channel(cls, image_data_with_channel):
r"""
Constructor that always requires the image has a
channel on the last axis. Only used by from_vector. By default,
just calls the constructor. Subclasses with constructors that don't
require channel axes need to overwrite this.
"""
return cls(image_data_with_channel[..., 0])
@classmethod
def blank(cls, shape, fill=True, round='ceil', **kwargs):
r"""
Returns a blank :class:`BooleanImage` of the requested shape
Parameters
----------
shape : tuple or list
The shape of the image. Any floating point values are rounded
according to the ``round`` kwarg.
fill : True or False, optional
The mask value to be set everywhere
Default: True (masked region is the whole image - meaning the whole
image is exposed)
round: {'ceil', 'floor', 'round'}
Rounding function to be applied to floating point shapes.
Default: 'ceil'
Returns
-------
blank_image : :class:`BooleanImage`
A blank mask of the requested size
"""
if round not in ['ceil', 'round', 'floor']:
raise ValueError('round must be either ceil, round or floor')
# Ensure that the '+' operator means concatenate tuples
shape = tuple(getattr(np, round)(shape))
if fill:
mask = np.ones(shape, dtype=np.bool)
else:
mask = np.zeros(shape, dtype=np.bool)
return cls(mask)
@property
def mask(self):
r"""
Returns the pixels of the mask with no channel axis. This is what
should be used to mask any k-dimensional image.
:type: (M, N, ..., L), np.bool ndarray
"""
return self.pixels[..., 0]
@property
def n_true(self):
r"""
The number of ``True`` values in the mask
:type: int
"""
return np.sum(self.pixels)
@property
def n_false(self):
r"""
The number of ``False`` values in the mask
:type: int
"""
return self.n_pixels - self.n_true
@property
def proportion_true(self):
r"""
The proportion of the mask which is ``True``
:type: double
"""
return (self.n_true * 1.0) / self.n_pixels
@property
def proportion_false(self):
r"""
The proportion of the mask which is ``False``
:type: double
"""
return (self.n_false * 1.0) / self.n_pixels
@property
def true_indices(self):
r"""
The indices of pixels that are true.
:type: (``n_dims``, ``n_true``) ndarray
"""
# Ignore the channel axis
return np.vstack(np.nonzero(self.pixels[..., 0])).T
@property
def false_indices(self):
r"""
The indices of pixels that are false.
:type: (``n_dims``, ``n_false``) ndarray
"""
# Ignore the channel axis
return np.vstack(np.nonzero(~self.pixels[..., 0])).T
@property
def all_indices(self):
r"""
Indices into all pixels of the mask, as consistent with
true_indices and false_indices
:type: (``n_dims``, ``n_pixels``) ndarray
"""
return np.indices(self.shape).reshape([self.n_dims, -1]).T
def __str__(self):
return ('{} {}D mask, {:.1%} '
'of which is True '.format(self._str_shape, self.n_dims,
self.proportion_true))
def from_vector(self, flattened):
r"""
Takes a flattened vector and returns a new
:class:`BooleanImage` formed by
reshaping the vector to the correct dimensions. Note that this is
rebuilding a boolean image **itself** from boolean values. The mask
is in no way interpreted in performing the operation, in contrast to
MaskedImage, where only the masked region is used in from_vector()
and as_vector(). Any image landmarks are transferred in the process.
Parameters
----------
flattened : (``n_pixels``,) np.bool ndarray
A flattened vector of all the pixels of a BooleanImage.
Returns
-------
image : :class:`BooleanImage`
New BooleanImage of same shape as this image
"""
mask = BooleanImage(flattened.reshape(self.shape))
mask.landmarks = self.landmarks
return mask
def invert(self):
r"""
Inverts the current mask in place, setting all True values to False,
and all False values to True.
"""
self.pixels = ~self.pixels
def inverted_copy(self):
r"""
Returns a copy of this Boolean image, which is inverted.
Returns
-------
inverted_image: :class:`BooleanNSImage`
An inverted copy of this boolean image.
"""
inverse = deepcopy(self)
inverse.invert()
return inverse
def bounds_true(self, boundary=0, constrain_to_bounds=True):
r"""
Returns the minimum to maximum indices along all dimensions that the
mask includes which fully surround the True mask values. In the case
of a 2D Image for instance, the min and max define two corners of a
rectangle bounding the True pixel values.
Parameters
----------
boundary : int, optional
A number of pixels that should be added to the extent. A
negative value can be used to shrink the bounds in.
Default: 0
constrain_to_bounds: bool, optional
If True, the bounding extent is snapped to not go beyond
the edge of the image. If False, the bounds are left unchanged.
Default: True
Returns
--------
min_b : (D,) ndarray
The minimum extent of the True mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
max_b : (D,) ndarray
The maximum extent of the True mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
"""
mpi = self.true_indices
maxes = np.max(mpi, axis=0) + boundary
mins = np.min(mpi, axis=0) - boundary
if constrain_to_bounds:
maxes = self.constrain_points_to_bounds(maxes)
mins = self.constrain_points_to_bounds(mins)
return mins, maxes
def bounds_false(self, boundary=0, constrain_to_bounds=True):
r"""
Returns the minimum to maximum indices along all dimensions that the
mask includes which fully surround the False mask values. In the case
of a 2D Image for instance, the min and max define two corners of a
rectangle bounding the False pixel values.
Parameters
----------
boundary : int >= 0, optional
A number of pixels that should be added to the extent. A
negative value can be used to shrink the bounds in.
Default: 0
constrain_to_bounds: bool, optional
If True, the bounding extent is snapped to not go beyond
the edge of the image. If False, the bounds are left unchanged.
Default: True
Returns
--------
min_b : (D,) ndarray
The minimum extent of the False mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
max_b : (D,) ndarray
The maximum extent of the False mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
"""
return self.inverted_copy().bounds_true(
boundary=boundary, constrain_to_bounds=constrain_to_bounds)
def warp_to(self, template_mask, transform, warp_landmarks=False,
interpolator='scipy', **kwargs):
r"""
Warps this BooleanImage into a different reference space.
Parameters
----------
template_mask : :class:`menpo.image.boolean.BooleanImage`
Defines the shape of the result, and what pixels should be
sampled.
transform : :class:`menpo.transform.base.Transform`
Transform **from the template space back to this image**.
Defines, for each True pixel location on the template, which pixel
location should be sampled from on this image.
warp_landmarks : bool, optional
If ``True``, warped_image will have the same landmark dictionary
as self, but with each landmark updated to the warped position.
Default: ``False``
interpolator : 'scipy' or 'c', optional
The interpolator that should be used to perform the warp.
Default: 'scipy'
kwargs : dict
Passed through to the interpolator. See `menpo.interpolation`
for details.
Returns
-------
warped_image : type(self)
A copy of this image, warped.
"""
# enforce the order as 0, for this boolean data, then call super
manually_set_order = kwargs.get('order', 0)
if manually_set_order != 0:
raise ValueError(
"The order of the interpolation on a boolean image has to be "
"0 (attempted to set {})".format(manually_set_order))
kwargs['order'] = 0
return Image.warp_to(self, template_mask, transform,
warp_landmarks=warp_landmarks,
interpolator=interpolator, **kwargs)
def _build_warped_image(self, template_mask, sampled_pixel_values,
**kwargs):
r"""
Builds the warped image from the template mask and
sampled pixel values. Overridden for BooleanImage as we can't use
the usual from_vector_inplace method.
"""
warped_image = BooleanImage.blank(template_mask.shape)
# As we are a mask image, we have to implement the update a little
# more manually than other image classes.
warped_image.pixels[warped_image.mask] = sampled_pixel_values
return warped_image | identifier_body | |
boolean.py | from copy import deepcopy
import numpy as np
from menpo.image.base import Image
from skimage.transform import pyramid_gaussian
class BooleanImage(Image):
r"""
A mask image made from binary pixels. The region of the image that is
left exposed by the mask is referred to as the 'masked region'. The
set of 'masked' pixels is those pixels corresponding to a True value in
the mask.
Parameters
-----------
mask_data : (M, N, ..., L) ndarray
The binary mask data. Note that there is no channel axis - a 2D Mask
Image is built from just a 2D numpy array of mask_data.
Automatically coerced in to boolean values.
"""
def __init__(self, mask_data):
# Enforce boolean pixels, and add a channel dim
mask_data = np.asarray(mask_data[..., None], dtype=np.bool)
super(BooleanImage, self).__init__(mask_data)
@classmethod
def _init_with_channel(cls, image_data_with_channel):
r"""
Constructor that always requires the image has a
channel on the last axis. Only used by from_vector. By default,
just calls the constructor. Subclasses with constructors that don't
require channel axes need to overwrite this.
"""
return cls(image_data_with_channel[..., 0])
@classmethod
def blank(cls, shape, fill=True, round='ceil', **kwargs):
r"""
Returns a blank :class:`BooleanImage` of the requested shape
Parameters
----------
shape : tuple or list
The shape of the image. Any floating point values are rounded
according to the ``round`` kwarg.
fill : True or False, optional
The mask value to be set everywhere
Default: True (masked region is the whole image - meaning the whole
image is exposed)
round: {'ceil', 'floor', 'round'}
Rounding function to be applied to floating point shapes.
Default: 'ceil'
Returns
-------
blank_image : :class:`BooleanImage`
A blank mask of the requested size
"""
if round not in ['ceil', 'round', 'floor']:
raise ValueError('round must be either ceil, round or floor')
# Ensure that the '+' operator means concatenate tuples
shape = tuple(getattr(np, round)(shape))
if fill:
mask = np.ones(shape, dtype=np.bool)
else:
mask = np.zeros(shape, dtype=np.bool)
return cls(mask)
@property
def mask(self):
r"""
Returns the pixels of the mask with no channel axis. This is what
should be used to mask any k-dimensional image.
:type: (M, N, ..., L), np.bool ndarray
"""
return self.pixels[..., 0]
@property
def n_true(self):
r"""
The number of ``True`` values in the mask
:type: int
"""
return np.sum(self.pixels)
@property
def n_false(self):
r"""
The number of ``False`` values in the mask
:type: int
"""
return self.n_pixels - self.n_true
@property
def proportion_true(self):
r"""
The proportion of the mask which is ``True``
:type: double
"""
return (self.n_true * 1.0) / self.n_pixels
@property
def proportion_false(self):
r"""
The proportion of the mask which is ``False``
:type: double
"""
return (self.n_false * 1.0) / self.n_pixels
@property
def true_indices(self):
r"""
The indices of pixels that are true.
:type: (``n_dims``, ``n_true``) ndarray
"""
# Ignore the channel axis
return np.vstack(np.nonzero(self.pixels[..., 0])).T
@property
def false_indices(self):
r"""
The indices of pixels that are false.
:type: (``n_dims``, ``n_false``) ndarray
"""
# Ignore the channel axis
return np.vstack(np.nonzero(~self.pixels[..., 0])).T
@property
def all_indices(self):
r"""
Indices into all pixels of the mask, as consistent with
true_indices and false_indices
:type: (``n_dims``, ``n_pixels``) ndarray
"""
return np.indices(self.shape).reshape([self.n_dims, -1]).T
def __str__(self):
return ('{} {}D mask, {:.1%} '
'of which is True '.format(self._str_shape, self.n_dims,
self.proportion_true))
def from_vector(self, flattened):
r"""
Takes a flattened vector and returns a new
:class:`BooleanImage` formed by
reshaping the vector to the correct dimensions. Note that this is
rebuilding a boolean image **itself** from boolean values. The mask
is in no way interpreted in performing the operation, in contrast to
MaskedImage, where only the masked region is used in from_vector()
and as_vector(). Any image landmarks are transferred in the process.
Parameters
----------
flattened : (``n_pixels``,) np.bool ndarray
A flattened vector of all the pixels of a BooleanImage.
Returns
-------
image : :class:`BooleanImage`
New BooleanImage of same shape as this image
"""
mask = BooleanImage(flattened.reshape(self.shape))
mask.landmarks = self.landmarks
return mask
def invert(self):
r"""
Inverts the current mask in place, setting all True values to False,
and all False values to True.
"""
self.pixels = ~self.pixels
def inverted_copy(self):
r"""
Returns a copy of this Boolean image, which is inverted.
Returns
-------
inverted_image: :class:`BooleanNSImage`
An inverted copy of this boolean image.
"""
inverse = deepcopy(self)
inverse.invert()
return inverse
def bounds_true(self, boundary=0, constrain_to_bounds=True):
r"""
Returns the minimum to maximum indices along all dimensions that the
mask includes which fully surround the True mask values. In the case
of a 2D Image for instance, the min and max define two corners of a
rectangle bounding the True pixel values.
Parameters
----------
boundary : int, optional
A number of pixels that should be added to the extent. A
negative value can be used to shrink the bounds in.
Default: 0
constrain_to_bounds: bool, optional
If True, the bounding extent is snapped to not go beyond
the edge of the image. If False, the bounds are left unchanged.
Default: True
Returns
--------
min_b : (D,) ndarray
The minimum extent of the True mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
max_b : (D,) ndarray
The maximum extent of the True mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
"""
mpi = self.true_indices
maxes = np.max(mpi, axis=0) + boundary
mins = np.min(mpi, axis=0) - boundary
if constrain_to_bounds:
maxes = self.constrain_points_to_bounds(maxes)
mins = self.constrain_points_to_bounds(mins)
return mins, maxes
def bounds_false(self, boundary=0, constrain_to_bounds=True):
r"""
Returns the minimum to maximum indices along all dimensions that the
mask includes which fully surround the False mask values. In the case
of a 2D Image for instance, the min and max define two corners of a
rectangle bounding the False pixel values.
Parameters
----------
boundary : int >= 0, optional
A number of pixels that should be added to the extent. A
negative value can be used to shrink the bounds in.
Default: 0
constrain_to_bounds: bool, optional
If True, the bounding extent is snapped to not go beyond
the edge of the image. If False, the bounds are left unchanged.
Default: True
Returns
--------
min_b : (D,) ndarray
The minimum extent of the False mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
max_b : (D,) ndarray
The maximum extent of the False mask region with the boundary
along each dimension. If constrain_to_bounds was True,
is clipped to legal image bounds.
"""
return self.inverted_copy().bounds_true(
boundary=boundary, constrain_to_bounds=constrain_to_bounds)
def warp_to(self, template_mask, transform, warp_landmarks=False,
interpolator='scipy', **kwargs):
r"""
Warps this BooleanImage into a different reference space.
Parameters
----------
template_mask : :class:`menpo.image.boolean.BooleanImage`
Defines the shape of the result, and what pixels should be
sampled.
transform : :class:`menpo.transform.base.Transform`
Transform **from the template space back to this image**.
Defines, for each True pixel location on the template, which pixel
location should be sampled from on this image.
warp_landmarks : bool, optional
If ``True``, warped_image will have the same landmark dictionary
as self, but with each landmark updated to the warped position.
Default: ``False``
interpolator : 'scipy' or 'c', optional
The interpolator that should be used to perform the warp.
Default: 'scipy'
kwargs : dict
Passed through to the interpolator. See `menpo.interpolation`
for details.
Returns
-------
warped_image : type(self)
A copy of this image, warped.
"""
# enforce the order as 0, for this boolean data, then call super
manually_set_order = kwargs.get('order', 0)
if manually_set_order != 0:
|
kwargs['order'] = 0
return Image.warp_to(self, template_mask, transform,
warp_landmarks=warp_landmarks,
interpolator=interpolator, **kwargs)
def _build_warped_image(self, template_mask, sampled_pixel_values,
**kwargs):
r"""
Builds the warped image from the template mask and
sampled pixel values. Overridden for BooleanImage as we can't use
the usual from_vector_inplace method.
"""
warped_image = BooleanImage.blank(template_mask.shape)
# As we are a mask image, we have to implement the update a little
# more manually than other image classes.
warped_image.pixels[warped_image.mask] = sampled_pixel_values
return warped_image
| raise ValueError(
"The order of the interpolation on a boolean image has to be "
"0 (attempted to set {})".format(manually_set_order)) | conditional_block |
client_compatibility_produce_consume_test.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ducktape.mark import parametrize
from ducktape.utils.util import wait_until
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.console_consumer import ConsoleConsumer
from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest
from kafkatest.utils import is_int_with_prefix
from kafkatest.version import DEV_BRANCH, LATEST_0_10_0, LATEST_0_10_1, LATEST_0_10_2, LATEST_0_11_0, LATEST_1_0, LATEST_1_1, LATEST_2_0, LATEST_2_1, LATEST_2_2, LATEST_2_3, LATEST_2_4, KafkaVersion
class | (ProduceConsumeValidateTest):
"""
These tests validate that we can use a new client to produce and consume from older brokers.
"""
def __init__(self, test_context):
""":type test_context: ducktape.tests.test.TestContext"""
super(ClientCompatibilityProduceConsumeTest, self).__init__(test_context=test_context)
self.topic = "test_topic"
self.zk = ZookeeperService(test_context, num_nodes=3)
self.kafka = KafkaService(test_context, num_nodes=3, zk=self.zk, topics={self.topic:{
"partitions": 10,
"replication-factor": 2}})
self.num_partitions = 10
self.timeout_sec = 60
self.producer_throughput = 1000
self.num_producers = 2
self.messages_per_producer = 1000
self.num_consumers = 1
def setUp(self):
self.zk.start()
def min_cluster_size(self):
# Override this since we're adding services outside of the constructor
return super(ClientCompatibilityProduceConsumeTest, self).min_cluster_size() + self.num_producers + self.num_consumers
@parametrize(broker_version=str(DEV_BRANCH))
@parametrize(broker_version=str(LATEST_0_10_0))
@parametrize(broker_version=str(LATEST_0_10_1))
@parametrize(broker_version=str(LATEST_0_10_2))
@parametrize(broker_version=str(LATEST_0_11_0))
@parametrize(broker_version=str(LATEST_1_0))
@parametrize(broker_version=str(LATEST_1_1))
@parametrize(broker_version=str(LATEST_2_0))
@parametrize(broker_version=str(LATEST_2_1))
@parametrize(broker_version=str(LATEST_2_2))
@parametrize(broker_version=str(LATEST_2_3))
@parametrize(broker_version=str(LATEST_2_4))
def test_produce_consume(self, broker_version):
print("running producer_consumer_compat with broker_version = %s" % broker_version)
self.kafka.set_version(KafkaVersion(broker_version))
self.kafka.security_protocol = "PLAINTEXT"
self.kafka.interbroker_security_protocol = self.kafka.security_protocol
self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka,
self.topic, throughput=self.producer_throughput,
message_validator=is_int_with_prefix)
self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka, self.topic,
consumer_timeout_ms=60000,
message_validator=is_int_with_prefix)
self.kafka.start()
self.run_produce_consume_validate(lambda: wait_until(
lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True,
timeout_sec=120, backoff_sec=1,
err_msg="Producer did not produce all messages in reasonable amount of time"))
| ClientCompatibilityProduceConsumeTest | identifier_name |
client_compatibility_produce_consume_test.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ducktape.mark import parametrize
from ducktape.utils.util import wait_until
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.console_consumer import ConsoleConsumer
from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest
from kafkatest.utils import is_int_with_prefix
from kafkatest.version import DEV_BRANCH, LATEST_0_10_0, LATEST_0_10_1, LATEST_0_10_2, LATEST_0_11_0, LATEST_1_0, LATEST_1_1, LATEST_2_0, LATEST_2_1, LATEST_2_2, LATEST_2_3, LATEST_2_4, KafkaVersion
class ClientCompatibilityProduceConsumeTest(ProduceConsumeValidateTest):
"""
These tests validate that we can use a new client to produce and consume from older brokers.
"""
def __init__(self, test_context):
""":type test_context: ducktape.tests.test.TestContext"""
super(ClientCompatibilityProduceConsumeTest, self).__init__(test_context=test_context)
self.topic = "test_topic"
self.zk = ZookeeperService(test_context, num_nodes=3)
self.kafka = KafkaService(test_context, num_nodes=3, zk=self.zk, topics={self.topic:{
"partitions": 10,
"replication-factor": 2}})
self.num_partitions = 10
self.timeout_sec = 60
self.producer_throughput = 1000
self.num_producers = 2
self.messages_per_producer = 1000
self.num_consumers = 1
def setUp(self):
self.zk.start()
def min_cluster_size(self):
# Override this since we're adding services outside of the constructor
return super(ClientCompatibilityProduceConsumeTest, self).min_cluster_size() + self.num_producers + self.num_consumers
@parametrize(broker_version=str(DEV_BRANCH))
@parametrize(broker_version=str(LATEST_0_10_0))
@parametrize(broker_version=str(LATEST_0_10_1))
@parametrize(broker_version=str(LATEST_0_10_2))
@parametrize(broker_version=str(LATEST_0_11_0))
@parametrize(broker_version=str(LATEST_1_0))
@parametrize(broker_version=str(LATEST_1_1))
@parametrize(broker_version=str(LATEST_2_0))
@parametrize(broker_version=str(LATEST_2_1))
@parametrize(broker_version=str(LATEST_2_2))
@parametrize(broker_version=str(LATEST_2_3))
@parametrize(broker_version=str(LATEST_2_4))
def test_produce_consume(self, broker_version):
print("running producer_consumer_compat with broker_version = %s" % broker_version)
self.kafka.set_version(KafkaVersion(broker_version))
self.kafka.security_protocol = "PLAINTEXT"
self.kafka.interbroker_security_protocol = self.kafka.security_protocol
self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka,
self.topic, throughput=self.producer_throughput,
message_validator=is_int_with_prefix)
self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka, self.topic,
consumer_timeout_ms=60000,
message_validator=is_int_with_prefix)
self.kafka.start() | self.run_produce_consume_validate(lambda: wait_until(
lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True,
timeout_sec=120, backoff_sec=1,
err_msg="Producer did not produce all messages in reasonable amount of time")) | random_line_split | |
client_compatibility_produce_consume_test.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ducktape.mark import parametrize
from ducktape.utils.util import wait_until
from kafkatest.services.zookeeper import ZookeeperService
from kafkatest.services.kafka import KafkaService
from kafkatest.services.verifiable_producer import VerifiableProducer
from kafkatest.services.console_consumer import ConsoleConsumer
from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest
from kafkatest.utils import is_int_with_prefix
from kafkatest.version import DEV_BRANCH, LATEST_0_10_0, LATEST_0_10_1, LATEST_0_10_2, LATEST_0_11_0, LATEST_1_0, LATEST_1_1, LATEST_2_0, LATEST_2_1, LATEST_2_2, LATEST_2_3, LATEST_2_4, KafkaVersion
class ClientCompatibilityProduceConsumeTest(ProduceConsumeValidateTest):
"""
These tests validate that we can use a new client to produce and consume from older brokers.
"""
def __init__(self, test_context):
|
def setUp(self):
self.zk.start()
def min_cluster_size(self):
# Override this since we're adding services outside of the constructor
return super(ClientCompatibilityProduceConsumeTest, self).min_cluster_size() + self.num_producers + self.num_consumers
@parametrize(broker_version=str(DEV_BRANCH))
@parametrize(broker_version=str(LATEST_0_10_0))
@parametrize(broker_version=str(LATEST_0_10_1))
@parametrize(broker_version=str(LATEST_0_10_2))
@parametrize(broker_version=str(LATEST_0_11_0))
@parametrize(broker_version=str(LATEST_1_0))
@parametrize(broker_version=str(LATEST_1_1))
@parametrize(broker_version=str(LATEST_2_0))
@parametrize(broker_version=str(LATEST_2_1))
@parametrize(broker_version=str(LATEST_2_2))
@parametrize(broker_version=str(LATEST_2_3))
@parametrize(broker_version=str(LATEST_2_4))
def test_produce_consume(self, broker_version):
print("running producer_consumer_compat with broker_version = %s" % broker_version)
self.kafka.set_version(KafkaVersion(broker_version))
self.kafka.security_protocol = "PLAINTEXT"
self.kafka.interbroker_security_protocol = self.kafka.security_protocol
self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka,
self.topic, throughput=self.producer_throughput,
message_validator=is_int_with_prefix)
self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka, self.topic,
consumer_timeout_ms=60000,
message_validator=is_int_with_prefix)
self.kafka.start()
self.run_produce_consume_validate(lambda: wait_until(
lambda: self.producer.each_produced_at_least(self.messages_per_producer) == True,
timeout_sec=120, backoff_sec=1,
err_msg="Producer did not produce all messages in reasonable amount of time"))
| """:type test_context: ducktape.tests.test.TestContext"""
super(ClientCompatibilityProduceConsumeTest, self).__init__(test_context=test_context)
self.topic = "test_topic"
self.zk = ZookeeperService(test_context, num_nodes=3)
self.kafka = KafkaService(test_context, num_nodes=3, zk=self.zk, topics={self.topic:{
"partitions": 10,
"replication-factor": 2}})
self.num_partitions = 10
self.timeout_sec = 60
self.producer_throughput = 1000
self.num_producers = 2
self.messages_per_producer = 1000
self.num_consumers = 1 | identifier_body |
ie_history.py | #!/usr/bin/env python
# Copyright 2011 Google Inc. All Rights Reserved.
"""Parser for IE index.dat files.
Note that this is a very naive and incomplete implementation and should be
replaced with a more intelligent one. Do not implement anything based on this
code, it is a placeholder for something real.
For anyone who wants a useful reference, see this:
http://heanet.dl.sourceforge.net/project/libmsiecf/Documentation/MSIE%20Cache%20
File%20format/MSIE%20Cache%20File%20%28index.dat%29%20format.pdf
"""
import datetime
import glob
import operator
import os
import struct
import sys
import urlparse
import logging
from grr.lib import parsers
from grr.lib import rdfvalue
# Difference between 1 Jan 1601 and 1 Jan 1970.
WIN_UNIX_DIFF_MSECS = 11644473600 * 1e6
class IEHistoryParser(parsers.FileParser):
"""Parse IE index.dat files into BrowserHistoryItem objects."""
output_types = ["BrowserHistoryItem"]
supported_artifacts = ["InternetExplorerHistory"]
def Parse(self, stat, file_object, knowledge_base):
"""Parse the History file."""
_, _ = stat, knowledge_base
# TODO(user): Convert this to use the far more intelligent plaso parser.
ie = IEParser(file_object)
for dat in ie.Parse():
yield rdfvalue.BrowserHistoryItem(
url=dat["url"], domain=urlparse.urlparse(dat["url"]).netloc,
access_time=dat.get("mtime"),
program_name="Internet Explorer", source_urn=stat.aff4path)
class IEParser(object):
"""Parser object for index.dat files.
The file format for IE index.dat files is somewhat poorly documented.
The following implementation is based on information from:
http://www.forensicswiki.org/wiki/Internet_Explorer_History_File_Format
Returns results in chronological order based on mtime
"""
FILE_HEADER = "Client UrlCache MMF Ver 5.2"
BLOCK_SIZE = 0x80
def __init__(self, input_obj):
"""Initialize.
Args:
input_obj: A file like object to read the index.dat from.
"""
self._file = input_obj
self._entries = []
def Parse(self):
"""Parse the file."""
if not self._file:
logging.error("Couldn't open file")
return
# Limit read size to 5MB.
self.input_dat = self._file.read(1024 * 1024 * 5)
if not self.input_dat.startswith(self.FILE_HEADER):
logging.error("Invalid index.dat file %s", self._file)
return
# Events aren't time ordered in the history file, so we collect them all
# then sort.
events = []
for event in self._DoParse():
events.append(event)
for event in sorted(events, key=operator.itemgetter("mtime")):
yield event
def _GetRecord(self, offset, record_size):
"""Retrieve a single record from the file.
Args:
offset: offset from start of input_dat where header starts | record_size: length of the header according to file (untrusted)
Returns:
A dict containing a single browser history record.
"""
record_header = "<4sLQQL"
get4 = lambda x: struct.unpack("<L", self.input_dat[x:x+4])[0]
url_offset = struct.unpack("B", self.input_dat[offset+52:offset+53])[0]
if url_offset in [0xFF, 0xFE]:
return None
data_offset = get4(offset + 68)
data_size = get4(offset + 72)
start_pos = offset + data_offset
data = struct.unpack("{0}s".format(data_size),
self.input_dat[start_pos:start_pos + data_size])[0]
fmt = record_header
unknown_size = url_offset - struct.calcsize(fmt)
fmt += "{0}s".format(unknown_size)
fmt += "{0}s".format(record_size - struct.calcsize(fmt))
dat = struct.unpack(fmt, self.input_dat[offset:offset+record_size])
header, blocks, mtime, ctime, ftime, _, url = dat
url = url.split(chr(0x00))[0]
if mtime: mtime = mtime/10 - WIN_UNIX_DIFF_MSECS
if ctime: ctime = ctime/10 - WIN_UNIX_DIFF_MSECS
return {"header": header, # the header
"blocks": blocks, # number of blocks
"urloffset": url_offset, # offset of URL in file
"data_offset": data_offset, # offset for start of data
"data_size": data_size, # size of data
"data": data, # actual data
"mtime": mtime, # modified time
"ctime": ctime, # created time
"ftime": ftime, # file time
"url": url # the url visited
}
def _DoParse(self):
"""Parse a file for history records yielding dicts.
Yields:
Dicts containing browser history
"""
get4 = lambda x: struct.unpack("<L", self.input_dat[x:x+4])[0]
filesize = get4(0x1c)
offset = get4(0x20)
coffset = offset
while coffset < filesize:
etype = struct.unpack("4s", self.input_dat[coffset:coffset + 4])[0]
if etype == "REDR":
pass
elif etype in ["URL "]:
# Found a valid record
reclen = get4(coffset + 4) * self.BLOCK_SIZE
yield self._GetRecord(coffset, reclen)
coffset += self.BLOCK_SIZE
def main(argv):
if len(argv) < 2:
print "Usage: {0} index.dat".format(os.path.basename(argv[0]))
else:
files_to_process = []
for input_glob in argv[1:]:
files_to_process += glob.glob(input_glob)
for input_file in files_to_process:
ie = IEParser(open(input_file))
for dat in ie.Parse():
dat["ctime"] = datetime.datetime.utcfromtimestamp(dat["ctime"]/1e6)
print "{ctime} {header} {url}".format(**dat)
if __name__ == "__main__":
main(sys.argv) | random_line_split | |
ie_history.py | #!/usr/bin/env python
# Copyright 2011 Google Inc. All Rights Reserved.
"""Parser for IE index.dat files.
Note that this is a very naive and incomplete implementation and should be
replaced with a more intelligent one. Do not implement anything based on this
code, it is a placeholder for something real.
For anyone who wants a useful reference, see this:
http://heanet.dl.sourceforge.net/project/libmsiecf/Documentation/MSIE%20Cache%20
File%20format/MSIE%20Cache%20File%20%28index.dat%29%20format.pdf
"""
import datetime
import glob
import operator
import os
import struct
import sys
import urlparse
import logging
from grr.lib import parsers
from grr.lib import rdfvalue
# Difference between 1 Jan 1601 and 1 Jan 1970.
WIN_UNIX_DIFF_MSECS = 11644473600 * 1e6
class IEHistoryParser(parsers.FileParser):
"""Parse IE index.dat files into BrowserHistoryItem objects."""
output_types = ["BrowserHistoryItem"]
supported_artifacts = ["InternetExplorerHistory"]
def Parse(self, stat, file_object, knowledge_base):
"""Parse the History file."""
_, _ = stat, knowledge_base
# TODO(user): Convert this to use the far more intelligent plaso parser.
ie = IEParser(file_object)
for dat in ie.Parse():
yield rdfvalue.BrowserHistoryItem(
url=dat["url"], domain=urlparse.urlparse(dat["url"]).netloc,
access_time=dat.get("mtime"),
program_name="Internet Explorer", source_urn=stat.aff4path)
class IEParser(object):
"""Parser object for index.dat files.
The file format for IE index.dat files is somewhat poorly documented.
The following implementation is based on information from:
http://www.forensicswiki.org/wiki/Internet_Explorer_History_File_Format
Returns results in chronological order based on mtime
"""
FILE_HEADER = "Client UrlCache MMF Ver 5.2"
BLOCK_SIZE = 0x80
def __init__(self, input_obj):
"""Initialize.
Args:
input_obj: A file like object to read the index.dat from.
"""
self._file = input_obj
self._entries = []
def Parse(self):
"""Parse the file."""
if not self._file:
logging.error("Couldn't open file")
return
# Limit read size to 5MB.
self.input_dat = self._file.read(1024 * 1024 * 5)
if not self.input_dat.startswith(self.FILE_HEADER):
logging.error("Invalid index.dat file %s", self._file)
return
# Events aren't time ordered in the history file, so we collect them all
# then sort.
events = []
for event in self._DoParse():
events.append(event)
for event in sorted(events, key=operator.itemgetter("mtime")):
yield event
def _GetRecord(self, offset, record_size):
"""Retrieve a single record from the file.
Args:
offset: offset from start of input_dat where header starts
record_size: length of the header according to file (untrusted)
Returns:
A dict containing a single browser history record.
"""
record_header = "<4sLQQL"
get4 = lambda x: struct.unpack("<L", self.input_dat[x:x+4])[0]
url_offset = struct.unpack("B", self.input_dat[offset+52:offset+53])[0]
if url_offset in [0xFF, 0xFE]:
return None
data_offset = get4(offset + 68)
data_size = get4(offset + 72)
start_pos = offset + data_offset
data = struct.unpack("{0}s".format(data_size),
self.input_dat[start_pos:start_pos + data_size])[0]
fmt = record_header
unknown_size = url_offset - struct.calcsize(fmt)
fmt += "{0}s".format(unknown_size)
fmt += "{0}s".format(record_size - struct.calcsize(fmt))
dat = struct.unpack(fmt, self.input_dat[offset:offset+record_size])
header, blocks, mtime, ctime, ftime, _, url = dat
url = url.split(chr(0x00))[0]
if mtime: mtime = mtime/10 - WIN_UNIX_DIFF_MSECS
if ctime: ctime = ctime/10 - WIN_UNIX_DIFF_MSECS
return {"header": header, # the header
"blocks": blocks, # number of blocks
"urloffset": url_offset, # offset of URL in file
"data_offset": data_offset, # offset for start of data
"data_size": data_size, # size of data
"data": data, # actual data
"mtime": mtime, # modified time
"ctime": ctime, # created time
"ftime": ftime, # file time
"url": url # the url visited
}
def _DoParse(self):
"""Parse a file for history records yielding dicts.
Yields:
Dicts containing browser history
"""
get4 = lambda x: struct.unpack("<L", self.input_dat[x:x+4])[0]
filesize = get4(0x1c)
offset = get4(0x20)
coffset = offset
while coffset < filesize:
etype = struct.unpack("4s", self.input_dat[coffset:coffset + 4])[0]
if etype == "REDR":
pass
elif etype in ["URL "]:
# Found a valid record
reclen = get4(coffset + 4) * self.BLOCK_SIZE
yield self._GetRecord(coffset, reclen)
coffset += self.BLOCK_SIZE
def main(argv):
if len(argv) < 2:
print "Usage: {0} index.dat".format(os.path.basename(argv[0]))
else:
files_to_process = []
for input_glob in argv[1:]:
files_to_process += glob.glob(input_glob)
for input_file in files_to_process:
|
if __name__ == "__main__":
main(sys.argv)
| ie = IEParser(open(input_file))
for dat in ie.Parse():
dat["ctime"] = datetime.datetime.utcfromtimestamp(dat["ctime"]/1e6)
print "{ctime} {header} {url}".format(**dat) | conditional_block |
ie_history.py | #!/usr/bin/env python
# Copyright 2011 Google Inc. All Rights Reserved.
"""Parser for IE index.dat files.
Note that this is a very naive and incomplete implementation and should be
replaced with a more intelligent one. Do not implement anything based on this
code, it is a placeholder for something real.
For anyone who wants a useful reference, see this:
http://heanet.dl.sourceforge.net/project/libmsiecf/Documentation/MSIE%20Cache%20
File%20format/MSIE%20Cache%20File%20%28index.dat%29%20format.pdf
"""
import datetime
import glob
import operator
import os
import struct
import sys
import urlparse
import logging
from grr.lib import parsers
from grr.lib import rdfvalue
# Difference between 1 Jan 1601 and 1 Jan 1970.
WIN_UNIX_DIFF_MSECS = 11644473600 * 1e6
class IEHistoryParser(parsers.FileParser):
"""Parse IE index.dat files into BrowserHistoryItem objects."""
output_types = ["BrowserHistoryItem"]
supported_artifacts = ["InternetExplorerHistory"]
def Parse(self, stat, file_object, knowledge_base):
"""Parse the History file."""
_, _ = stat, knowledge_base
# TODO(user): Convert this to use the far more intelligent plaso parser.
ie = IEParser(file_object)
for dat in ie.Parse():
yield rdfvalue.BrowserHistoryItem(
url=dat["url"], domain=urlparse.urlparse(dat["url"]).netloc,
access_time=dat.get("mtime"),
program_name="Internet Explorer", source_urn=stat.aff4path)
class | (object):
"""Parser object for index.dat files.
The file format for IE index.dat files is somewhat poorly documented.
The following implementation is based on information from:
http://www.forensicswiki.org/wiki/Internet_Explorer_History_File_Format
Returns results in chronological order based on mtime
"""
FILE_HEADER = "Client UrlCache MMF Ver 5.2"
BLOCK_SIZE = 0x80
def __init__(self, input_obj):
"""Initialize.
Args:
input_obj: A file like object to read the index.dat from.
"""
self._file = input_obj
self._entries = []
def Parse(self):
"""Parse the file."""
if not self._file:
logging.error("Couldn't open file")
return
# Limit read size to 5MB.
self.input_dat = self._file.read(1024 * 1024 * 5)
if not self.input_dat.startswith(self.FILE_HEADER):
logging.error("Invalid index.dat file %s", self._file)
return
# Events aren't time ordered in the history file, so we collect them all
# then sort.
events = []
for event in self._DoParse():
events.append(event)
for event in sorted(events, key=operator.itemgetter("mtime")):
yield event
def _GetRecord(self, offset, record_size):
"""Retrieve a single record from the file.
Args:
offset: offset from start of input_dat where header starts
record_size: length of the header according to file (untrusted)
Returns:
A dict containing a single browser history record.
"""
record_header = "<4sLQQL"
get4 = lambda x: struct.unpack("<L", self.input_dat[x:x+4])[0]
url_offset = struct.unpack("B", self.input_dat[offset+52:offset+53])[0]
if url_offset in [0xFF, 0xFE]:
return None
data_offset = get4(offset + 68)
data_size = get4(offset + 72)
start_pos = offset + data_offset
data = struct.unpack("{0}s".format(data_size),
self.input_dat[start_pos:start_pos + data_size])[0]
fmt = record_header
unknown_size = url_offset - struct.calcsize(fmt)
fmt += "{0}s".format(unknown_size)
fmt += "{0}s".format(record_size - struct.calcsize(fmt))
dat = struct.unpack(fmt, self.input_dat[offset:offset+record_size])
header, blocks, mtime, ctime, ftime, _, url = dat
url = url.split(chr(0x00))[0]
if mtime: mtime = mtime/10 - WIN_UNIX_DIFF_MSECS
if ctime: ctime = ctime/10 - WIN_UNIX_DIFF_MSECS
return {"header": header, # the header
"blocks": blocks, # number of blocks
"urloffset": url_offset, # offset of URL in file
"data_offset": data_offset, # offset for start of data
"data_size": data_size, # size of data
"data": data, # actual data
"mtime": mtime, # modified time
"ctime": ctime, # created time
"ftime": ftime, # file time
"url": url # the url visited
}
def _DoParse(self):
"""Parse a file for history records yielding dicts.
Yields:
Dicts containing browser history
"""
get4 = lambda x: struct.unpack("<L", self.input_dat[x:x+4])[0]
filesize = get4(0x1c)
offset = get4(0x20)
coffset = offset
while coffset < filesize:
etype = struct.unpack("4s", self.input_dat[coffset:coffset + 4])[0]
if etype == "REDR":
pass
elif etype in ["URL "]:
# Found a valid record
reclen = get4(coffset + 4) * self.BLOCK_SIZE
yield self._GetRecord(coffset, reclen)
coffset += self.BLOCK_SIZE
def main(argv):
if len(argv) < 2:
print "Usage: {0} index.dat".format(os.path.basename(argv[0]))
else:
files_to_process = []
for input_glob in argv[1:]:
files_to_process += glob.glob(input_glob)
for input_file in files_to_process:
ie = IEParser(open(input_file))
for dat in ie.Parse():
dat["ctime"] = datetime.datetime.utcfromtimestamp(dat["ctime"]/1e6)
print "{ctime} {header} {url}".format(**dat)
if __name__ == "__main__":
main(sys.argv)
| IEParser | identifier_name |
ie_history.py | #!/usr/bin/env python
# Copyright 2011 Google Inc. All Rights Reserved.
"""Parser for IE index.dat files.
Note that this is a very naive and incomplete implementation and should be
replaced with a more intelligent one. Do not implement anything based on this
code, it is a placeholder for something real.
For anyone who wants a useful reference, see this:
http://heanet.dl.sourceforge.net/project/libmsiecf/Documentation/MSIE%20Cache%20
File%20format/MSIE%20Cache%20File%20%28index.dat%29%20format.pdf
"""
import datetime
import glob
import operator
import os
import struct
import sys
import urlparse
import logging
from grr.lib import parsers
from grr.lib import rdfvalue
# Difference between 1 Jan 1601 and 1 Jan 1970.
WIN_UNIX_DIFF_MSECS = 11644473600 * 1e6
class IEHistoryParser(parsers.FileParser):
"""Parse IE index.dat files into BrowserHistoryItem objects."""
output_types = ["BrowserHistoryItem"]
supported_artifacts = ["InternetExplorerHistory"]
def Parse(self, stat, file_object, knowledge_base):
"""Parse the History file."""
_, _ = stat, knowledge_base
# TODO(user): Convert this to use the far more intelligent plaso parser.
ie = IEParser(file_object)
for dat in ie.Parse():
yield rdfvalue.BrowserHistoryItem(
url=dat["url"], domain=urlparse.urlparse(dat["url"]).netloc,
access_time=dat.get("mtime"),
program_name="Internet Explorer", source_urn=stat.aff4path)
class IEParser(object):
"""Parser object for index.dat files.
The file format for IE index.dat files is somewhat poorly documented.
The following implementation is based on information from:
http://www.forensicswiki.org/wiki/Internet_Explorer_History_File_Format
Returns results in chronological order based on mtime
"""
FILE_HEADER = "Client UrlCache MMF Ver 5.2"
BLOCK_SIZE = 0x80
def __init__(self, input_obj):
"""Initialize.
Args:
input_obj: A file like object to read the index.dat from.
"""
self._file = input_obj
self._entries = []
def Parse(self):
"""Parse the file."""
if not self._file:
logging.error("Couldn't open file")
return
# Limit read size to 5MB.
self.input_dat = self._file.read(1024 * 1024 * 5)
if not self.input_dat.startswith(self.FILE_HEADER):
logging.error("Invalid index.dat file %s", self._file)
return
# Events aren't time ordered in the history file, so we collect them all
# then sort.
events = []
for event in self._DoParse():
events.append(event)
for event in sorted(events, key=operator.itemgetter("mtime")):
yield event
def _GetRecord(self, offset, record_size):
"""Retrieve a single record from the file.
Args:
offset: offset from start of input_dat where header starts
record_size: length of the header according to file (untrusted)
Returns:
A dict containing a single browser history record.
"""
record_header = "<4sLQQL"
get4 = lambda x: struct.unpack("<L", self.input_dat[x:x+4])[0]
url_offset = struct.unpack("B", self.input_dat[offset+52:offset+53])[0]
if url_offset in [0xFF, 0xFE]:
return None
data_offset = get4(offset + 68)
data_size = get4(offset + 72)
start_pos = offset + data_offset
data = struct.unpack("{0}s".format(data_size),
self.input_dat[start_pos:start_pos + data_size])[0]
fmt = record_header
unknown_size = url_offset - struct.calcsize(fmt)
fmt += "{0}s".format(unknown_size)
fmt += "{0}s".format(record_size - struct.calcsize(fmt))
dat = struct.unpack(fmt, self.input_dat[offset:offset+record_size])
header, blocks, mtime, ctime, ftime, _, url = dat
url = url.split(chr(0x00))[0]
if mtime: mtime = mtime/10 - WIN_UNIX_DIFF_MSECS
if ctime: ctime = ctime/10 - WIN_UNIX_DIFF_MSECS
return {"header": header, # the header
"blocks": blocks, # number of blocks
"urloffset": url_offset, # offset of URL in file
"data_offset": data_offset, # offset for start of data
"data_size": data_size, # size of data
"data": data, # actual data
"mtime": mtime, # modified time
"ctime": ctime, # created time
"ftime": ftime, # file time
"url": url # the url visited
}
def _DoParse(self):
|
def main(argv):
if len(argv) < 2:
print "Usage: {0} index.dat".format(os.path.basename(argv[0]))
else:
files_to_process = []
for input_glob in argv[1:]:
files_to_process += glob.glob(input_glob)
for input_file in files_to_process:
ie = IEParser(open(input_file))
for dat in ie.Parse():
dat["ctime"] = datetime.datetime.utcfromtimestamp(dat["ctime"]/1e6)
print "{ctime} {header} {url}".format(**dat)
if __name__ == "__main__":
main(sys.argv)
| """Parse a file for history records yielding dicts.
Yields:
Dicts containing browser history
"""
get4 = lambda x: struct.unpack("<L", self.input_dat[x:x+4])[0]
filesize = get4(0x1c)
offset = get4(0x20)
coffset = offset
while coffset < filesize:
etype = struct.unpack("4s", self.input_dat[coffset:coffset + 4])[0]
if etype == "REDR":
pass
elif etype in ["URL "]:
# Found a valid record
reclen = get4(coffset + 4) * self.BLOCK_SIZE
yield self._GetRecord(coffset, reclen)
coffset += self.BLOCK_SIZE | identifier_body |
economy.js | /**
* Economy
* Gold Server - http://gold.psim.us/
*
* Deals with economy commands, mostly.
* Functions for a lot of this can be found in: ./chat-plugins/goldusers.js
*
* @license MIT license
*/
'use strict';
const fs = require('fs');
let prices;
exports.commands = {
shop: function (target, room, user) {
if (!this.runBroadcast()) return;
if (room.id === 'lobby' && this.broadcasting) {
return this.sendReplyBox('<center>Click <button name="send" value="/shop" style="background-color: black; font-color: white;" title="Enter the Shop!"><font color="white"><b>here</button></b></font> to enter our shop!');
} else {
updatePrices();
let topStyle = 'background: linear-gradient(10deg, #FFF8B5, #eadf7c, #FFF8B5); color: black; border: 1px solid #635b00; padding: 2px; border-radius: 5px;';
let top = '<center><h3><b><u>Gold Bucks Shop</u></b></h3><table style="' + topStyle + '" border="1" cellspacing ="2" cellpadding="3"><tr><th>Item</th><th>Description</th><th>Cost</th></tr>';
let bottom = '</table><br /><b>Prices in the shop go up and down automatically depending on the amount of bucks the average user has at that given time.</b><br />To buy an item from the shop, click the respective button for said item.<br>Do /getbucks to learn more about how to obtain bucks. </center>';
return this.sendReply('|raw|' +
top +
shopTable("Symbol", "Buys a custom symbol to go infront of name and puts you towards the top of userlist (lasts 2 hrs from logout)", prices['symbol']) +
// shopTable("Declare", "Advertisement declare for a room on the server from an Administrator / Leader.", prices['declare']) +
shopTable("Fix", "Ability to modify a custom avatar, trainer card, or userlist icon.", prices['fix']) +
shopTable("Custom", "Buys a custom avatar to be applied to your name (you supply)", prices['custom']) +
shopTable("Animated", "Buys an animated avatar to be applied to your name (you supply)", prices['animated']) +
shopTable("Room", "Buys a public unofficial chat room - will be deleted if inactive. Must have a valid purpose; staff can reject making these.", prices['room']) +
shopTable("Musicbox", "A command that lists / links up to 8 of your favorite songs", prices['musicbox']) +
shopTable("Trainer", "Gives you a custom command - you provide the HTML and command name.", prices['trainer']) +
shopTable("Mystery Box", "Gives you a special surprise gift when you open it! (Could be good or bad!)", prices['pack']) +
shopTable("Emote", "A custom chat emoticon such as \"Kappa\" - must be 30x30", prices['emote']) +
shopTable("Color", "This gives your username a custom color on the userlist and in all rooms (existing at time of purchase)", prices['color']) +
shopTable("Icon", "This gives your username a custom userlist icon on our regular client - MUST be a Pokemon and has to be 32x32.", prices['icon']) +
shopTable("VIP Status", "Gives you the ability to change your custom symbol, avatar, custom color, and userlist icon as much as you wish, and it is also displayed in your profile.", prices['vip']) +
bottom
);
}
},
buy: function (target, room, user) {
updatePrices();
if (!target) return this.errorReply("You need to pick an item! Type /buy [item] to buy something.");
let parts = target.split(',');
let output = '';
let price;
function link(link, formatted) {
return '<a href="' + link + '" target="_blank">' + formatted + '</a>';
}
function | (price) {
if (Gold.readMoney(user.userid) < price) return false;
if (Gold.readMoney(user.userid) >= price) return true;
}
function alertStaff(message, staffRoom) {
Gold.pmUpperStaff('/raw ' + message, '~Server', false);
if (staffRoom) {
Rooms.get('staff').add('|raw|<b>' + message + '</b>');
Rooms.get('staff').update();
}
}
function processPurchase(price, item, desc) {
if (!desc) desc = '';
if (Gold.readMoney(user.userid) < price) return false; // this should never happen
Gold.updateMoney(user.userid, -price);
logTransaction(user.name + ' has purchased a(n) ' + item + '. ' + desc);
}
switch (toId(parts[0])) {
case 'symbol':
price = prices['symbol'];
if (Gold.hasVip(user.userid)) return this.errorReply("You are a VIP user - you do not need to buy custom symbols from the shop. Use /customsymbol to change your symbol.");
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
this.sendReply("You have purchased a custom symbol. You will have this until you log off for more than an hour.");
this.sendReply("Use /customsymbol [symbol] to change your symbol now!");
user.canCustomSymbol = true;
break;
case 'custom':
case 'avatar':
case 'customavatar':
price = prices['custom'];
if (Gold.hasVip(user.userid)) return this.errorReply("You are a VIP user - you do not need to buy avatars from the shop. Use /customavatar to change your avatar.");
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy avatar, [link to avatar]. Must be a PNG or JPG.");
let filepaths = ['.png', '.jpg'];
if (!~filepaths.indexOf(parts[1].substr(-4))) return this.errorReply("Your image for a regular custom avatar must be either a PNG or JPG. (If it is a valid file type, it will end in one of these)");
processPurchase(price, parts[0], 'Image: ' + parts[1]);
if (Config.customavatars[user.userid]) output = ' | <button name="send" value="/sca delete, ' + user.userid + '" target="_blank" title="Click this to remove current avatar.">Click2Remove</button>';
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom avatar. Image: ' + link(parts[1].replace(' ', ''), 'desired avatar'), true);
alertStaff('<center><img src="' + parts[1] + '" width="80" height="80"><br /><button name="send" value="/sca set, ' + toId(user.name) + ', ' + parts[1] + '" target="_blank" title="Click this to set the above custom avatar.">Click2Set</button> ' + output + '</center>', false);
this.sendReply("You have bought a custom avatar from the shop. The staff have been notified and will set it ASAP.");
break;
case 'color':
case 'customcolor':
price = prices['color'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy color, [hex code OR name of an alt you want the color of]");
if (parts[1].length > 20) return this.errorReply("This is not a valid color, try again.");
processPurchase(price, parts[0], parts[1]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom color. Color: ' + parts[1], true);
this.sendReply("You have purchased a custom color: " + parts[1] + " from the shop. Please screen capture this in case the staff do not get this message.");
break;
case 'emote':
case 'emoticon':
price = prices['emote'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1] || !parts[2]) return this.errorReply("Usage: /buy emote, [emote code], [image for the emote]");
let emoteFilepaths = ['.png', '.jpg', '.gif'];
if (!~emoteFilepaths.indexOf(parts[2].substr(-4))) return this.errorReply("Emoticons must be in one of the following formats: PNG, JPG, or GIF.");
if (Gold.emoticons.chatEmotes[parts[1].replace(' ', '')]) return this.errorReply("An emoticon with this trigger word already exists on this server.");
processPurchase(price, parts[0], 'Emote: ' + parts[1] + ' Link: ' + parts[2]);
alertStaff(Gold.nameColor(user.name, true) + " has purchased a custom emote. Emote \"" + parts[1].trim() + "\": " + link(parts[2].replace(' ', ''), 'desired emote'), true);
alertStaff('<center><img title=' + parts[1] + ' src=' + parts[2] + '><br /><button name="send" value="/emote add, ' + parts[1] + ', ' + parts[2] + '" target="_blank" title="Click to add the emoticon above.">Click2Add</button></center>', false);
this.sendReply("You have bought a custom emoticon from the shop. The staff have been notified and will add it ASAP.");
break;
case 'animated':
price = prices['animated'];
if (Gold.hasVip(user.userid)) return this.errorReply("You are a VIP user - you do not need to buy animated avatars from the shop. Use /customavatar to change your avatar.");
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy animated, [link to avatar]. Must be a GIF.");
if (parts[1].split('.').pop() !== 'gif') return this.errorReply("Your animated avatar must be a GIF. (If it's a GIF, the link will end in .gif)");
processPurchase(price, parts[0], 'Image: ' + parts[1]);
if (Config.customavatars[user.userid]) output = ' | <button name="send" value="/sca delete, ' + user.userid + '" target="_blank" title="Click this to remove current avatar.">Click2Remove</button>';
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom animated avatar. Image: ' + link(parts[1].replace(' ', ''), 'desired avatar'), true);
alertStaff('<center><img src="' + parts[1] + '" width="80" height="80"><br /><button name="send" value="/sca set, ' + toId(user.name) + ', ' + parts[1] + '" target="_blank" title="Click this to set the above custom avatar.">Click2Set</button> ' + output + '</center>', false);
this.sendReply("You have purchased a custom animated avatar. The staff have been notified and will add it ASAP.");
break;
case 'room':
case 'chatroom':
price = prices['room'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy room, [room name]");
let bannedRoomNames = [',', '|', '[', '-'];
if (~bannedRoomNames.indexOf(parts[1])) return this.errorReply("This room name is not valid, try again.");
processPurchase(price, parts[0], 'Room name: ' + parts[1]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a chat room. Room name: ' + parts[1], true);
this.sendReply("You have purchased a room. The staff have been notified and it will be created shortly as long as it meets our basic rules.");
break;
case 'trainer':
case 'trainercard':
price = prices['trainer'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a trainer card.', true);
this.sendReply("|html|You have purchased a trainer card. Please use <a href=http://goldservers.info/site/trainercard.html>this</a> to make your trainer card and then PM a leader or administrator the HTML with the command name you want it to have.");
break;
case 'mb':
case 'musicbox':
price = prices['musicbox'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!Gold.createMusicBox(user)) return this.errorReply("You already have a music box! There's no need to buy another.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a music box.', true);
Gold.createMusicBox(user); // give the user a music box
this.parse('/' + toId(parts[0]) + ' help');
this.sendReply("You have purchased a music box. You may have a maximum of 8 songs in it.");
break;
case 'fix':
price = prices['fix'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a fix from the shop.', true);
user.canFixItem = true;
this.sendReply("You have purchased a fix from the shop. You can use this to alter your trainer card, music box, or custom chat emoticon. PM a leader or administrator to proceed.");
break;
/*
case 'ad':
case 'declare':
price = prices['declare'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased the ability to declare from the shop.', true);
this.sendReply("You have purchased an advertisement declare from the shop. Please prepare an advertisement for your room; a leader or administrator will soon be PMing you to proceed.");
break;
*/
case 'userlisticon':
case 'icon':
price = prices['icon'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1] || parts[1].length < 3) return this.errorReply("Usage: /buy icon, [32x32 icon image]");
let iconFilepaths = ['.png', '.jpg', '.gif'];
if (!~iconFilepaths.indexOf(parts[1].substr(-4))) return this.errorReply("Your image for a custom userlist icon must be a PNG, JPG, or GIF.");
processPurchase(price, parts[0], 'Image: ' + parts[1]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom userlist icon. Image: ' + link(parts[1].replace(' ', ''), 'desired icon'), true);
alertStaff('<center><button name="send" value="/icon ' + user.userid + ', ' + parts[1] + '" target="_blank" title="Click this to set the above custom userlist icon.">Click2Set</button></center>', false);
this.sendReply("You have purchased a custom userlist icon. The staff have been notified and this will be added ASAP.");
break;
case 'vip':
case 'vipstatus':
price = prices['vip'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
Gold.modifyBadge(user.userid, 'vip', 'GIVE');
alertStaff(Gold.nameColor(user.name, true) + " has purchased VIP Status from the shop and they have recieved it automatically from the server.", true);
break;
case 'mysterybox':
case 'pack':
case 'magicpack':
price = prices['pack'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (room.id !== 'lobby') return this.errorReply("You must buy this item in the Lobby!");
processPurchase(price, parts[0]);
let randomNumber = Math.floor((Math.random() * 100) + 1);
let prize = '';
let goodBad = '';
let opts;
if (randomNumber < 70) {
goodBad = 'bad';
opts = ['nothing', 'rick rolled', 'meme avatar', 'kick from Lobby', '2 minute mute'];
prize = opts[Math.floor(Math.random() * opts.length)];
} else if (randomNumber > 70) {
goodBad = 'good';
opts = ['100 bucks', '125 bucks', 'a custom symbol', 'a custom userlist icon', 'ability to get Dubtrack VIP', 'ability to set the PotD', 'custom color', 'the cost of the mystery box back', 'ability to have a leader/admin broadcast an image to Lobby', 'a kind, warm hearted thank you'];
prize = opts[Math.floor(Math.random() * opts.length)];
}
switch (prize) {
// good
case '100 bucks':
Gold.updateMoney(user.userid, 100);
break;
case '125 bucks':
Gold.updateMoney(user.userid, 125);
break;
case 'the cost of the mystery box back':
Gold.updateMoney(user.userid, prices['pack']);
break;
case 'ability to get Dubtrack VIP':
case 'ability to have a leader/admin broadcast an image to Lobby':
case 'custom color':
case 'ability to set the PotD':
alertStaff(Gold.nameColor(user.name, true) + " has won an " + prize + ". Please PM them to proceed with giving them this.", true);
break;
case 'a custom symbol':
user.canCustomSymbol = true;
this.sendReply("Do /customsymbol [symbol] to set a FREE custom symbol! (Do /rs to reset your custom symbol when you want to remove it later.)");
break;
case 'a kind, warm hearted thank you':
this.sendReply("THANK U 8D!");
break;
case 'a custom userlist icon':
this.sendReply("PM a leader or administrator to claim this prize!");
break;
// bad
case 'nothing':
break;
case 'meme avatar':
opts = ['notpawn.png', 'notpawn2.png'];
user.avatar = opts[Math.floor(Math.random() * opts.length)];
break;
case 'kick from Lobby':
try {
user.leaveRoom('lobby');
user.popup("You have been kicked from the Lobby by the Mystery Box!");
} catch (e) {}
break;
case '2 minute mute':
try {
Rooms('lobby').mute(user, 2 * 60 * 1000, false);
} catch (e) {}
break;
case 'rick rolled':
Rooms('lobby').add("|raw|<blink>" +
"Never gonna give you up<br />" +
"Never gonna let you down<br />" +
"Never gonna run around and desert you<br />" +
"Never gonna make you cry<br />" +
"Never gonna say goodbye<br />" +
"Never gonna tell a lie and hurt you</blink>").update();
break;
default:
this.sendReply("Oh oh... this shouldn't of happened. Please message an Administrator and take a screencap of this. (Problem with mysterybox)");
break;
}
Rooms('lobby').add("|raw|" + Gold.nameColor(user.name, true) + " has bought a Magic Pack from the shop! " + (goodBad === 'good' ? "They have won a(n) <b>" + prize + "</b>!" : "Oh no! They got a " + prize + " from their pack :(")).update();
break;
default:
this.errorReply("Shop item not found. Check spelling?");
}
},
awardbucks: 'givebucks',
gb: 'givebucks',
givebucks: function (target, room, user) {
if (!user.can('pban')) return this.errorReply("You do not have enough authority to do this.");
let parts = target.split(',');
if (!parts[1]) return this.errorReply("Usage: /givebucks [user], [amount]");
for (let u in parts) parts[u] = parts[u].trim();
let targetUser = parts[0];
if (targetUser.length < 1 || toId(targetUser).length > 18) return this.errorReply("Usernames cannot be this length.");
let amount = Math.round(Number(toId(parts[1])));
//checks
if (isNaN(amount)) return this.errorReply("The amount you give must be a number.");
if (amount < 1) return this.errorReply("You can't give less than one buck.");
if (amount > 1000) return this.errorReply("You cannot give more than 1,000 bucks at once.");
//give the bucks
Gold.updateMoney(toId(targetUser), amount);
//send replies
let amountLbl = amount + " Gold buck" + Gold.pluralFormat(amount, 's');
logTransaction(user.name + " has given " + amountLbl + " to " + targetUser + ".");
this.sendReply("You have given " + amountLbl + " to " + targetUser + ".");
if (Users(targetUser)) Users(targetUser).popup("|modal|" + user.name + " has given " + amountLbl + " to you.");
},
takebucks: 'removebucks',
removebucks: function (target, room, user) {
if (!user.can('pban')) return this.errorReply("You do not have enough authority to do this.");
let parts = target.split(',');
if (!parts[1]) return this.errorReply("Usage: /removebucks [user], [amount]");
for (let u in parts) parts[u] = parts[u].trim();
let targetUser = parts[0];
if (targetUser.length < 1 || toId(targetUser).length > 18) return this.errorReply("Usernames cannot be this length.");
let amount = Math.round(Number(toId(parts[1])));
if (amount > Gold.readMoney(targetUser)) return this.errorReply("You cannot remove more bucks than the user has.");
//checks
if (isNaN(amount)) return this.errorReply("The amount you remove must be a number.");
if (amount < 1) return this.errorReply("You can't remove less than one buck.");
if (amount > 1000) return this.errorReply("You cannot remove more than 1,000 bucks at once.");
//take the bucks
Gold.updateMoney(toId(targetUser), -amount);
//send replies
let amountLbl = amount + " Gold buck" + Gold.pluralFormat(amount, 's');
logTransaction(user.name + " has removed " + amountLbl + " from " + targetUser + ".");
this.sendReply("You have removed " + amountLbl + " from " + targetUser + ".");
if (Users(targetUser)) Users(targetUser).popup("|modal|" + user.name + " has removed " + amountLbl + " from you.");
},
tb: 'transferbucks',
transferbucks: function (target, room, user) {
let parts = target.split(',');
if (!parts[1]) return this.errorReply("Usage: /transferbucks [user], [amount]");
for (let u in parts) parts[u] = parts[u].trim();
let targetUser = parts[0];
if (targetUser.length < 1 || toId(targetUser).length > 18) return this.errorReply("Usernames cannot be this length.");
let amount = Math.round(Number(parts[1]));
//checks
if (isNaN(amount)) return this.errorReply("The amount you transfer must be a number.");
if (amount < 1) return this.errorReply("Cannot be less than 1.");
if (toId(targetUser) === user.userid) return this.errorReply("You cannot transfer bucks to yourself.");
if (Gold.readMoney(user.userid) < amount) return this.errorReply("You cannot transfer more than you have.");
//finally, transfer the bucks
Gold.updateMoney(user.userid, Number(-amount));
Gold.updateMoney(targetUser, Number(amount));
//log the transaction
let amountLbl = amount + " Gold buck" + Gold.pluralFormat(amount, 's');
logTransaction(user.name + " has transfered " + amountLbl + " to " + targetUser);
//send return messages
this.sendReply("You have transfered " + amountLbl + " to " + targetUser + ".");
let targetUserConnected = Users(parts[0]);
if (targetUserConnected) {
targetUserConnected.popup("|modal|" + user.name + " has transferred " + amountLbl + " to you.");
targetUserConnected.sendTo(room, "|raw|<b>" + Gold.nameColor(user.name, false) + " has transferred " + amountLbl + " to you.</b>");
}
},
'!atm': true,
balance: 'atm',
wallet: 'atm',
satchel: 'atm',
fannypack: 'atm',
purse: 'atm',
bag: 'atm',
bank: 'atm',
atm: function (target, room, user) {
if (!this.runBroadcast()) return;
if (!target) target = user.name;
let output = "<u>Gold Wallet:</u><br />", bucks = Gold.readMoney(target);
output += Gold.nameColor(target, true) + ' ' + (bucks === 0 ? "does not have any Gold bucks." : "has " + bucks + " Gold buck" + Gold.pluralFormat(bucks, 's') + ".");
return this.sendReplyBox(output);
},
'!richestuser': true,
whosgotthemoneyz: 'richestuser',
richestusers: 'richestuser',
richestuser: function (target, room, user) {
if (!this.runBroadcast()) return;
let number = (target && !~target.indexOf('.') && target > 1 && !isNaN(target) ? Number(target) : 10);
if (this.broadcasting && number > 10) number = 10; // limit to 10 when broadcasting
return this.sendReplyBox(Gold.richestUsers(number));
},
moneylog: function (target, room, user) {
if (!this.can('hotpatch')) return false;
if (!target) return this.errorReply("Usage: /moneylog [number] to view the last x lines OR /moneylog [text] to search for text.");
let word = false;
if (isNaN(Number(target))) word = true;
let lines = fs.readFileSync('logs/transactions.log', 'utf8').split('\n').reverse();
let output = '';
let count = 0;
let regex = new RegExp(target.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "gi");
if (word) {
output += 'Displaying last 50 lines containing "' + target + '":\n';
for (let line in lines) {
if (count >= 50) break;
if (!~lines[line].search(regex)) continue;
output += lines[line] + '\n';
count++;
}
} else {
if (target > 100) target = 100;
output = lines.slice(0, (lines.length > target ? target : lines.length));
output.unshift("Displaying the last " + (lines.length > target ? target : lines.length) + " lines:");
output = output.join('\n');
}
user.popup(output);
},
cs: 'customsymbol',
customsymbol: function (target, room, user) {
if (!user.canCustomSymbol && !Gold.hasVip(user.userid)) return this.errorReply("You don't have the permission to use this command.");
if (user.hasCustomSymbol) return this.errorReply("You currently have a custom symbol, use /resetsymbol if you would like to use this command again.");
if (!this.canTalk()) return;
if (!target || target.length > 1) return this.errorReply("/customsymbol [symbol] - changes your symbol (usergroup) to the specified symbol. The symbol can only be one character");
if (~target.indexOf('\u202e')) return this.errorReply("nono riperino");
let bannedSymbols = /[ +<>$%‽!★@&~#*卐|A-z0-9]/;
if (target.match(bannedSymbols)) return this.errorReply("That symbol is banned.");
user.getIdentity = function (roomid) {
if (this.locked) return '‽' + this.name;
if (roomid) {
let room = Rooms(roomid);
if (room.isMuted(this)) return '!' + this.name;
if (room && room.auth) {
if (room.auth[this.userid]) return room.auth[this.userid] + this.name;
if (room.isPrivate === true) return ' ' + this.name;
}
}
return target + this.name;
};
user.updateIdentity();
user.canCustomSymbol = false;
user.hasCustomSymbol = true;
return this.sendReply("Your symbol has been set.");
},
rs: 'resetsymbol',
resetsymbol: function (target, room, user) {
if (!user.hasCustomSymbol) return this.errorReply("You don't have a custom symbol!");
user.hasCustomSymbol = false;
delete user.getIdentity;
user.updateIdentity();
this.sendReply('Your symbol has been reset.');
},
'!economy': true,
economy: function (target, room, user) {
if (!this.runBroadcast()) return;
let econ = Gold.moneyCirculating();
return this.sendReplyBox("<b>Total bucks in economy:</b> " + econ[0] + "<br /><b>The average user has:</b> " + econ[1] + " bucks.<br />At least " + econ[2] + " users have 1 buck.");
},
};
// local functions
function logTransaction(message) {
if (!message) return false;
fs.appendFile('logs/transactions.log', '[' + new Date().toUTCString() + '] ' + message + '\n');
}
function updatePrices() {
let avg = Gold.moneyCirculating()[1];
prices = {
'symbol': Math.round(avg * 0.035),
// 'declare': Math.round(avg * 0.19),
'fix': Math.round(avg * 0.2),
'custom': Math.round(avg * 0.55),
'animated': Math.round(avg * 0.65),
'room': Math.round(avg * 0.53),
'musicbox': Math.round(avg * 0.4),
'trainer': Math.round(avg * 0.4),
'emote': Math.round(avg * 2.5),
'color': Math.round(avg * 4.5),
'icon': Math.round(avg * 4.5),
'pack': Math.round(avg * 1),
'vip': Math.round(avg * 25),
};
}
function shopTable(item, desc, price) {
let buttonStyle = 'border-radius: 5px; background: linear-gradient(-30deg, #fff493, #e8d95a, #fff493); color: black; text-shadow: 0px 0px 5px #d6b600; border-bottom: 2px solid #635b00; border-right: 2px solid #968900; width: 100%;';
let descStyle = 'border-radius: 5px; border: 1px solid #635b00; background: #fff8b5; color: black;';
let priceStyle = 'border-radius: 5px; border: 1px solid #635b00; background: #fff8b5; color: black; font-weight: bold; text-align: center;';
return '<tr><td style="' + descStyle + '"><button title="Click this button to buy a(n) ' + item + ' from the shop." style="' + buttonStyle + '" name="send" value="/buy ' + item + '">' + item + '</button></td><td style="' + descStyle + '">' + desc + '</td><td style="' + priceStyle + '">' + price + '</td></tr>';
}
| moneyCheck | identifier_name |
economy.js | /**
* Economy
* Gold Server - http://gold.psim.us/
*
* Deals with economy commands, mostly.
* Functions for a lot of this can be found in: ./chat-plugins/goldusers.js
*
* @license MIT license
*/
'use strict';
const fs = require('fs');
let prices;
exports.commands = {
shop: function (target, room, user) {
if (!this.runBroadcast()) return;
if (room.id === 'lobby' && this.broadcasting) {
return this.sendReplyBox('<center>Click <button name="send" value="/shop" style="background-color: black; font-color: white;" title="Enter the Shop!"><font color="white"><b>here</button></b></font> to enter our shop!');
} else {
updatePrices();
let topStyle = 'background: linear-gradient(10deg, #FFF8B5, #eadf7c, #FFF8B5); color: black; border: 1px solid #635b00; padding: 2px; border-radius: 5px;';
let top = '<center><h3><b><u>Gold Bucks Shop</u></b></h3><table style="' + topStyle + '" border="1" cellspacing ="2" cellpadding="3"><tr><th>Item</th><th>Description</th><th>Cost</th></tr>';
let bottom = '</table><br /><b>Prices in the shop go up and down automatically depending on the amount of bucks the average user has at that given time.</b><br />To buy an item from the shop, click the respective button for said item.<br>Do /getbucks to learn more about how to obtain bucks. </center>';
return this.sendReply('|raw|' +
top +
shopTable("Symbol", "Buys a custom symbol to go infront of name and puts you towards the top of userlist (lasts 2 hrs from logout)", prices['symbol']) +
// shopTable("Declare", "Advertisement declare for a room on the server from an Administrator / Leader.", prices['declare']) +
shopTable("Fix", "Ability to modify a custom avatar, trainer card, or userlist icon.", prices['fix']) +
shopTable("Custom", "Buys a custom avatar to be applied to your name (you supply)", prices['custom']) +
shopTable("Animated", "Buys an animated avatar to be applied to your name (you supply)", prices['animated']) +
shopTable("Room", "Buys a public unofficial chat room - will be deleted if inactive. Must have a valid purpose; staff can reject making these.", prices['room']) +
shopTable("Musicbox", "A command that lists / links up to 8 of your favorite songs", prices['musicbox']) +
shopTable("Trainer", "Gives you a custom command - you provide the HTML and command name.", prices['trainer']) +
shopTable("Mystery Box", "Gives you a special surprise gift when you open it! (Could be good or bad!)", prices['pack']) +
shopTable("Emote", "A custom chat emoticon such as \"Kappa\" - must be 30x30", prices['emote']) +
shopTable("Color", "This gives your username a custom color on the userlist and in all rooms (existing at time of purchase)", prices['color']) +
shopTable("Icon", "This gives your username a custom userlist icon on our regular client - MUST be a Pokemon and has to be 32x32.", prices['icon']) +
shopTable("VIP Status", "Gives you the ability to change your custom symbol, avatar, custom color, and userlist icon as much as you wish, and it is also displayed in your profile.", prices['vip']) +
bottom
);
}
},
buy: function (target, room, user) {
updatePrices();
if (!target) return this.errorReply("You need to pick an item! Type /buy [item] to buy something.");
let parts = target.split(',');
let output = '';
let price;
function link(link, formatted) {
return '<a href="' + link + '" target="_blank">' + formatted + '</a>';
}
function moneyCheck(price) {
if (Gold.readMoney(user.userid) < price) return false;
if (Gold.readMoney(user.userid) >= price) return true;
}
function alertStaff(message, staffRoom) {
Gold.pmUpperStaff('/raw ' + message, '~Server', false);
if (staffRoom) {
Rooms.get('staff').add('|raw|<b>' + message + '</b>');
Rooms.get('staff').update();
}
}
function processPurchase(price, item, desc) {
if (!desc) desc = '';
if (Gold.readMoney(user.userid) < price) return false; // this should never happen
Gold.updateMoney(user.userid, -price);
logTransaction(user.name + ' has purchased a(n) ' + item + '. ' + desc);
}
| if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
this.sendReply("You have purchased a custom symbol. You will have this until you log off for more than an hour.");
this.sendReply("Use /customsymbol [symbol] to change your symbol now!");
user.canCustomSymbol = true;
break;
case 'custom':
case 'avatar':
case 'customavatar':
price = prices['custom'];
if (Gold.hasVip(user.userid)) return this.errorReply("You are a VIP user - you do not need to buy avatars from the shop. Use /customavatar to change your avatar.");
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy avatar, [link to avatar]. Must be a PNG or JPG.");
let filepaths = ['.png', '.jpg'];
if (!~filepaths.indexOf(parts[1].substr(-4))) return this.errorReply("Your image for a regular custom avatar must be either a PNG or JPG. (If it is a valid file type, it will end in one of these)");
processPurchase(price, parts[0], 'Image: ' + parts[1]);
if (Config.customavatars[user.userid]) output = ' | <button name="send" value="/sca delete, ' + user.userid + '" target="_blank" title="Click this to remove current avatar.">Click2Remove</button>';
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom avatar. Image: ' + link(parts[1].replace(' ', ''), 'desired avatar'), true);
alertStaff('<center><img src="' + parts[1] + '" width="80" height="80"><br /><button name="send" value="/sca set, ' + toId(user.name) + ', ' + parts[1] + '" target="_blank" title="Click this to set the above custom avatar.">Click2Set</button> ' + output + '</center>', false);
this.sendReply("You have bought a custom avatar from the shop. The staff have been notified and will set it ASAP.");
break;
case 'color':
case 'customcolor':
price = prices['color'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy color, [hex code OR name of an alt you want the color of]");
if (parts[1].length > 20) return this.errorReply("This is not a valid color, try again.");
processPurchase(price, parts[0], parts[1]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom color. Color: ' + parts[1], true);
this.sendReply("You have purchased a custom color: " + parts[1] + " from the shop. Please screen capture this in case the staff do not get this message.");
break;
case 'emote':
case 'emoticon':
price = prices['emote'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1] || !parts[2]) return this.errorReply("Usage: /buy emote, [emote code], [image for the emote]");
let emoteFilepaths = ['.png', '.jpg', '.gif'];
if (!~emoteFilepaths.indexOf(parts[2].substr(-4))) return this.errorReply("Emoticons must be in one of the following formats: PNG, JPG, or GIF.");
if (Gold.emoticons.chatEmotes[parts[1].replace(' ', '')]) return this.errorReply("An emoticon with this trigger word already exists on this server.");
processPurchase(price, parts[0], 'Emote: ' + parts[1] + ' Link: ' + parts[2]);
alertStaff(Gold.nameColor(user.name, true) + " has purchased a custom emote. Emote \"" + parts[1].trim() + "\": " + link(parts[2].replace(' ', ''), 'desired emote'), true);
alertStaff('<center><img title=' + parts[1] + ' src=' + parts[2] + '><br /><button name="send" value="/emote add, ' + parts[1] + ', ' + parts[2] + '" target="_blank" title="Click to add the emoticon above.">Click2Add</button></center>', false);
this.sendReply("You have bought a custom emoticon from the shop. The staff have been notified and will add it ASAP.");
break;
case 'animated':
price = prices['animated'];
if (Gold.hasVip(user.userid)) return this.errorReply("You are a VIP user - you do not need to buy animated avatars from the shop. Use /customavatar to change your avatar.");
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy animated, [link to avatar]. Must be a GIF.");
if (parts[1].split('.').pop() !== 'gif') return this.errorReply("Your animated avatar must be a GIF. (If it's a GIF, the link will end in .gif)");
processPurchase(price, parts[0], 'Image: ' + parts[1]);
if (Config.customavatars[user.userid]) output = ' | <button name="send" value="/sca delete, ' + user.userid + '" target="_blank" title="Click this to remove current avatar.">Click2Remove</button>';
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom animated avatar. Image: ' + link(parts[1].replace(' ', ''), 'desired avatar'), true);
alertStaff('<center><img src="' + parts[1] + '" width="80" height="80"><br /><button name="send" value="/sca set, ' + toId(user.name) + ', ' + parts[1] + '" target="_blank" title="Click this to set the above custom avatar.">Click2Set</button> ' + output + '</center>', false);
this.sendReply("You have purchased a custom animated avatar. The staff have been notified and will add it ASAP.");
break;
case 'room':
case 'chatroom':
price = prices['room'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy room, [room name]");
let bannedRoomNames = [',', '|', '[', '-'];
if (~bannedRoomNames.indexOf(parts[1])) return this.errorReply("This room name is not valid, try again.");
processPurchase(price, parts[0], 'Room name: ' + parts[1]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a chat room. Room name: ' + parts[1], true);
this.sendReply("You have purchased a room. The staff have been notified and it will be created shortly as long as it meets our basic rules.");
break;
case 'trainer':
case 'trainercard':
price = prices['trainer'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a trainer card.', true);
this.sendReply("|html|You have purchased a trainer card. Please use <a href=http://goldservers.info/site/trainercard.html>this</a> to make your trainer card and then PM a leader or administrator the HTML with the command name you want it to have.");
break;
case 'mb':
case 'musicbox':
price = prices['musicbox'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!Gold.createMusicBox(user)) return this.errorReply("You already have a music box! There's no need to buy another.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a music box.', true);
Gold.createMusicBox(user); // give the user a music box
this.parse('/' + toId(parts[0]) + ' help');
this.sendReply("You have purchased a music box. You may have a maximum of 8 songs in it.");
break;
case 'fix':
price = prices['fix'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a fix from the shop.', true);
user.canFixItem = true;
this.sendReply("You have purchased a fix from the shop. You can use this to alter your trainer card, music box, or custom chat emoticon. PM a leader or administrator to proceed.");
break;
/*
case 'ad':
case 'declare':
price = prices['declare'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased the ability to declare from the shop.', true);
this.sendReply("You have purchased an advertisement declare from the shop. Please prepare an advertisement for your room; a leader or administrator will soon be PMing you to proceed.");
break;
*/
case 'userlisticon':
case 'icon':
price = prices['icon'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1] || parts[1].length < 3) return this.errorReply("Usage: /buy icon, [32x32 icon image]");
let iconFilepaths = ['.png', '.jpg', '.gif'];
if (!~iconFilepaths.indexOf(parts[1].substr(-4))) return this.errorReply("Your image for a custom userlist icon must be a PNG, JPG, or GIF.");
processPurchase(price, parts[0], 'Image: ' + parts[1]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom userlist icon. Image: ' + link(parts[1].replace(' ', ''), 'desired icon'), true);
alertStaff('<center><button name="send" value="/icon ' + user.userid + ', ' + parts[1] + '" target="_blank" title="Click this to set the above custom userlist icon.">Click2Set</button></center>', false);
this.sendReply("You have purchased a custom userlist icon. The staff have been notified and this will be added ASAP.");
break;
case 'vip':
case 'vipstatus':
price = prices['vip'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
Gold.modifyBadge(user.userid, 'vip', 'GIVE');
alertStaff(Gold.nameColor(user.name, true) + " has purchased VIP Status from the shop and they have recieved it automatically from the server.", true);
break;
case 'mysterybox':
case 'pack':
case 'magicpack':
price = prices['pack'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (room.id !== 'lobby') return this.errorReply("You must buy this item in the Lobby!");
processPurchase(price, parts[0]);
let randomNumber = Math.floor((Math.random() * 100) + 1);
let prize = '';
let goodBad = '';
let opts;
if (randomNumber < 70) {
goodBad = 'bad';
opts = ['nothing', 'rick rolled', 'meme avatar', 'kick from Lobby', '2 minute mute'];
prize = opts[Math.floor(Math.random() * opts.length)];
} else if (randomNumber > 70) {
goodBad = 'good';
opts = ['100 bucks', '125 bucks', 'a custom symbol', 'a custom userlist icon', 'ability to get Dubtrack VIP', 'ability to set the PotD', 'custom color', 'the cost of the mystery box back', 'ability to have a leader/admin broadcast an image to Lobby', 'a kind, warm hearted thank you'];
prize = opts[Math.floor(Math.random() * opts.length)];
}
switch (prize) {
// good
case '100 bucks':
Gold.updateMoney(user.userid, 100);
break;
case '125 bucks':
Gold.updateMoney(user.userid, 125);
break;
case 'the cost of the mystery box back':
Gold.updateMoney(user.userid, prices['pack']);
break;
case 'ability to get Dubtrack VIP':
case 'ability to have a leader/admin broadcast an image to Lobby':
case 'custom color':
case 'ability to set the PotD':
alertStaff(Gold.nameColor(user.name, true) + " has won an " + prize + ". Please PM them to proceed with giving them this.", true);
break;
case 'a custom symbol':
user.canCustomSymbol = true;
this.sendReply("Do /customsymbol [symbol] to set a FREE custom symbol! (Do /rs to reset your custom symbol when you want to remove it later.)");
break;
case 'a kind, warm hearted thank you':
this.sendReply("THANK U 8D!");
break;
case 'a custom userlist icon':
this.sendReply("PM a leader or administrator to claim this prize!");
break;
// bad
case 'nothing':
break;
case 'meme avatar':
opts = ['notpawn.png', 'notpawn2.png'];
user.avatar = opts[Math.floor(Math.random() * opts.length)];
break;
case 'kick from Lobby':
try {
user.leaveRoom('lobby');
user.popup("You have been kicked from the Lobby by the Mystery Box!");
} catch (e) {}
break;
case '2 minute mute':
try {
Rooms('lobby').mute(user, 2 * 60 * 1000, false);
} catch (e) {}
break;
case 'rick rolled':
Rooms('lobby').add("|raw|<blink>" +
"Never gonna give you up<br />" +
"Never gonna let you down<br />" +
"Never gonna run around and desert you<br />" +
"Never gonna make you cry<br />" +
"Never gonna say goodbye<br />" +
"Never gonna tell a lie and hurt you</blink>").update();
break;
default:
this.sendReply("Oh oh... this shouldn't of happened. Please message an Administrator and take a screencap of this. (Problem with mysterybox)");
break;
}
Rooms('lobby').add("|raw|" + Gold.nameColor(user.name, true) + " has bought a Magic Pack from the shop! " + (goodBad === 'good' ? "They have won a(n) <b>" + prize + "</b>!" : "Oh no! They got a " + prize + " from their pack :(")).update();
break;
default:
this.errorReply("Shop item not found. Check spelling?");
}
},
awardbucks: 'givebucks',
gb: 'givebucks',
givebucks: function (target, room, user) {
if (!user.can('pban')) return this.errorReply("You do not have enough authority to do this.");
let parts = target.split(',');
if (!parts[1]) return this.errorReply("Usage: /givebucks [user], [amount]");
for (let u in parts) parts[u] = parts[u].trim();
let targetUser = parts[0];
if (targetUser.length < 1 || toId(targetUser).length > 18) return this.errorReply("Usernames cannot be this length.");
let amount = Math.round(Number(toId(parts[1])));
//checks
if (isNaN(amount)) return this.errorReply("The amount you give must be a number.");
if (amount < 1) return this.errorReply("You can't give less than one buck.");
if (amount > 1000) return this.errorReply("You cannot give more than 1,000 bucks at once.");
//give the bucks
Gold.updateMoney(toId(targetUser), amount);
//send replies
let amountLbl = amount + " Gold buck" + Gold.pluralFormat(amount, 's');
logTransaction(user.name + " has given " + amountLbl + " to " + targetUser + ".");
this.sendReply("You have given " + amountLbl + " to " + targetUser + ".");
if (Users(targetUser)) Users(targetUser).popup("|modal|" + user.name + " has given " + amountLbl + " to you.");
},
takebucks: 'removebucks',
removebucks: function (target, room, user) {
if (!user.can('pban')) return this.errorReply("You do not have enough authority to do this.");
let parts = target.split(',');
if (!parts[1]) return this.errorReply("Usage: /removebucks [user], [amount]");
for (let u in parts) parts[u] = parts[u].trim();
let targetUser = parts[0];
if (targetUser.length < 1 || toId(targetUser).length > 18) return this.errorReply("Usernames cannot be this length.");
let amount = Math.round(Number(toId(parts[1])));
if (amount > Gold.readMoney(targetUser)) return this.errorReply("You cannot remove more bucks than the user has.");
//checks
if (isNaN(amount)) return this.errorReply("The amount you remove must be a number.");
if (amount < 1) return this.errorReply("You can't remove less than one buck.");
if (amount > 1000) return this.errorReply("You cannot remove more than 1,000 bucks at once.");
//take the bucks
Gold.updateMoney(toId(targetUser), -amount);
//send replies
let amountLbl = amount + " Gold buck" + Gold.pluralFormat(amount, 's');
logTransaction(user.name + " has removed " + amountLbl + " from " + targetUser + ".");
this.sendReply("You have removed " + amountLbl + " from " + targetUser + ".");
if (Users(targetUser)) Users(targetUser).popup("|modal|" + user.name + " has removed " + amountLbl + " from you.");
},
tb: 'transferbucks',
transferbucks: function (target, room, user) {
let parts = target.split(',');
if (!parts[1]) return this.errorReply("Usage: /transferbucks [user], [amount]");
for (let u in parts) parts[u] = parts[u].trim();
let targetUser = parts[0];
if (targetUser.length < 1 || toId(targetUser).length > 18) return this.errorReply("Usernames cannot be this length.");
let amount = Math.round(Number(parts[1]));
//checks
if (isNaN(amount)) return this.errorReply("The amount you transfer must be a number.");
if (amount < 1) return this.errorReply("Cannot be less than 1.");
if (toId(targetUser) === user.userid) return this.errorReply("You cannot transfer bucks to yourself.");
if (Gold.readMoney(user.userid) < amount) return this.errorReply("You cannot transfer more than you have.");
//finally, transfer the bucks
Gold.updateMoney(user.userid, Number(-amount));
Gold.updateMoney(targetUser, Number(amount));
//log the transaction
let amountLbl = amount + " Gold buck" + Gold.pluralFormat(amount, 's');
logTransaction(user.name + " has transfered " + amountLbl + " to " + targetUser);
//send return messages
this.sendReply("You have transfered " + amountLbl + " to " + targetUser + ".");
let targetUserConnected = Users(parts[0]);
if (targetUserConnected) {
targetUserConnected.popup("|modal|" + user.name + " has transferred " + amountLbl + " to you.");
targetUserConnected.sendTo(room, "|raw|<b>" + Gold.nameColor(user.name, false) + " has transferred " + amountLbl + " to you.</b>");
}
},
'!atm': true,
balance: 'atm',
wallet: 'atm',
satchel: 'atm',
fannypack: 'atm',
purse: 'atm',
bag: 'atm',
bank: 'atm',
atm: function (target, room, user) {
if (!this.runBroadcast()) return;
if (!target) target = user.name;
let output = "<u>Gold Wallet:</u><br />", bucks = Gold.readMoney(target);
output += Gold.nameColor(target, true) + ' ' + (bucks === 0 ? "does not have any Gold bucks." : "has " + bucks + " Gold buck" + Gold.pluralFormat(bucks, 's') + ".");
return this.sendReplyBox(output);
},
'!richestuser': true,
whosgotthemoneyz: 'richestuser',
richestusers: 'richestuser',
richestuser: function (target, room, user) {
if (!this.runBroadcast()) return;
let number = (target && !~target.indexOf('.') && target > 1 && !isNaN(target) ? Number(target) : 10);
if (this.broadcasting && number > 10) number = 10; // limit to 10 when broadcasting
return this.sendReplyBox(Gold.richestUsers(number));
},
moneylog: function (target, room, user) {
if (!this.can('hotpatch')) return false;
if (!target) return this.errorReply("Usage: /moneylog [number] to view the last x lines OR /moneylog [text] to search for text.");
let word = false;
if (isNaN(Number(target))) word = true;
let lines = fs.readFileSync('logs/transactions.log', 'utf8').split('\n').reverse();
let output = '';
let count = 0;
let regex = new RegExp(target.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "gi");
if (word) {
output += 'Displaying last 50 lines containing "' + target + '":\n';
for (let line in lines) {
if (count >= 50) break;
if (!~lines[line].search(regex)) continue;
output += lines[line] + '\n';
count++;
}
} else {
if (target > 100) target = 100;
output = lines.slice(0, (lines.length > target ? target : lines.length));
output.unshift("Displaying the last " + (lines.length > target ? target : lines.length) + " lines:");
output = output.join('\n');
}
user.popup(output);
},
cs: 'customsymbol',
customsymbol: function (target, room, user) {
if (!user.canCustomSymbol && !Gold.hasVip(user.userid)) return this.errorReply("You don't have the permission to use this command.");
if (user.hasCustomSymbol) return this.errorReply("You currently have a custom symbol, use /resetsymbol if you would like to use this command again.");
if (!this.canTalk()) return;
if (!target || target.length > 1) return this.errorReply("/customsymbol [symbol] - changes your symbol (usergroup) to the specified symbol. The symbol can only be one character");
if (~target.indexOf('\u202e')) return this.errorReply("nono riperino");
let bannedSymbols = /[ +<>$%‽!★@&~#*卐|A-z0-9]/;
if (target.match(bannedSymbols)) return this.errorReply("That symbol is banned.");
user.getIdentity = function (roomid) {
if (this.locked) return '‽' + this.name;
if (roomid) {
let room = Rooms(roomid);
if (room.isMuted(this)) return '!' + this.name;
if (room && room.auth) {
if (room.auth[this.userid]) return room.auth[this.userid] + this.name;
if (room.isPrivate === true) return ' ' + this.name;
}
}
return target + this.name;
};
user.updateIdentity();
user.canCustomSymbol = false;
user.hasCustomSymbol = true;
return this.sendReply("Your symbol has been set.");
},
rs: 'resetsymbol',
resetsymbol: function (target, room, user) {
if (!user.hasCustomSymbol) return this.errorReply("You don't have a custom symbol!");
user.hasCustomSymbol = false;
delete user.getIdentity;
user.updateIdentity();
this.sendReply('Your symbol has been reset.');
},
'!economy': true,
economy: function (target, room, user) {
if (!this.runBroadcast()) return;
let econ = Gold.moneyCirculating();
return this.sendReplyBox("<b>Total bucks in economy:</b> " + econ[0] + "<br /><b>The average user has:</b> " + econ[1] + " bucks.<br />At least " + econ[2] + " users have 1 buck.");
},
};
// local functions
function logTransaction(message) {
if (!message) return false;
fs.appendFile('logs/transactions.log', '[' + new Date().toUTCString() + '] ' + message + '\n');
}
function updatePrices() {
let avg = Gold.moneyCirculating()[1];
prices = {
'symbol': Math.round(avg * 0.035),
// 'declare': Math.round(avg * 0.19),
'fix': Math.round(avg * 0.2),
'custom': Math.round(avg * 0.55),
'animated': Math.round(avg * 0.65),
'room': Math.round(avg * 0.53),
'musicbox': Math.round(avg * 0.4),
'trainer': Math.round(avg * 0.4),
'emote': Math.round(avg * 2.5),
'color': Math.round(avg * 4.5),
'icon': Math.round(avg * 4.5),
'pack': Math.round(avg * 1),
'vip': Math.round(avg * 25),
};
}
function shopTable(item, desc, price) {
let buttonStyle = 'border-radius: 5px; background: linear-gradient(-30deg, #fff493, #e8d95a, #fff493); color: black; text-shadow: 0px 0px 5px #d6b600; border-bottom: 2px solid #635b00; border-right: 2px solid #968900; width: 100%;';
let descStyle = 'border-radius: 5px; border: 1px solid #635b00; background: #fff8b5; color: black;';
let priceStyle = 'border-radius: 5px; border: 1px solid #635b00; background: #fff8b5; color: black; font-weight: bold; text-align: center;';
return '<tr><td style="' + descStyle + '"><button title="Click this button to buy a(n) ' + item + ' from the shop." style="' + buttonStyle + '" name="send" value="/buy ' + item + '">' + item + '</button></td><td style="' + descStyle + '">' + desc + '</td><td style="' + priceStyle + '">' + price + '</td></tr>';
} | switch (toId(parts[0])) {
case 'symbol':
price = prices['symbol'];
if (Gold.hasVip(user.userid)) return this.errorReply("You are a VIP user - you do not need to buy custom symbols from the shop. Use /customsymbol to change your symbol."); | random_line_split |
economy.js | /**
* Economy
* Gold Server - http://gold.psim.us/
*
* Deals with economy commands, mostly.
* Functions for a lot of this can be found in: ./chat-plugins/goldusers.js
*
* @license MIT license
*/
'use strict';
const fs = require('fs');
let prices;
exports.commands = {
shop: function (target, room, user) {
if (!this.runBroadcast()) return;
if (room.id === 'lobby' && this.broadcasting) {
return this.sendReplyBox('<center>Click <button name="send" value="/shop" style="background-color: black; font-color: white;" title="Enter the Shop!"><font color="white"><b>here</button></b></font> to enter our shop!');
} else {
updatePrices();
let topStyle = 'background: linear-gradient(10deg, #FFF8B5, #eadf7c, #FFF8B5); color: black; border: 1px solid #635b00; padding: 2px; border-radius: 5px;';
let top = '<center><h3><b><u>Gold Bucks Shop</u></b></h3><table style="' + topStyle + '" border="1" cellspacing ="2" cellpadding="3"><tr><th>Item</th><th>Description</th><th>Cost</th></tr>';
let bottom = '</table><br /><b>Prices in the shop go up and down automatically depending on the amount of bucks the average user has at that given time.</b><br />To buy an item from the shop, click the respective button for said item.<br>Do /getbucks to learn more about how to obtain bucks. </center>';
return this.sendReply('|raw|' +
top +
shopTable("Symbol", "Buys a custom symbol to go infront of name and puts you towards the top of userlist (lasts 2 hrs from logout)", prices['symbol']) +
// shopTable("Declare", "Advertisement declare for a room on the server from an Administrator / Leader.", prices['declare']) +
shopTable("Fix", "Ability to modify a custom avatar, trainer card, or userlist icon.", prices['fix']) +
shopTable("Custom", "Buys a custom avatar to be applied to your name (you supply)", prices['custom']) +
shopTable("Animated", "Buys an animated avatar to be applied to your name (you supply)", prices['animated']) +
shopTable("Room", "Buys a public unofficial chat room - will be deleted if inactive. Must have a valid purpose; staff can reject making these.", prices['room']) +
shopTable("Musicbox", "A command that lists / links up to 8 of your favorite songs", prices['musicbox']) +
shopTable("Trainer", "Gives you a custom command - you provide the HTML and command name.", prices['trainer']) +
shopTable("Mystery Box", "Gives you a special surprise gift when you open it! (Could be good or bad!)", prices['pack']) +
shopTable("Emote", "A custom chat emoticon such as \"Kappa\" - must be 30x30", prices['emote']) +
shopTable("Color", "This gives your username a custom color on the userlist and in all rooms (existing at time of purchase)", prices['color']) +
shopTable("Icon", "This gives your username a custom userlist icon on our regular client - MUST be a Pokemon and has to be 32x32.", prices['icon']) +
shopTable("VIP Status", "Gives you the ability to change your custom symbol, avatar, custom color, and userlist icon as much as you wish, and it is also displayed in your profile.", prices['vip']) +
bottom
);
}
},
buy: function (target, room, user) {
updatePrices();
if (!target) return this.errorReply("You need to pick an item! Type /buy [item] to buy something.");
let parts = target.split(',');
let output = '';
let price;
function link(link, formatted) |
function moneyCheck(price) {
if (Gold.readMoney(user.userid) < price) return false;
if (Gold.readMoney(user.userid) >= price) return true;
}
function alertStaff(message, staffRoom) {
Gold.pmUpperStaff('/raw ' + message, '~Server', false);
if (staffRoom) {
Rooms.get('staff').add('|raw|<b>' + message + '</b>');
Rooms.get('staff').update();
}
}
function processPurchase(price, item, desc) {
if (!desc) desc = '';
if (Gold.readMoney(user.userid) < price) return false; // this should never happen
Gold.updateMoney(user.userid, -price);
logTransaction(user.name + ' has purchased a(n) ' + item + '. ' + desc);
}
switch (toId(parts[0])) {
case 'symbol':
price = prices['symbol'];
if (Gold.hasVip(user.userid)) return this.errorReply("You are a VIP user - you do not need to buy custom symbols from the shop. Use /customsymbol to change your symbol.");
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
this.sendReply("You have purchased a custom symbol. You will have this until you log off for more than an hour.");
this.sendReply("Use /customsymbol [symbol] to change your symbol now!");
user.canCustomSymbol = true;
break;
case 'custom':
case 'avatar':
case 'customavatar':
price = prices['custom'];
if (Gold.hasVip(user.userid)) return this.errorReply("You are a VIP user - you do not need to buy avatars from the shop. Use /customavatar to change your avatar.");
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy avatar, [link to avatar]. Must be a PNG or JPG.");
let filepaths = ['.png', '.jpg'];
if (!~filepaths.indexOf(parts[1].substr(-4))) return this.errorReply("Your image for a regular custom avatar must be either a PNG or JPG. (If it is a valid file type, it will end in one of these)");
processPurchase(price, parts[0], 'Image: ' + parts[1]);
if (Config.customavatars[user.userid]) output = ' | <button name="send" value="/sca delete, ' + user.userid + '" target="_blank" title="Click this to remove current avatar.">Click2Remove</button>';
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom avatar. Image: ' + link(parts[1].replace(' ', ''), 'desired avatar'), true);
alertStaff('<center><img src="' + parts[1] + '" width="80" height="80"><br /><button name="send" value="/sca set, ' + toId(user.name) + ', ' + parts[1] + '" target="_blank" title="Click this to set the above custom avatar.">Click2Set</button> ' + output + '</center>', false);
this.sendReply("You have bought a custom avatar from the shop. The staff have been notified and will set it ASAP.");
break;
case 'color':
case 'customcolor':
price = prices['color'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy color, [hex code OR name of an alt you want the color of]");
if (parts[1].length > 20) return this.errorReply("This is not a valid color, try again.");
processPurchase(price, parts[0], parts[1]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom color. Color: ' + parts[1], true);
this.sendReply("You have purchased a custom color: " + parts[1] + " from the shop. Please screen capture this in case the staff do not get this message.");
break;
case 'emote':
case 'emoticon':
price = prices['emote'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1] || !parts[2]) return this.errorReply("Usage: /buy emote, [emote code], [image for the emote]");
let emoteFilepaths = ['.png', '.jpg', '.gif'];
if (!~emoteFilepaths.indexOf(parts[2].substr(-4))) return this.errorReply("Emoticons must be in one of the following formats: PNG, JPG, or GIF.");
if (Gold.emoticons.chatEmotes[parts[1].replace(' ', '')]) return this.errorReply("An emoticon with this trigger word already exists on this server.");
processPurchase(price, parts[0], 'Emote: ' + parts[1] + ' Link: ' + parts[2]);
alertStaff(Gold.nameColor(user.name, true) + " has purchased a custom emote. Emote \"" + parts[1].trim() + "\": " + link(parts[2].replace(' ', ''), 'desired emote'), true);
alertStaff('<center><img title=' + parts[1] + ' src=' + parts[2] + '><br /><button name="send" value="/emote add, ' + parts[1] + ', ' + parts[2] + '" target="_blank" title="Click to add the emoticon above.">Click2Add</button></center>', false);
this.sendReply("You have bought a custom emoticon from the shop. The staff have been notified and will add it ASAP.");
break;
case 'animated':
price = prices['animated'];
if (Gold.hasVip(user.userid)) return this.errorReply("You are a VIP user - you do not need to buy animated avatars from the shop. Use /customavatar to change your avatar.");
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy animated, [link to avatar]. Must be a GIF.");
if (parts[1].split('.').pop() !== 'gif') return this.errorReply("Your animated avatar must be a GIF. (If it's a GIF, the link will end in .gif)");
processPurchase(price, parts[0], 'Image: ' + parts[1]);
if (Config.customavatars[user.userid]) output = ' | <button name="send" value="/sca delete, ' + user.userid + '" target="_blank" title="Click this to remove current avatar.">Click2Remove</button>';
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom animated avatar. Image: ' + link(parts[1].replace(' ', ''), 'desired avatar'), true);
alertStaff('<center><img src="' + parts[1] + '" width="80" height="80"><br /><button name="send" value="/sca set, ' + toId(user.name) + ', ' + parts[1] + '" target="_blank" title="Click this to set the above custom avatar.">Click2Set</button> ' + output + '</center>', false);
this.sendReply("You have purchased a custom animated avatar. The staff have been notified and will add it ASAP.");
break;
case 'room':
case 'chatroom':
price = prices['room'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1]) return this.errorReply("Usage: /buy room, [room name]");
let bannedRoomNames = [',', '|', '[', '-'];
if (~bannedRoomNames.indexOf(parts[1])) return this.errorReply("This room name is not valid, try again.");
processPurchase(price, parts[0], 'Room name: ' + parts[1]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a chat room. Room name: ' + parts[1], true);
this.sendReply("You have purchased a room. The staff have been notified and it will be created shortly as long as it meets our basic rules.");
break;
case 'trainer':
case 'trainercard':
price = prices['trainer'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a trainer card.', true);
this.sendReply("|html|You have purchased a trainer card. Please use <a href=http://goldservers.info/site/trainercard.html>this</a> to make your trainer card and then PM a leader or administrator the HTML with the command name you want it to have.");
break;
case 'mb':
case 'musicbox':
price = prices['musicbox'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!Gold.createMusicBox(user)) return this.errorReply("You already have a music box! There's no need to buy another.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a music box.', true);
Gold.createMusicBox(user); // give the user a music box
this.parse('/' + toId(parts[0]) + ' help');
this.sendReply("You have purchased a music box. You may have a maximum of 8 songs in it.");
break;
case 'fix':
price = prices['fix'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a fix from the shop.', true);
user.canFixItem = true;
this.sendReply("You have purchased a fix from the shop. You can use this to alter your trainer card, music box, or custom chat emoticon. PM a leader or administrator to proceed.");
break;
/*
case 'ad':
case 'declare':
price = prices['declare'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased the ability to declare from the shop.', true);
this.sendReply("You have purchased an advertisement declare from the shop. Please prepare an advertisement for your room; a leader or administrator will soon be PMing you to proceed.");
break;
*/
case 'userlisticon':
case 'icon':
price = prices['icon'];
if (Gold.hasVip(user.userid)) price = 0;
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (!parts[1] || parts[1].length < 3) return this.errorReply("Usage: /buy icon, [32x32 icon image]");
let iconFilepaths = ['.png', '.jpg', '.gif'];
if (!~iconFilepaths.indexOf(parts[1].substr(-4))) return this.errorReply("Your image for a custom userlist icon must be a PNG, JPG, or GIF.");
processPurchase(price, parts[0], 'Image: ' + parts[1]);
alertStaff(Gold.nameColor(user.name, true) + ' has purchased a custom userlist icon. Image: ' + link(parts[1].replace(' ', ''), 'desired icon'), true);
alertStaff('<center><button name="send" value="/icon ' + user.userid + ', ' + parts[1] + '" target="_blank" title="Click this to set the above custom userlist icon.">Click2Set</button></center>', false);
this.sendReply("You have purchased a custom userlist icon. The staff have been notified and this will be added ASAP.");
break;
case 'vip':
case 'vipstatus':
price = prices['vip'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
processPurchase(price, parts[0]);
Gold.modifyBadge(user.userid, 'vip', 'GIVE');
alertStaff(Gold.nameColor(user.name, true) + " has purchased VIP Status from the shop and they have recieved it automatically from the server.", true);
break;
case 'mysterybox':
case 'pack':
case 'magicpack':
price = prices['pack'];
if (!moneyCheck(price)) return this.errorReply("You do not have enough bucks for this item at this time, sorry.");
if (room.id !== 'lobby') return this.errorReply("You must buy this item in the Lobby!");
processPurchase(price, parts[0]);
let randomNumber = Math.floor((Math.random() * 100) + 1);
let prize = '';
let goodBad = '';
let opts;
if (randomNumber < 70) {
goodBad = 'bad';
opts = ['nothing', 'rick rolled', 'meme avatar', 'kick from Lobby', '2 minute mute'];
prize = opts[Math.floor(Math.random() * opts.length)];
} else if (randomNumber > 70) {
goodBad = 'good';
opts = ['100 bucks', '125 bucks', 'a custom symbol', 'a custom userlist icon', 'ability to get Dubtrack VIP', 'ability to set the PotD', 'custom color', 'the cost of the mystery box back', 'ability to have a leader/admin broadcast an image to Lobby', 'a kind, warm hearted thank you'];
prize = opts[Math.floor(Math.random() * opts.length)];
}
switch (prize) {
// good
case '100 bucks':
Gold.updateMoney(user.userid, 100);
break;
case '125 bucks':
Gold.updateMoney(user.userid, 125);
break;
case 'the cost of the mystery box back':
Gold.updateMoney(user.userid, prices['pack']);
break;
case 'ability to get Dubtrack VIP':
case 'ability to have a leader/admin broadcast an image to Lobby':
case 'custom color':
case 'ability to set the PotD':
alertStaff(Gold.nameColor(user.name, true) + " has won an " + prize + ". Please PM them to proceed with giving them this.", true);
break;
case 'a custom symbol':
user.canCustomSymbol = true;
this.sendReply("Do /customsymbol [symbol] to set a FREE custom symbol! (Do /rs to reset your custom symbol when you want to remove it later.)");
break;
case 'a kind, warm hearted thank you':
this.sendReply("THANK U 8D!");
break;
case 'a custom userlist icon':
this.sendReply("PM a leader or administrator to claim this prize!");
break;
// bad
case 'nothing':
break;
case 'meme avatar':
opts = ['notpawn.png', 'notpawn2.png'];
user.avatar = opts[Math.floor(Math.random() * opts.length)];
break;
case 'kick from Lobby':
try {
user.leaveRoom('lobby');
user.popup("You have been kicked from the Lobby by the Mystery Box!");
} catch (e) {}
break;
case '2 minute mute':
try {
Rooms('lobby').mute(user, 2 * 60 * 1000, false);
} catch (e) {}
break;
case 'rick rolled':
Rooms('lobby').add("|raw|<blink>" +
"Never gonna give you up<br />" +
"Never gonna let you down<br />" +
"Never gonna run around and desert you<br />" +
"Never gonna make you cry<br />" +
"Never gonna say goodbye<br />" +
"Never gonna tell a lie and hurt you</blink>").update();
break;
default:
this.sendReply("Oh oh... this shouldn't of happened. Please message an Administrator and take a screencap of this. (Problem with mysterybox)");
break;
}
Rooms('lobby').add("|raw|" + Gold.nameColor(user.name, true) + " has bought a Magic Pack from the shop! " + (goodBad === 'good' ? "They have won a(n) <b>" + prize + "</b>!" : "Oh no! They got a " + prize + " from their pack :(")).update();
break;
default:
this.errorReply("Shop item not found. Check spelling?");
}
},
awardbucks: 'givebucks',
gb: 'givebucks',
givebucks: function (target, room, user) {
if (!user.can('pban')) return this.errorReply("You do not have enough authority to do this.");
let parts = target.split(',');
if (!parts[1]) return this.errorReply("Usage: /givebucks [user], [amount]");
for (let u in parts) parts[u] = parts[u].trim();
let targetUser = parts[0];
if (targetUser.length < 1 || toId(targetUser).length > 18) return this.errorReply("Usernames cannot be this length.");
let amount = Math.round(Number(toId(parts[1])));
//checks
if (isNaN(amount)) return this.errorReply("The amount you give must be a number.");
if (amount < 1) return this.errorReply("You can't give less than one buck.");
if (amount > 1000) return this.errorReply("You cannot give more than 1,000 bucks at once.");
//give the bucks
Gold.updateMoney(toId(targetUser), amount);
//send replies
let amountLbl = amount + " Gold buck" + Gold.pluralFormat(amount, 's');
logTransaction(user.name + " has given " + amountLbl + " to " + targetUser + ".");
this.sendReply("You have given " + amountLbl + " to " + targetUser + ".");
if (Users(targetUser)) Users(targetUser).popup("|modal|" + user.name + " has given " + amountLbl + " to you.");
},
takebucks: 'removebucks',
removebucks: function (target, room, user) {
if (!user.can('pban')) return this.errorReply("You do not have enough authority to do this.");
let parts = target.split(',');
if (!parts[1]) return this.errorReply("Usage: /removebucks [user], [amount]");
for (let u in parts) parts[u] = parts[u].trim();
let targetUser = parts[0];
if (targetUser.length < 1 || toId(targetUser).length > 18) return this.errorReply("Usernames cannot be this length.");
let amount = Math.round(Number(toId(parts[1])));
if (amount > Gold.readMoney(targetUser)) return this.errorReply("You cannot remove more bucks than the user has.");
//checks
if (isNaN(amount)) return this.errorReply("The amount you remove must be a number.");
if (amount < 1) return this.errorReply("You can't remove less than one buck.");
if (amount > 1000) return this.errorReply("You cannot remove more than 1,000 bucks at once.");
//take the bucks
Gold.updateMoney(toId(targetUser), -amount);
//send replies
let amountLbl = amount + " Gold buck" + Gold.pluralFormat(amount, 's');
logTransaction(user.name + " has removed " + amountLbl + " from " + targetUser + ".");
this.sendReply("You have removed " + amountLbl + " from " + targetUser + ".");
if (Users(targetUser)) Users(targetUser).popup("|modal|" + user.name + " has removed " + amountLbl + " from you.");
},
tb: 'transferbucks',
transferbucks: function (target, room, user) {
let parts = target.split(',');
if (!parts[1]) return this.errorReply("Usage: /transferbucks [user], [amount]");
for (let u in parts) parts[u] = parts[u].trim();
let targetUser = parts[0];
if (targetUser.length < 1 || toId(targetUser).length > 18) return this.errorReply("Usernames cannot be this length.");
let amount = Math.round(Number(parts[1]));
//checks
if (isNaN(amount)) return this.errorReply("The amount you transfer must be a number.");
if (amount < 1) return this.errorReply("Cannot be less than 1.");
if (toId(targetUser) === user.userid) return this.errorReply("You cannot transfer bucks to yourself.");
if (Gold.readMoney(user.userid) < amount) return this.errorReply("You cannot transfer more than you have.");
//finally, transfer the bucks
Gold.updateMoney(user.userid, Number(-amount));
Gold.updateMoney(targetUser, Number(amount));
//log the transaction
let amountLbl = amount + " Gold buck" + Gold.pluralFormat(amount, 's');
logTransaction(user.name + " has transfered " + amountLbl + " to " + targetUser);
//send return messages
this.sendReply("You have transfered " + amountLbl + " to " + targetUser + ".");
let targetUserConnected = Users(parts[0]);
if (targetUserConnected) {
targetUserConnected.popup("|modal|" + user.name + " has transferred " + amountLbl + " to you.");
targetUserConnected.sendTo(room, "|raw|<b>" + Gold.nameColor(user.name, false) + " has transferred " + amountLbl + " to you.</b>");
}
},
'!atm': true,
balance: 'atm',
wallet: 'atm',
satchel: 'atm',
fannypack: 'atm',
purse: 'atm',
bag: 'atm',
bank: 'atm',
atm: function (target, room, user) {
if (!this.runBroadcast()) return;
if (!target) target = user.name;
let output = "<u>Gold Wallet:</u><br />", bucks = Gold.readMoney(target);
output += Gold.nameColor(target, true) + ' ' + (bucks === 0 ? "does not have any Gold bucks." : "has " + bucks + " Gold buck" + Gold.pluralFormat(bucks, 's') + ".");
return this.sendReplyBox(output);
},
'!richestuser': true,
whosgotthemoneyz: 'richestuser',
richestusers: 'richestuser',
richestuser: function (target, room, user) {
if (!this.runBroadcast()) return;
let number = (target && !~target.indexOf('.') && target > 1 && !isNaN(target) ? Number(target) : 10);
if (this.broadcasting && number > 10) number = 10; // limit to 10 when broadcasting
return this.sendReplyBox(Gold.richestUsers(number));
},
moneylog: function (target, room, user) {
if (!this.can('hotpatch')) return false;
if (!target) return this.errorReply("Usage: /moneylog [number] to view the last x lines OR /moneylog [text] to search for text.");
let word = false;
if (isNaN(Number(target))) word = true;
let lines = fs.readFileSync('logs/transactions.log', 'utf8').split('\n').reverse();
let output = '';
let count = 0;
let regex = new RegExp(target.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "gi");
if (word) {
output += 'Displaying last 50 lines containing "' + target + '":\n';
for (let line in lines) {
if (count >= 50) break;
if (!~lines[line].search(regex)) continue;
output += lines[line] + '\n';
count++;
}
} else {
if (target > 100) target = 100;
output = lines.slice(0, (lines.length > target ? target : lines.length));
output.unshift("Displaying the last " + (lines.length > target ? target : lines.length) + " lines:");
output = output.join('\n');
}
user.popup(output);
},
cs: 'customsymbol',
customsymbol: function (target, room, user) {
if (!user.canCustomSymbol && !Gold.hasVip(user.userid)) return this.errorReply("You don't have the permission to use this command.");
if (user.hasCustomSymbol) return this.errorReply("You currently have a custom symbol, use /resetsymbol if you would like to use this command again.");
if (!this.canTalk()) return;
if (!target || target.length > 1) return this.errorReply("/customsymbol [symbol] - changes your symbol (usergroup) to the specified symbol. The symbol can only be one character");
if (~target.indexOf('\u202e')) return this.errorReply("nono riperino");
let bannedSymbols = /[ +<>$%‽!★@&~#*卐|A-z0-9]/;
if (target.match(bannedSymbols)) return this.errorReply("That symbol is banned.");
user.getIdentity = function (roomid) {
if (this.locked) return '‽' + this.name;
if (roomid) {
let room = Rooms(roomid);
if (room.isMuted(this)) return '!' + this.name;
if (room && room.auth) {
if (room.auth[this.userid]) return room.auth[this.userid] + this.name;
if (room.isPrivate === true) return ' ' + this.name;
}
}
return target + this.name;
};
user.updateIdentity();
user.canCustomSymbol = false;
user.hasCustomSymbol = true;
return this.sendReply("Your symbol has been set.");
},
rs: 'resetsymbol',
resetsymbol: function (target, room, user) {
if (!user.hasCustomSymbol) return this.errorReply("You don't have a custom symbol!");
user.hasCustomSymbol = false;
delete user.getIdentity;
user.updateIdentity();
this.sendReply('Your symbol has been reset.');
},
'!economy': true,
economy: function (target, room, user) {
if (!this.runBroadcast()) return;
let econ = Gold.moneyCirculating();
return this.sendReplyBox("<b>Total bucks in economy:</b> " + econ[0] + "<br /><b>The average user has:</b> " + econ[1] + " bucks.<br />At least " + econ[2] + " users have 1 buck.");
},
};
// local functions
function logTransaction(message) {
if (!message) return false;
fs.appendFile('logs/transactions.log', '[' + new Date().toUTCString() + '] ' + message + '\n');
}
function updatePrices() {
let avg = Gold.moneyCirculating()[1];
prices = {
'symbol': Math.round(avg * 0.035),
// 'declare': Math.round(avg * 0.19),
'fix': Math.round(avg * 0.2),
'custom': Math.round(avg * 0.55),
'animated': Math.round(avg * 0.65),
'room': Math.round(avg * 0.53),
'musicbox': Math.round(avg * 0.4),
'trainer': Math.round(avg * 0.4),
'emote': Math.round(avg * 2.5),
'color': Math.round(avg * 4.5),
'icon': Math.round(avg * 4.5),
'pack': Math.round(avg * 1),
'vip': Math.round(avg * 25),
};
}
function shopTable(item, desc, price) {
let buttonStyle = 'border-radius: 5px; background: linear-gradient(-30deg, #fff493, #e8d95a, #fff493); color: black; text-shadow: 0px 0px 5px #d6b600; border-bottom: 2px solid #635b00; border-right: 2px solid #968900; width: 100%;';
let descStyle = 'border-radius: 5px; border: 1px solid #635b00; background: #fff8b5; color: black;';
let priceStyle = 'border-radius: 5px; border: 1px solid #635b00; background: #fff8b5; color: black; font-weight: bold; text-align: center;';
return '<tr><td style="' + descStyle + '"><button title="Click this button to buy a(n) ' + item + ' from the shop." style="' + buttonStyle + '" name="send" value="/buy ' + item + '">' + item + '</button></td><td style="' + descStyle + '">' + desc + '</td><td style="' + priceStyle + '">' + price + '</td></tr>';
}
| {
return '<a href="' + link + '" target="_blank">' + formatted + '</a>';
} | identifier_body |
board.js | (function () {
window.SnakeGame = window.SnakeGame || {};
var Board = SnakeGame.Board = function (options) {
options = options || {};
this.height = options.height || Board.HEIGHT;
this.width = options.width || Board.WIDTH;
this.player = options.player || new SnakeGame.Snake(this);
this.opponent = options.opponent || new SnakeGame.SnakeAI(this);
this.placeApple();
};
Board.HEIGHT = 24;
Board.WIDTH = 24;
Board.prototype.placeApple = function () {
var emptySpaces = this.emptySpaces();
var randomSpaceIdx = Math.floor(Math.random() * emptySpaces.length);
this.applePos = emptySpaces[randomSpaceIdx];
};
Board.prototype.emptySpaces = function () {
var emptySpaces = [];
for (row = 0; row < this.height; row++) {
for (col = 0; col < this.width; col++) {
var pos = [row, col];
var segments = this.player.segments.concat(this.opponent.segments);
if (!SnakeGame.Util.samePos(this.applePos, pos) &&
!SnakeGame.Util.inSegments(segments, pos)) {
emptySpaces.push([row, col]);
}
}
}
return emptySpaces;
}
Board.prototype.render = function () {
var board = [];
for (row = 0; row < this.height; row++) { | var pos = row + "-" + col;
var $li = $("<li>").attr("id", pos);
board[row].append($li);
}
}
return board;
}
Board.prototype.inRange = function (pos) {
return (pos[0] >= 0 && pos[0] < this.height) &&
(pos[1] >= 0 && pos[1] < this.width);
}
Board.prototype.winner = function () {
if (this.player.isDead) {
return this.opponent;
} else if (this.opponent.isDead) {
return this.player;
}
}
Board.prototype.isOver = function () {
return !!this.winner();
}
})(); | board[row] = $("<ul>").addClass("snake-row").addClass("group");
for (col = 0; col < this.width; col++) { | random_line_split |
test-localizer.js | import globalize from 'globalize';
import configure from '../src/configure';
export default function testLocalizer() {
function getCulture(culture){
return culture ? globalize.findClosestCulture(culture) : globalize.culture()
}
function shortDay(dayOfTheWeek, culture) {
let names = getCulture(culture).calendar.days.namesShort;
return names[dayOfTheWeek.getDay()];
}
var date = {
formats: {
date: 'd',
time: 't',
default: 'f',
header: 'MMMM yyyy',
footer: 'D',
weekday: shortDay,
dayOfMonth: 'dd',
month: 'MMM',
year: 'yyyy',
decade: 'yyyy',
century: 'yyyy',
},
firstOfWeek(culture) {
culture = getCulture(culture)
return (culture && culture.calendar.firstDay) || 0
},
parse(value, format, culture) | ,
format(value, format, culture){
return globalize.format(value, format, culture)
}
}
function formatData(format, _culture){
var culture = getCulture(_culture)
, numFormat = culture.numberFormat
if (typeof format === 'string') {
if (format.indexOf('p') !== -1) numFormat = numFormat.percent
if (format.indexOf('c') !== -1) numFormat = numFormat.curency
}
return numFormat
}
var number = {
formats: {
default: 'D'
},
parse(value, culture) {
return globalize.parseFloat(value, 10, culture)
},
format(value, format, culture){
return globalize.format(value, format, culture)
},
decimalChar(format, culture){
var data = formatData(format, culture)
return data['.'] || '.'
},
precision(format, _culture){
var data = formatData(format, _culture)
if (typeof format === 'string' && format.length > 1)
return parseFloat(format.substr(1))
return data ? data.decimals : null
}
}
configure.setLocalizers({ date, number })
}
| {
return globalize.parseDate(value, format, culture)
} | identifier_body |
test-localizer.js | import globalize from 'globalize';
import configure from '../src/configure';
export default function testLocalizer() {
function getCulture(culture){
return culture ? globalize.findClosestCulture(culture) : globalize.culture()
}
function shortDay(dayOfTheWeek, culture) {
let names = getCulture(culture).calendar.days.namesShort;
return names[dayOfTheWeek.getDay()];
}
var date = {
formats: {
date: 'd',
time: 't',
default: 'f',
header: 'MMMM yyyy',
footer: 'D',
weekday: shortDay,
dayOfMonth: 'dd',
month: 'MMM',
year: 'yyyy',
decade: 'yyyy',
century: 'yyyy',
},
firstOfWeek(culture) {
culture = getCulture(culture)
return (culture && culture.calendar.firstDay) || 0
},
parse(value, format, culture){
return globalize.parseDate(value, format, culture)
},
format(value, format, culture){
return globalize.format(value, format, culture)
}
}
function formatData(format, _culture){
var culture = getCulture(_culture)
, numFormat = culture.numberFormat
if (typeof format === 'string') {
if (format.indexOf('p') !== -1) numFormat = numFormat.percent
if (format.indexOf('c') !== -1) numFormat = numFormat.curency
}
return numFormat
}
var number = {
formats: {
default: 'D'
},
parse(value, culture) {
return globalize.parseFloat(value, 10, culture)
},
format(value, format, culture){
return globalize.format(value, format, culture)
},
decimalChar(format, culture){
var data = formatData(format, culture)
return data['.'] || '.'
},
| (format, _culture){
var data = formatData(format, _culture)
if (typeof format === 'string' && format.length > 1)
return parseFloat(format.substr(1))
return data ? data.decimals : null
}
}
configure.setLocalizers({ date, number })
}
| precision | identifier_name |
test-localizer.js | import globalize from 'globalize';
import configure from '../src/configure';
export default function testLocalizer() {
function getCulture(culture){
return culture ? globalize.findClosestCulture(culture) : globalize.culture()
}
function shortDay(dayOfTheWeek, culture) {
let names = getCulture(culture).calendar.days.namesShort;
return names[dayOfTheWeek.getDay()];
}
var date = {
formats: {
date: 'd',
time: 't',
default: 'f',
header: 'MMMM yyyy',
footer: 'D',
weekday: shortDay,
dayOfMonth: 'dd',
month: 'MMM',
year: 'yyyy',
decade: 'yyyy',
century: 'yyyy',
},
firstOfWeek(culture) {
culture = getCulture(culture)
return (culture && culture.calendar.firstDay) || 0
}, |
format(value, format, culture){
return globalize.format(value, format, culture)
}
}
function formatData(format, _culture){
var culture = getCulture(_culture)
, numFormat = culture.numberFormat
if (typeof format === 'string') {
if (format.indexOf('p') !== -1) numFormat = numFormat.percent
if (format.indexOf('c') !== -1) numFormat = numFormat.curency
}
return numFormat
}
var number = {
formats: {
default: 'D'
},
parse(value, culture) {
return globalize.parseFloat(value, 10, culture)
},
format(value, format, culture){
return globalize.format(value, format, culture)
},
decimalChar(format, culture){
var data = formatData(format, culture)
return data['.'] || '.'
},
precision(format, _culture){
var data = formatData(format, _culture)
if (typeof format === 'string' && format.length > 1)
return parseFloat(format.substr(1))
return data ? data.decimals : null
}
}
configure.setLocalizers({ date, number })
} |
parse(value, format, culture){
return globalize.parseDate(value, format, culture)
}, | random_line_split |
yamsdaq_models.py | from sqlalchemy import Column, ForeignKey, Integer, String, Text, DateTime, Float
from models import Base, Account
from sqlalchemy.orm import relationship
from datetime import datetime
# STOCK EXCHANGE
class Company(Base):
__tablename__ = 'companies'
code = Column(String(4), primary_key=True)
name = Column(Text, nullable=False)
submission_id = Column(Text, nullable=False)
value_points = relationship('ValuePoint', back_populates="company", cascade="all, delete, delete-orphan")
owned_stocks = relationship('Stock', back_populates="company", cascade="all, delete, delete-orphan")
def __repr__(self):
return '<Company %r (%r)>' % (self.name, self.code)
class | (Base):
__tablename__ = 'valuepoints'
id = Column(Integer, primary_key=True)
datetime = Column(DateTime, nullable=False, default=datetime.utcnow)
value = Column(Float, nullable=False)
company_code = Column(String(4), ForeignKey('companies.code'), nullable=False)
company = relationship(Company, back_populates="value_points")
def __repr__(self):
return '<Value of %r at %r: $%.2f>' % (self.company.name, self.datetime, self.value)
class Stock(Base):
__tablename__ = 'stocks'
id = Column(Integer, primary_key=True)
count = Column(Integer, nullable=False)
value_per_stock_at_purchase = Column(Float, nullable=False)
owner_number = Column(Integer, ForeignKey('accounts.number'), nullable=False)
owner = relationship(Account, back_populates="owned_stocks")
company_code = Column(String(4), ForeignKey('companies.code'), nullable=False)
company = relationship(Company, back_populates="owned_stocks")
Account.owned_stocks = relationship('Stock', back_populates="owner", cascade="all, delete, delete-orphan") | ValuePoint | identifier_name |
yamsdaq_models.py | from sqlalchemy import Column, ForeignKey, Integer, String, Text, DateTime, Float
from models import Base, Account
from sqlalchemy.orm import relationship
from datetime import datetime
# STOCK EXCHANGE
class Company(Base):
__tablename__ = 'companies'
code = Column(String(4), primary_key=True)
name = Column(Text, nullable=False)
submission_id = Column(Text, nullable=False)
value_points = relationship('ValuePoint', back_populates="company", cascade="all, delete, delete-orphan")
owned_stocks = relationship('Stock', back_populates="company", cascade="all, delete, delete-orphan")
def __repr__(self):
|
class ValuePoint(Base):
__tablename__ = 'valuepoints'
id = Column(Integer, primary_key=True)
datetime = Column(DateTime, nullable=False, default=datetime.utcnow)
value = Column(Float, nullable=False)
company_code = Column(String(4), ForeignKey('companies.code'), nullable=False)
company = relationship(Company, back_populates="value_points")
def __repr__(self):
return '<Value of %r at %r: $%.2f>' % (self.company.name, self.datetime, self.value)
class Stock(Base):
__tablename__ = 'stocks'
id = Column(Integer, primary_key=True)
count = Column(Integer, nullable=False)
value_per_stock_at_purchase = Column(Float, nullable=False)
owner_number = Column(Integer, ForeignKey('accounts.number'), nullable=False)
owner = relationship(Account, back_populates="owned_stocks")
company_code = Column(String(4), ForeignKey('companies.code'), nullable=False)
company = relationship(Company, back_populates="owned_stocks")
Account.owned_stocks = relationship('Stock', back_populates="owner", cascade="all, delete, delete-orphan") | return '<Company %r (%r)>' % (self.name, self.code) | identifier_body |
yamsdaq_models.py | from sqlalchemy import Column, ForeignKey, Integer, String, Text, DateTime, Float
from models import Base, Account
from sqlalchemy.orm import relationship
from datetime import datetime
# STOCK EXCHANGE
class Company(Base):
__tablename__ = 'companies'
code = Column(String(4), primary_key=True)
name = Column(Text, nullable=False)
submission_id = Column(Text, nullable=False)
value_points = relationship('ValuePoint', back_populates="company", cascade="all, delete, delete-orphan")
owned_stocks = relationship('Stock', back_populates="company", cascade="all, delete, delete-orphan")
def __repr__(self):
return '<Company %r (%r)>' % (self.name, self.code)
class ValuePoint(Base):
__tablename__ = 'valuepoints'
id = Column(Integer, primary_key=True)
datetime = Column(DateTime, nullable=False, default=datetime.utcnow)
value = Column(Float, nullable=False)
company_code = Column(String(4), ForeignKey('companies.code'), nullable=False)
company = relationship(Company, back_populates="value_points")
def __repr__(self):
return '<Value of %r at %r: $%.2f>' % (self.company.name, self.datetime, self.value)
class Stock(Base):
__tablename__ = 'stocks'
| id = Column(Integer, primary_key=True)
count = Column(Integer, nullable=False)
value_per_stock_at_purchase = Column(Float, nullable=False)
owner_number = Column(Integer, ForeignKey('accounts.number'), nullable=False)
owner = relationship(Account, back_populates="owned_stocks")
company_code = Column(String(4), ForeignKey('companies.code'), nullable=False)
company = relationship(Company, back_populates="owned_stocks")
Account.owned_stocks = relationship('Stock', back_populates="owner", cascade="all, delete, delete-orphan") | random_line_split | |
jquery.media.template.shockplayer.js | /**
* Copyright (c) 2010 Alethia Inc,
* http://www.alethia-inc.com
* Developed by Travis Tidwell | travist at alethia-inc.com
*
* License: GPL version 3.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file serves as a starting point for new template designs. Below you will
* see a listing of all media player "hooks" that can be implemented by the
* template to customize the functionality of this template.
*/
(function($) {
jQuery.media = jQuery.media ? jQuery.media : {};
// Add the menu callback.
window.onFlashPlayerMenu = function( id ) {
var player = jQuery.media.players[id];
player.showMenu( !player.menuOn );
};
jQuery.media.templates = jQuery.extend( {}, {
"shockplayer" : function( mediaplayer, settings ) {
return new (function( mediaplayer, settings ) {
settings = jQuery.media.utils.getSettings(settings);
var _this = this;
this.mediaDisplay = null;
this.player = null;
this.logo = null;
this.fullScreenButton = null;
this.prev = null;
this.next = null;
this.info = null;
this.nodeInfo = null;
/**
* Called just before the mediaplayer is ready to show this template to the user.
* This function is used to initialize the template given the current state of
* settings passed to the player. You can use this function to initialize variables,
* change width's and height's of elements based on certain parameters passed to the
* media player.
*
* @param - The settings object.
*/
this.initialize = function( settings ) {
// Get the player elements.
this.mediaDisplay = mediaplayer.node.player.media;
this.player = mediaplayer.node.player;
this.volumeBar = $('#mediaplayer_audioBar');
this.logo = this.player.logo;
this.prev = $('#mediaplayer_prev');
this.next = $('#mediaplayer_next');
this.info = $('#mediaplayer_bigPlay');
this.fullScreenButton = mediaplayer.display.find("#mediafront_resizeScreen").click( function( event ) {
event.preventDefault();
mediaplayer.onFullScreen(!mediaplayer.fullScreen);
});
// Hide the volume bar by default.
this.volumeBar.hide();
this.fullScreenButton.find(".off").hide();
// Show the control bar, and then hide it after 5 seconds of inactivity.
jQuery.media.utils.showThenHide( mediaplayer.controller.display, "display", null, "slow", function() {
mediaplayer.node.player.play.css("bottom", "5px");
});
jQuery.media.utils.showThenHide( this.fullScreenButton, "fullscreen" );
// Make sure that we show the volume bar when they hover over the mute button.
// Add a timer to the mouse move of the display to show the control bar and logo on mouse move.
mediaplayer.display.bind("mousemove", function() {
mediaplayer.node.player.play.css("bottom", "45px");
if(!mediaplayer.node.player.usePlayerControls) {
jQuery.media.utils.showThenHide( _this.prev, "prev", "fast", "fast" );
jQuery.media.utils.showThenHide( _this.next, "next", "fast", "fast" );
jQuery.media.utils.showThenHide( _this.info, "info", "fast", "fast" );
jQuery.media.utils.showThenHide( _this.fullScreenButton, "fullscreen" );
if( jQuery.media.hasMedia ) {
jQuery.media.utils.showThenHide( mediaplayer.controller.display, "display", "fast", "slow", function() {
mediaplayer.node.player.play.css("bottom", "5px");
});
}
}
});
// Show the volume bar when they hover over the mute button.
mediaplayer.controller.mute.display.bind("mousemove", function() {
if( jQuery.media.hasMedia ) {
jQuery.media.utils.showThenHide( _this.volumeBar, "volumeBar", "fast", "fast" );
}
});
// Stop the hide on both the control bar and the volumeBar.
jQuery.media.utils.stopHideOnOver( mediaplayer.controller.display, "display" );
jQuery.media.utils.stopHideOnOver( this.fullScreenButton, "fullscreen" );
jQuery.media.utils.stopHideOnOver( this.volumeBar, "volumeBar" );
jQuery.media.utils.stopHideOnOver( this.info, 'info');
jQuery.media.utils.stopHideOnOver( this.prev, "prev" );
jQuery.media.utils.stopHideOnOver( this.next, "next" );
// Show the media controls.
this.player.showControls(true);
};
/**
* Returns our template settings overrides. This is used to force a particular
* setting to be a certain value if the user does not provide that parameter.
*
* @return - An associative array of our settings. We can use this to override any
* default settings for the player as well as default ids.
*/
this.getSettings = function() {
return {
volumeVertical:true,
showInfo:true
};
};
/**
* Called when the user presses the menu button.
*
* @param - If the menu should be on (true) or off (false).
*/
this.onMenu = function( on ) {
if( mediaplayer.menu ) {
if( on ) {
mediaplayer.menu.display.show( "normal" );
}
else {
mediaplayer.menu.display.hide( "normal" );
}
}
};
/**
* Called when the user presses the fullscreen button.
*
* @param - If the player is in fullscreen (true) or normal mode (false).
*/
this.onFullScreen = function( on ) {
if( on ) {
this.fullScreenButton.find(".on").hide();
this.fullScreenButton.find(".off").show();
this.player.display.addClass("fullscreen");
mediaplayer.menu.display.addClass("fullscreen");
// Hide the players controls, and show the HTML controls.
if (this.player && !mediaplayer.node.player.usePlayerControls) {
this.player.showControls(true);
}
}
else {
this.fullScreenButton.find(".on").show();
this.fullScreenButton.find(".off").hide();
this.player.display.removeClass("fullscreen");
mediaplayer.menu.display.removeClass("fullscreen");
// Hide the players controls, and show the HTML controls.
if (this.player && !mediaplayer.node.player.usePlayerControls) {
this.player.showControls(false);
}
}
};
/**
* Selects or Deselects a menu item.
*
* @param - The link jQuery object
*/
this.onMenuSelect = function( link, contents, selected ) {
if( selected ) {
contents.show("normal");
link.addClass('active');
}
else {
contents.hide("normal");
link.removeClass('active');
} | mediaplayer.node.player.play.show();
};
// See if we are using FireFox with an mp4 video.
this.isFireFoxWithH264 = function() {
if (this.player && this.player.media && this.player.media.mediaFile) {
var ext = this.player.media.mediaFile.getFileExtension();
return jQuery.browser.mozilla && (ext == 'mp4' || ext == 'm4v');
}
else {
return false;
}
};
this.onMediaUpdate = function( data ) {
if (data.type == "playerready" && this.isFireFoxWithH264()) {
mediaplayer.node.player.media.player.player.setTitle(this.nodeInfo.title);
mediaplayer.showNativeControls(true);
this.fullScreenButton.hide();
this.prev.hide();
this.next.hide();
this.info.hide();
}
if( mediaplayer.controller && mediaplayer.node ) {
if( data.type == "reset" ) {
jQuery.media.hasMedia = true;
if (!mediaplayer.node.player.usePlayerControls) {
mediaplayer.controller.display.show();
}
this.player.display.removeClass("nomedia");
}
else if( data.type == "nomedia" ) {
jQuery.media.hasMedia = false;
mediaplayer.controller.display.hide();
this.player.display.addClass("nomedia");
}
}
};
/**
* This function is currently stubbed out.
* You can implement it and hook into the time display by
* reassigning this as follows...
*
* this.formatTime = function( time ) {
* }
*
* You can see the default implementation of this function
* by opening js/source/jquery.media.control.js on the line
* after it says this.formatTime = ...
*/
this.formatTime = false;
})( mediaplayer, settings );
}
}, jQuery.media.templates );
})(jQuery); | };
this.onNodeLoad = function( data ) {
this.nodeInfo = data; | random_line_split |
jquery.media.template.shockplayer.js | /**
* Copyright (c) 2010 Alethia Inc,
* http://www.alethia-inc.com
* Developed by Travis Tidwell | travist at alethia-inc.com
*
* License: GPL version 3.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file serves as a starting point for new template designs. Below you will
* see a listing of all media player "hooks" that can be implemented by the
* template to customize the functionality of this template.
*/
(function($) {
jQuery.media = jQuery.media ? jQuery.media : {};
// Add the menu callback.
window.onFlashPlayerMenu = function( id ) {
var player = jQuery.media.players[id];
player.showMenu( !player.menuOn );
};
jQuery.media.templates = jQuery.extend( {}, {
"shockplayer" : function( mediaplayer, settings ) {
return new (function( mediaplayer, settings ) {
settings = jQuery.media.utils.getSettings(settings);
var _this = this;
this.mediaDisplay = null;
this.player = null;
this.logo = null;
this.fullScreenButton = null;
this.prev = null;
this.next = null;
this.info = null;
this.nodeInfo = null;
/**
* Called just before the mediaplayer is ready to show this template to the user.
* This function is used to initialize the template given the current state of
* settings passed to the player. You can use this function to initialize variables,
* change width's and height's of elements based on certain parameters passed to the
* media player.
*
* @param - The settings object.
*/
this.initialize = function( settings ) {
// Get the player elements.
this.mediaDisplay = mediaplayer.node.player.media;
this.player = mediaplayer.node.player;
this.volumeBar = $('#mediaplayer_audioBar');
this.logo = this.player.logo;
this.prev = $('#mediaplayer_prev');
this.next = $('#mediaplayer_next');
this.info = $('#mediaplayer_bigPlay');
this.fullScreenButton = mediaplayer.display.find("#mediafront_resizeScreen").click( function( event ) {
event.preventDefault();
mediaplayer.onFullScreen(!mediaplayer.fullScreen);
});
// Hide the volume bar by default.
this.volumeBar.hide();
this.fullScreenButton.find(".off").hide();
// Show the control bar, and then hide it after 5 seconds of inactivity.
jQuery.media.utils.showThenHide( mediaplayer.controller.display, "display", null, "slow", function() {
mediaplayer.node.player.play.css("bottom", "5px");
});
jQuery.media.utils.showThenHide( this.fullScreenButton, "fullscreen" );
// Make sure that we show the volume bar when they hover over the mute button.
// Add a timer to the mouse move of the display to show the control bar and logo on mouse move.
mediaplayer.display.bind("mousemove", function() {
mediaplayer.node.player.play.css("bottom", "45px");
if(!mediaplayer.node.player.usePlayerControls) {
jQuery.media.utils.showThenHide( _this.prev, "prev", "fast", "fast" );
jQuery.media.utils.showThenHide( _this.next, "next", "fast", "fast" );
jQuery.media.utils.showThenHide( _this.info, "info", "fast", "fast" );
jQuery.media.utils.showThenHide( _this.fullScreenButton, "fullscreen" );
if( jQuery.media.hasMedia ) |
}
});
// Show the volume bar when they hover over the mute button.
mediaplayer.controller.mute.display.bind("mousemove", function() {
if( jQuery.media.hasMedia ) {
jQuery.media.utils.showThenHide( _this.volumeBar, "volumeBar", "fast", "fast" );
}
});
// Stop the hide on both the control bar and the volumeBar.
jQuery.media.utils.stopHideOnOver( mediaplayer.controller.display, "display" );
jQuery.media.utils.stopHideOnOver( this.fullScreenButton, "fullscreen" );
jQuery.media.utils.stopHideOnOver( this.volumeBar, "volumeBar" );
jQuery.media.utils.stopHideOnOver( this.info, 'info');
jQuery.media.utils.stopHideOnOver( this.prev, "prev" );
jQuery.media.utils.stopHideOnOver( this.next, "next" );
// Show the media controls.
this.player.showControls(true);
};
/**
* Returns our template settings overrides. This is used to force a particular
* setting to be a certain value if the user does not provide that parameter.
*
* @return - An associative array of our settings. We can use this to override any
* default settings for the player as well as default ids.
*/
this.getSettings = function() {
return {
volumeVertical:true,
showInfo:true
};
};
/**
* Called when the user presses the menu button.
*
* @param - If the menu should be on (true) or off (false).
*/
this.onMenu = function( on ) {
if( mediaplayer.menu ) {
if( on ) {
mediaplayer.menu.display.show( "normal" );
}
else {
mediaplayer.menu.display.hide( "normal" );
}
}
};
/**
* Called when the user presses the fullscreen button.
*
* @param - If the player is in fullscreen (true) or normal mode (false).
*/
this.onFullScreen = function( on ) {
if( on ) {
this.fullScreenButton.find(".on").hide();
this.fullScreenButton.find(".off").show();
this.player.display.addClass("fullscreen");
mediaplayer.menu.display.addClass("fullscreen");
// Hide the players controls, and show the HTML controls.
if (this.player && !mediaplayer.node.player.usePlayerControls) {
this.player.showControls(true);
}
}
else {
this.fullScreenButton.find(".on").show();
this.fullScreenButton.find(".off").hide();
this.player.display.removeClass("fullscreen");
mediaplayer.menu.display.removeClass("fullscreen");
// Hide the players controls, and show the HTML controls.
if (this.player && !mediaplayer.node.player.usePlayerControls) {
this.player.showControls(false);
}
}
};
/**
* Selects or Deselects a menu item.
*
* @param - The link jQuery object
*/
this.onMenuSelect = function( link, contents, selected ) {
if( selected ) {
contents.show("normal");
link.addClass('active');
}
else {
contents.hide("normal");
link.removeClass('active');
}
};
this.onNodeLoad = function( data ) {
this.nodeInfo = data;
mediaplayer.node.player.play.show();
};
// See if we are using FireFox with an mp4 video.
this.isFireFoxWithH264 = function() {
if (this.player && this.player.media && this.player.media.mediaFile) {
var ext = this.player.media.mediaFile.getFileExtension();
return jQuery.browser.mozilla && (ext == 'mp4' || ext == 'm4v');
}
else {
return false;
}
};
this.onMediaUpdate = function( data ) {
if (data.type == "playerready" && this.isFireFoxWithH264()) {
mediaplayer.node.player.media.player.player.setTitle(this.nodeInfo.title);
mediaplayer.showNativeControls(true);
this.fullScreenButton.hide();
this.prev.hide();
this.next.hide();
this.info.hide();
}
if( mediaplayer.controller && mediaplayer.node ) {
if( data.type == "reset" ) {
jQuery.media.hasMedia = true;
if (!mediaplayer.node.player.usePlayerControls) {
mediaplayer.controller.display.show();
}
this.player.display.removeClass("nomedia");
}
else if( data.type == "nomedia" ) {
jQuery.media.hasMedia = false;
mediaplayer.controller.display.hide();
this.player.display.addClass("nomedia");
}
}
};
/**
* This function is currently stubbed out.
* You can implement it and hook into the time display by
* reassigning this as follows...
*
* this.formatTime = function( time ) {
* }
*
* You can see the default implementation of this function
* by opening js/source/jquery.media.control.js on the line
* after it says this.formatTime = ...
*/
this.formatTime = false;
})( mediaplayer, settings );
}
}, jQuery.media.templates );
})(jQuery);
| {
jQuery.media.utils.showThenHide( mediaplayer.controller.display, "display", "fast", "slow", function() {
mediaplayer.node.player.play.css("bottom", "5px");
});
} | conditional_block |
status.py | import requests
class Status(object):
SKIP_LOCALES = ['en_US']
def __init__(self, url, app=None, highlight=None):
self.url = url
self.app = app
self.highlight = highlight or []
self.data = []
self.created = None
def get_data(self):
if self.data:
return
resp = requests.get(self.url)
if resp.status_code != 200:
resp.raise_for_status()
self.data = resp.json()
self.created = self.data[-1]['created']
def summary(self):
"""Generates summary data of today's state"""
self.get_data()
highlight = self.highlight
last_item = self.data[-1]
output = {}
output['app'] = self.app or 'ALL'
data = last_item['locales']
if self.app:
get_item = lambda x: x['apps'][self.app]
else:
get_item = lambda x: x
apps = data.items()[0][1]['apps'].keys()
apps.sort()
output['apps'] = apps
items = [item for item in data.items() if item[0] not in highlight]
hitems = [item for item in data.items() if item[0] in highlight]
highlighted = []
if hitems:
for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']):
if loc in self.SKIP_LOCALES:
continue
item = get_item(loc_data)
total = item.get('total', -1)
translated = item.get('translated', -1)
percent = item.get('percent', -1)
untranslated_words = item.get('untranslated_words', -1)
highlighted.append({
'locale': loc,
'percent': percent,
'total': total,
'translated': translated,
'untranslated': total - translated,
'untranslated_words': untranslated_words
})
output['highlighted'] = highlighted
locales = []
for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']):
if loc in self.SKIP_LOCALES:
continue
item = get_item(loc_data)
total = item.get('total', -1)
translated = item.get('translated', -1)
percent = item.get('percent', -1)
untranslated_words = item.get('untranslated_words', -1)
locales.append({
'locale': loc,
'percent': percent,
'total': total,
'translated': translated,
'untranslated': total - translated,
'untranslated_words': untranslated_words
})
output['locales'] = locales
output['created'] = self.created
return output
def _mark_movement(self, data):
"""For each item, converts to a tuple of (movement, item)"""
ret = []
prev_day = None
for i, day in enumerate(data):
if i == 0:
ret.append(('', day))
prev_day = day
continue
if prev_day > day:
|
elif prev_day < day:
item = ('up', day)
else:
item = ('equal', day)
prev_day = day
ret.append(item)
return ret
def history(self):
self.get_data()
data = self.data
highlight = self.highlight
app = self.app
# Get a list of the locales we'll iterate through
locales = sorted(data[-1]['locales'].keys())
num_days = 14
# Truncate the data to what we want to look at
data = data[-num_days:]
if app:
get_data = lambda x: x['apps'][app]['percent']
else:
get_data = lambda x: x['percent']
hlocales = [loc for loc in locales if loc in highlight]
locales = [loc for loc in locales if loc not in highlight]
output = {}
output['app'] = self.app or 'All'
output['headers'] = [item['created'] for item in data]
output['highlighted'] = sorted(
(loc, self._mark_movement(get_data(day['locales'][loc]) for day in data))
for loc in hlocales
)
output['locales'] = sorted(
(loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data))
for loc in locales
)
output['created'] = self.created
return output
| item = ('down', day) | conditional_block |
status.py | import requests
class Status(object):
SKIP_LOCALES = ['en_US']
def __init__(self, url, app=None, highlight=None):
self.url = url
self.app = app
self.highlight = highlight or []
self.data = []
self.created = None
def get_data(self):
|
def summary(self):
"""Generates summary data of today's state"""
self.get_data()
highlight = self.highlight
last_item = self.data[-1]
output = {}
output['app'] = self.app or 'ALL'
data = last_item['locales']
if self.app:
get_item = lambda x: x['apps'][self.app]
else:
get_item = lambda x: x
apps = data.items()[0][1]['apps'].keys()
apps.sort()
output['apps'] = apps
items = [item for item in data.items() if item[0] not in highlight]
hitems = [item for item in data.items() if item[0] in highlight]
highlighted = []
if hitems:
for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']):
if loc in self.SKIP_LOCALES:
continue
item = get_item(loc_data)
total = item.get('total', -1)
translated = item.get('translated', -1)
percent = item.get('percent', -1)
untranslated_words = item.get('untranslated_words', -1)
highlighted.append({
'locale': loc,
'percent': percent,
'total': total,
'translated': translated,
'untranslated': total - translated,
'untranslated_words': untranslated_words
})
output['highlighted'] = highlighted
locales = []
for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']):
if loc in self.SKIP_LOCALES:
continue
item = get_item(loc_data)
total = item.get('total', -1)
translated = item.get('translated', -1)
percent = item.get('percent', -1)
untranslated_words = item.get('untranslated_words', -1)
locales.append({
'locale': loc,
'percent': percent,
'total': total,
'translated': translated,
'untranslated': total - translated,
'untranslated_words': untranslated_words
})
output['locales'] = locales
output['created'] = self.created
return output
def _mark_movement(self, data):
"""For each item, converts to a tuple of (movement, item)"""
ret = []
prev_day = None
for i, day in enumerate(data):
if i == 0:
ret.append(('', day))
prev_day = day
continue
if prev_day > day:
item = ('down', day)
elif prev_day < day:
item = ('up', day)
else:
item = ('equal', day)
prev_day = day
ret.append(item)
return ret
def history(self):
self.get_data()
data = self.data
highlight = self.highlight
app = self.app
# Get a list of the locales we'll iterate through
locales = sorted(data[-1]['locales'].keys())
num_days = 14
# Truncate the data to what we want to look at
data = data[-num_days:]
if app:
get_data = lambda x: x['apps'][app]['percent']
else:
get_data = lambda x: x['percent']
hlocales = [loc for loc in locales if loc in highlight]
locales = [loc for loc in locales if loc not in highlight]
output = {}
output['app'] = self.app or 'All'
output['headers'] = [item['created'] for item in data]
output['highlighted'] = sorted(
(loc, self._mark_movement(get_data(day['locales'][loc]) for day in data))
for loc in hlocales
)
output['locales'] = sorted(
(loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data))
for loc in locales
)
output['created'] = self.created
return output
| if self.data:
return
resp = requests.get(self.url)
if resp.status_code != 200:
resp.raise_for_status()
self.data = resp.json()
self.created = self.data[-1]['created'] | identifier_body |
status.py | import requests
class Status(object):
SKIP_LOCALES = ['en_US']
def __init__(self, url, app=None, highlight=None):
self.url = url
self.app = app
self.highlight = highlight or []
self.data = []
self.created = None
def get_data(self):
if self.data:
return
resp = requests.get(self.url)
if resp.status_code != 200:
resp.raise_for_status()
self.data = resp.json()
self.created = self.data[-1]['created']
def summary(self):
"""Generates summary data of today's state"""
self.get_data()
highlight = self.highlight
last_item = self.data[-1]
output = {}
output['app'] = self.app or 'ALL'
data = last_item['locales']
if self.app:
get_item = lambda x: x['apps'][self.app]
else:
get_item = lambda x: x
apps = data.items()[0][1]['apps'].keys()
apps.sort()
output['apps'] = apps
items = [item for item in data.items() if item[0] not in highlight]
hitems = [item for item in data.items() if item[0] in highlight]
highlighted = []
if hitems:
for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']):
if loc in self.SKIP_LOCALES:
continue
item = get_item(loc_data)
total = item.get('total', -1)
translated = item.get('translated', -1)
percent = item.get('percent', -1)
untranslated_words = item.get('untranslated_words', -1)
highlighted.append({
'locale': loc,
'percent': percent,
'total': total,
'translated': translated,
'untranslated': total - translated,
'untranslated_words': untranslated_words
})
output['highlighted'] = highlighted
locales = []
for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']):
if loc in self.SKIP_LOCALES:
continue
item = get_item(loc_data)
total = item.get('total', -1)
translated = item.get('translated', -1)
percent = item.get('percent', -1)
untranslated_words = item.get('untranslated_words', -1)
locales.append({
'locale': loc,
'percent': percent,
'total': total,
'translated': translated,
'untranslated': total - translated,
'untranslated_words': untranslated_words
})
output['locales'] = locales
output['created'] = self.created
return output
def _mark_movement(self, data):
"""For each item, converts to a tuple of (movement, item)"""
ret = []
prev_day = None
for i, day in enumerate(data):
if i == 0:
ret.append(('', day))
prev_day = day
continue
if prev_day > day:
item = ('down', day) | else:
item = ('equal', day)
prev_day = day
ret.append(item)
return ret
def history(self):
self.get_data()
data = self.data
highlight = self.highlight
app = self.app
# Get a list of the locales we'll iterate through
locales = sorted(data[-1]['locales'].keys())
num_days = 14
# Truncate the data to what we want to look at
data = data[-num_days:]
if app:
get_data = lambda x: x['apps'][app]['percent']
else:
get_data = lambda x: x['percent']
hlocales = [loc for loc in locales if loc in highlight]
locales = [loc for loc in locales if loc not in highlight]
output = {}
output['app'] = self.app or 'All'
output['headers'] = [item['created'] for item in data]
output['highlighted'] = sorted(
(loc, self._mark_movement(get_data(day['locales'][loc]) for day in data))
for loc in hlocales
)
output['locales'] = sorted(
(loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data))
for loc in locales
)
output['created'] = self.created
return output | elif prev_day < day:
item = ('up', day) | random_line_split |
status.py | import requests
class Status(object):
SKIP_LOCALES = ['en_US']
def __init__(self, url, app=None, highlight=None):
self.url = url
self.app = app
self.highlight = highlight or []
self.data = []
self.created = None
def | (self):
if self.data:
return
resp = requests.get(self.url)
if resp.status_code != 200:
resp.raise_for_status()
self.data = resp.json()
self.created = self.data[-1]['created']
def summary(self):
"""Generates summary data of today's state"""
self.get_data()
highlight = self.highlight
last_item = self.data[-1]
output = {}
output['app'] = self.app or 'ALL'
data = last_item['locales']
if self.app:
get_item = lambda x: x['apps'][self.app]
else:
get_item = lambda x: x
apps = data.items()[0][1]['apps'].keys()
apps.sort()
output['apps'] = apps
items = [item for item in data.items() if item[0] not in highlight]
hitems = [item for item in data.items() if item[0] in highlight]
highlighted = []
if hitems:
for loc, loc_data in sorted(hitems, key=lambda x: -x[1]['percent']):
if loc in self.SKIP_LOCALES:
continue
item = get_item(loc_data)
total = item.get('total', -1)
translated = item.get('translated', -1)
percent = item.get('percent', -1)
untranslated_words = item.get('untranslated_words', -1)
highlighted.append({
'locale': loc,
'percent': percent,
'total': total,
'translated': translated,
'untranslated': total - translated,
'untranslated_words': untranslated_words
})
output['highlighted'] = highlighted
locales = []
for loc, loc_data in sorted(items, key=lambda x: -x[1]['percent']):
if loc in self.SKIP_LOCALES:
continue
item = get_item(loc_data)
total = item.get('total', -1)
translated = item.get('translated', -1)
percent = item.get('percent', -1)
untranslated_words = item.get('untranslated_words', -1)
locales.append({
'locale': loc,
'percent': percent,
'total': total,
'translated': translated,
'untranslated': total - translated,
'untranslated_words': untranslated_words
})
output['locales'] = locales
output['created'] = self.created
return output
def _mark_movement(self, data):
"""For each item, converts to a tuple of (movement, item)"""
ret = []
prev_day = None
for i, day in enumerate(data):
if i == 0:
ret.append(('', day))
prev_day = day
continue
if prev_day > day:
item = ('down', day)
elif prev_day < day:
item = ('up', day)
else:
item = ('equal', day)
prev_day = day
ret.append(item)
return ret
def history(self):
self.get_data()
data = self.data
highlight = self.highlight
app = self.app
# Get a list of the locales we'll iterate through
locales = sorted(data[-1]['locales'].keys())
num_days = 14
# Truncate the data to what we want to look at
data = data[-num_days:]
if app:
get_data = lambda x: x['apps'][app]['percent']
else:
get_data = lambda x: x['percent']
hlocales = [loc for loc in locales if loc in highlight]
locales = [loc for loc in locales if loc not in highlight]
output = {}
output['app'] = self.app or 'All'
output['headers'] = [item['created'] for item in data]
output['highlighted'] = sorted(
(loc, self._mark_movement(get_data(day['locales'][loc]) for day in data))
for loc in hlocales
)
output['locales'] = sorted(
(loc, self._mark_movement(get_data(day['locales'].get(loc, {'percent': 0.0})) for day in data))
for loc in locales
)
output['created'] = self.created
return output
| get_data | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.